package com.gree.mall.miniapp.logic.acitivy;

import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.miniapp.bean.promotion.PromotionLuckDrawExchangeDetail;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.PromotionLuckDrawCouponCodeService;
import com.gree.mall.miniapp.plus.service.PromotionLuckDrawCouponService;
import com.gree.mall.miniapp.plus.service.PromotionLuckDrawService;
import com.gree.mall.miniapp.plus.service.UserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class PromotionLuckDrawLogic {

    @Autowired
    PromotionLuckDrawService promotionLuckDrawService;
    @Autowired
    PromotionLuckDrawCouponService promotionLuckDrawCouponService;
    @Autowired
    PromotionLuckDrawCouponCodeService promotionLuckDrawCouponCodeService;
    @Autowired
    UserCouponService userCouponService;
    @Autowired
    CommonLogic commonLogic;

    /**
     * 兑换优惠券
     * @param code
     * @param request
     */
    @Transactional
    public PromotionLuckDrawExchangeDetail exchange(String code, HttpServletRequest request){

        String userCouponId = "draw"+IdWorker.getIdStr();

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        User user = currentCompanyWechat.getUser();
        if(user.getExchangeNum() >= 10){
            throw new RemoteServiceException("您错误兑换次数已超上限，已被禁止兑换");
        }
        PromotionLuckDrawCouponCode promotionLuckDrawCouponCode = promotionLuckDrawCouponCodeService.lambdaQuery().eq(PromotionLuckDrawCouponCode::getCode, code).one();
        if(promotionLuckDrawCouponCode == null){
           user.setExchangeNum(user.getExchangeNum() + 1);
           user.updateById();
           throw new RemoteServiceException("兑换码错误，请重新兑换");
        }
        long curTime = new Date().getTime();
        if(promotionLuckDrawCouponCode.getEndTime().getTime() < curTime || promotionLuckDrawCouponCode.getStartTime().getTime() > curTime
                || promotionLuckDrawCouponCode.getStatus()){
            throw new RemoteServiceException("兑换码无效");
        }
        //本次活动
        PromotionLuckDraw promotionLuckDraw = promotionLuckDrawService.getById(promotionLuckDrawCouponCode.getPromotionLuckDrawId());
        if(promotionLuckDraw == null || !promotionLuckDraw.getStatus() || promotionLuckDraw.getStartTime().getTime() > curTime
                || promotionLuckDraw.getEndTime().getTime() < curTime){
            throw new RemoteServiceException("本次活动已取消");
        }
        //兑换成功
        promotionLuckDrawCouponCode.setUserNickName(user.getNickName());
        promotionLuckDrawCouponCode.setUserId(user.getUserId());
        promotionLuckDrawCouponCode.setUserMobile(user.getMobile());
        promotionLuckDrawCouponCode.setUserExchangeTime(new Date());
        promotionLuckDrawCouponCode.setStatus(true);
        promotionLuckDrawCouponCode.setUserCouponId(userCouponId);
        promotionLuckDrawCouponCode.updateById();

        //发放优惠券
        PromotionLuckDrawCoupon promotionLuckDrawCoupon = promotionLuckDrawCouponService.getById(promotionLuckDrawCouponCode.getPromotionLuckDrawCouponId());
        if(promotionLuckDrawCoupon == null){
            throw new RemoteServiceException("兑换失败");
        }
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setId(userCouponId);
        userCoupon.setUserId(currentCompanyWechat.getUserId());
        userCoupon.setCouponId(promotionLuckDrawCoupon.getId());
        userCoupon.setCouponName(promotionLuckDrawCoupon.getCouponName());
        userCoupon.setCouponValue(promotionLuckDrawCoupon.getDiscountAmount());
        userCoupon.setCouponType(promotionLuckDrawCoupon.getCouponType());
        userCoupon.setReceiveTime(new Date());
        userCoupon.setActiveStartTime(promotionLuckDraw.getCouponStartTime());
        userCoupon.setActiveEndTime(promotionLuckDraw.getCouponEndTime());
        userCoupon.setOrderAmount(promotionLuckDrawCoupon.getOrderLimitAmount());
        userCoupon.setReceivePlatform("抽奖活动兑换");
        userCoupon.setTransferType(false);
        userCoupon.setLeftShareTimes(0);
        userCoupon.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
        userCoupon.setCompanyName(currentCompanyWechat.getCompanyName());
        userCoupon.insert();

        return this.detail(code);
    }


    /**
     * 兑换记录
     */
    public IPage<PromotionLuckDrawCouponCode> list(Integer pageNum,Integer pageSize,HttpServletRequest request){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        IPage<PromotionLuckDrawCouponCode> list = promotionLuckDrawCouponCodeService.lambdaQuery()
                .eq(PromotionLuckDrawCouponCode::getUserId, currentCompanyWechat.getUserId())
                .orderByDesc(PromotionLuckDrawCouponCode::getUserExchangeTime).page(new Page<>(pageNum,pageSize));
        return list;
    }

    /**
     * 兑换详情
     * @param code
     * @return
     */
    public PromotionLuckDrawExchangeDetail detail(String code){
        PromotionLuckDrawCouponCode promotionLuckDrawCouponCode = promotionLuckDrawCouponCodeService.lambdaQuery().eq(PromotionLuckDrawCouponCode::getCode, code).one();
        PromotionLuckDraw promotionLuckDraw = promotionLuckDrawService.getById(promotionLuckDrawCouponCode.getPromotionLuckDrawId());
        PromotionLuckDrawCoupon promotionLuckDrawCoupon = promotionLuckDrawCouponService.getById(promotionLuckDrawCouponCode.getPromotionLuckDrawCouponId());
        //返回详情
        PromotionLuckDrawExchangeDetail detail = new PromotionLuckDrawExchangeDetail();
        detail.setName(promotionLuckDraw.getName());
        detail.setCouponName(promotionLuckDrawCoupon.getCouponName());
        detail.setStartTime(promotionLuckDraw.getStartTime());
        detail.setEndTime(promotionLuckDraw.getEndTime());
        detail.setUseStartTime(promotionLuckDraw.getCouponStartTime());
        detail.setUseEndTime(promotionLuckDraw.getCouponEndTime());
        detail.setUseRemark(promotionLuckDrawCoupon.getUseRemark());
        detail.setRemark(promotionLuckDraw.getRemark());
        detail.setStatus(promotionLuckDrawCouponCode.getStatus());
        detail.setUse(StringUtils.isNotBlank(promotionLuckDrawCouponCode.getOrderId()));
        detail.setUseTime(promotionLuckDrawCouponCode.getUserUseTime());
        detail.setUserExchangeTime(promotionLuckDrawCouponCode.getUserExchangeTime());
        detail.setOrderLimitAmount(promotionLuckDrawCoupon.getOrderLimitAmount());
        detail.setCouponType(promotionLuckDrawCoupon.getCouponType());
        return detail;
    }


    /**
     * 回写抽奖活动
     */
    public void updatePromotionLuckDrawCode(OrderInfo orderInfo){
        try {
            String userCouponId = orderInfo.getUserCouponId();
            if (StringUtils.isBlank(userCouponId)) {
                return;
            }
            PromotionLuckDrawCouponCode code = promotionLuckDrawCouponCodeService.lambdaQuery().eq(PromotionLuckDrawCouponCode::getUserCouponId, userCouponId).one();
            if (code == null) {
                return;
            }
            code.setUserUseTime(orderInfo.getPayTime());
            code.setOrderId(orderInfo.getOrderId());
            code.setUserNickName(orderInfo.getUserName());
            code.updateById();
        }catch(Exception e){
            log.error("【订单支付回写抽奖活动信息失败】",e);
        }
    }


}
