package com.qs.mp.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qs.mp.admin.domain.Coupon;
import com.qs.mp.admin.service.ICouponService;
import com.qs.mp.channel.domain.ChannelCouponVerifyLog;
import com.qs.mp.channel.domain.ChannelMoneyLog;
import com.qs.mp.channel.mapper.ChannelCouponVerifyLogMapper;
import com.qs.mp.channel.service.IChannelCouponVerifyLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.mp.channel.service.IChannelMoneyLogService;
import com.qs.mp.common.enums.ChannelMoneyEnum;
import com.qs.mp.common.enums.CouponDiscountTypeEnum;
import com.qs.mp.common.enums.CouponSettleStatusEnum;
import com.qs.mp.common.enums.CouponStatusEnum;
import com.qs.mp.common.enums.UserCouponStatusEnum;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.user.domain.UserCoupon;
import com.qs.mp.user.service.IUserCouponService;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * <p>
 * 渠道优惠券核销流水 服务实现类
 * </p>
 *
 * @author quanshu
 * @since 2022-03-21
 */
@Service
public class ChannelCouponVerifyLogServiceImpl extends ServiceImpl<ChannelCouponVerifyLogMapper, ChannelCouponVerifyLog> implements IChannelCouponVerifyLogService {

  protected final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

  @Autowired
  private ICouponService couponService;

  @Autowired
  private IUserCouponService userCouponService;

  @Autowired
  private IChannelMoneyLogService channelMoneyLogService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void verify(Long channelId, UserCoupon userCoupon) {
    Date verifyDate = new Date();
    // 核销券
    boolean updateRst = userCouponService.update(new LambdaUpdateWrapper<UserCoupon>()
        .set(UserCoupon::getStatus, UserCouponStatusEnum.USED)
            .set(UserCoupon::getVerifyTime, verifyDate)
        .eq(UserCoupon::getId, userCoupon.getId())
        .eq(UserCoupon::getStatus, UserCouponStatusEnum.UNUSED));
    Assert.isTrue(updateRst, "经销商核销券时，券状态更新失败。userCouponId:" + userCoupon.getId());
    Coupon coupon = couponService.getById(userCoupon.getCouponId());

    // 记录核销日志
    ChannelCouponVerifyLog verifyLog = new ChannelCouponVerifyLog();
    verifyLog.setChannelId(channelId);
    verifyLog.setUserCouponId(userCoupon.getId());
    verifyLog.setVerifyCode(userCoupon.getVerifyCode());
    verifyLog.setTitle(coupon.getTitle());
    verifyLog.setDiscountType(coupon.getDiscountType());
    verifyLog.setDiscount(coupon.getDiscount());
    verifyLog.setDistributeTime(userCoupon.getCreatedTime());
    verifyLog.setValidStart(userCoupon.getValidStart());
    verifyLog.setValidEnd(userCoupon.getValidEnd());
    verifyLog.setVerifyTime(verifyDate);
    verifyLog.setSettleStatus(CouponSettleStatusEnum.FINISHED);
    save(verifyLog);

    if (coupon.getDiscountType() == CouponDiscountTypeEnum.MONEY_OFF){
      int logMoney = coupon.getDiscount() * (100 - coupon.getChannelSharedRate()) / 100;
      if (logMoney == 0) {
        LogUtil.warn(logger, "优惠券核销结算金额为0，忽略。userCouponId:{0}", userCoupon.getId());
      } else {
        // 结算
        ChannelMoneyLog moneyLog = new ChannelMoneyLog();
        moneyLog.setChannelId(channelId);
        moneyLog.setType(ChannelMoneyEnum.COUPON);
        moneyLog.setLogMoney(logMoney);
        moneyLog.setLogText("券码:" + userCoupon.getVerifyCode());
        moneyLog.setBizTime(new Date());
        moneyLog.setRefId(String.valueOf(verifyLog.getId()));
        channelMoneyLogService.changeMoney(moneyLog);
      }
    } else {
      LogUtil.warn(logger, "优惠券核销结算，类型非代金券，忽略。userCouponId:{0}", userCoupon.getId());
    }
  }

  @Override
  public Integer sumDisCountByQueryWrapper(QueryWrapper<ChannelCouponVerifyLog> queryWrapper) {
    return getBaseMapper().sumDisCountByQueryWrapper(queryWrapper);
  }
}
