package com.qs.mp.web.controller.api.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qs.mp.admin.domain.Goods;
import com.qs.mp.admin.domain.GoodsSku;
import com.qs.mp.admin.domain.PrizeRecovery;
import com.qs.mp.admin.service.IGoodsService;
import com.qs.mp.admin.service.IGoodsSkuService;
import com.qs.mp.admin.service.IPrizeRecoveryService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.core.redis.RedisCache;
import com.qs.mp.common.enums.PrizeStorageInTypeEnum;
import com.qs.mp.common.enums.PrizeStorageStatusEnum;
import com.qs.mp.common.utils.StringUtils;
import com.qs.mp.framework.redis.RedisKey;
import com.qs.mp.user.domain.UserExchangeOrder;
import com.qs.mp.user.domain.UserPrizeStorage;
import com.qs.mp.user.domain.param.UserPrizeRecoveryCreateParam;
import com.qs.mp.user.domain.vo.PrizeRecoverySettleVO;
import com.qs.mp.user.domain.vo.TicketOrderSettleVO;
import com.qs.mp.user.service.IUserExchangeOrderService;
import com.qs.mp.user.service.IUserPrizeStorageService;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.*;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Cup
 * @date 2022/5/25
 */
@RestController
@RequestMapping("/api/v1/mp/user/prize/recovery")
@Api(tags = "用户奖品回收相关接口")
public class UserPrizeRecoveryController extends BaseApiController {

    @Autowired
    private IPrizeRecoveryService prizeRecoveryService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IGoodsSkuService goodsSkuService;

    @Autowired
    private IUserPrizeStorageService userPrizeStorageService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IUserExchangeOrderService userExchangeOrderService;

    @PostMapping("/list")
    @ApiOperation("已回收列表")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = PrizeRecovery.class)
    )
    public TableDataInfo list() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        startPage();
        List<PrizeRecovery> list = prizeRecoveryService.list(new LambdaQueryWrapper<PrizeRecovery>().eq(PrizeRecovery::getUserId, userId).orderByDesc(PrizeRecovery::getCreatedTime));
        return getDataTable(list);
    }


    @PostMapping("/settle")
    @ApiOperation("回收奖品结算页面")
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = PrizeRecoverySettleVO.class)
    )
    public AjaxResult settle(@RequestBody UserPrizeRecoveryCreateParam param) {
        if (StringUtils.isBlank(param.getStorageId()) || Objects.isNull(param.getGoodsId())) {
            return AjaxResult.error("参数错误");
        }

        Long userId = SecurityUtils.getLoginUser().getUserId();

        PrizeRecoverySettleVO settleVO = new PrizeRecoverySettleVO();

        UserPrizeStorage userPrizeStorage = userPrizeStorageService.getOne(new LambdaQueryWrapper<UserPrizeStorage>()
                .eq(UserPrizeStorage::getStorageId, param.getStorageId())
                .eq(UserPrizeStorage::getStatus, PrizeStorageStatusEnum.NOT_DISTRIBUTED)
                .eq(UserPrizeStorage::getUserId, userId));
        if (Objects.isNull(userPrizeStorage)) {
            return AjaxResult.error("奖品不存在");
        }

        if (userPrizeStorage.getGoodsNum() < param.getNum() || param.getNum() <= 0) {
            return AjaxResult.error("奖品数量非法");
        }

        if (!PrizeStorageInTypeEnum.TICKET_CASHED.equals(userPrizeStorage.getInType()) && !PrizeStorageInTypeEnum.COIN_EXCHANGE.equals(userPrizeStorage.getInType())) {
            return AjaxResult.error("当前奖品类型不支持回收");
        }

        // 回收折扣
        BigDecimal discountRate = new BigDecimal(70);
        // 兑换价格
        Integer exchangePrice = 0;

        if (PrizeStorageInTypeEnum.COIN_EXCHANGE.equals(userPrizeStorage.getInType())) {
            UserExchangeOrder userExchangeOrder = userExchangeOrderService.getOne(new LambdaQueryWrapper<UserExchangeOrder>().eq(UserExchangeOrder::getOrderId, userPrizeStorage.getRefId()));
            if (Objects.isNull(userExchangeOrder)) {
                return AjaxResult.error("无兑换订单信息");
            }
            GoodsSku goodsSku = null;
            if (Objects.nonNull(userExchangeOrder.getSkuId())) {
                goodsSku = goodsSkuService.getById(userExchangeOrder.getSkuId());
            }
            if (Objects.nonNull(goodsSku)) {
                discountRate = goodsSku.getDiscountRate();
            } else {
                Goods goods = goodsService.getById(userPrizeStorage.getGoodsId());
                discountRate = goods.getDiscountRate();
            }
            exchangePrice = BigDecimal.valueOf(userExchangeOrder.getOrderCoin()).divide(BigDecimal.valueOf(userExchangeOrder.getNum()),0, RoundingMode.HALF_UP).intValue();
        } else if (PrizeStorageInTypeEnum.TICKET_CASHED.equals(userPrizeStorage.getInType())) {
            Goods goods = goodsService.getById(userPrizeStorage.getGoodsId());
            if (Objects.isNull(goods)) {
                return AjaxResult.error("商品信息有误");
            }
            discountRate = goods.getDiscountRate();
            exchangePrice = goods.getExchangePrice();
        }

        int returnNum = BigDecimal.valueOf((long) exchangePrice * param.getNum()).multiply(discountRate).divide(BigDecimal.valueOf(100),0, RoundingMode.HALF_UP).intValue();

        settleVO.setReturnCoin(returnNum);
        // 封装结算对象
        settleVO.setExchangePrice(exchangePrice);
        settleVO.setStorageId(userPrizeStorage.getStorageId());
        settleVO.setGoodsId(userPrizeStorage.getGoodsId());
        settleVO.setTitle(userPrizeStorage.getTitle());
        settleVO.setPicUrl(userPrizeStorage.getPicUrl());
        settleVO.setSkuId(param.getSkuId());
        settleVO.setProperties(param.getProperties());
        settleVO.setNum(param.getNum());
        settleVO.setGoodsNum(userPrizeStorage.getGoodsNum());
        settleVO.setDiscountRate(discountRate);

        // 缓存回收结算对象
        redisCache.setCacheObject(RedisKey.build(RedisKey.USER_PRIZE_RECOVERY_KEY, userId), settleVO, 10, TimeUnit.MINUTES);
        return AjaxResult.success(settleVO);
    }

    @PostMapping("/submit")
    @ApiOperation("提交回收")
    public AjaxResult submit() {
        Long userId = SecurityUtils.getLoginUser().getUserId();

        PrizeRecoverySettleVO settleVO = redisCache.getCacheObject(RedisKey.build(RedisKey.USER_PRIZE_RECOVERY_KEY, userId));
        if (null == settleVO) {
            return AjaxResult.error("订单已过期，请重新下单");
        }

        prizeRecoveryService.submitRecovery(userId, settleVO);

        // 清除缓存的回收订单
        redisCache.deleteObject(RedisKey.build(RedisKey.USER_PRIZE_RECOVERY_KEY, userId));

        return AjaxResult.success();
    }

}
