package vip.xiaonuo.biz.modular.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import vip.xiaonuo.biz.core.enums.FundChangeTypeEnum;
import vip.xiaonuo.biz.modular.couponrecord.service.BizCouponRecordService;
import vip.xiaonuo.biz.modular.rebaterecord.entity.BizRebateRecord;
import vip.xiaonuo.biz.modular.rebaterecord.service.BizRebateRecordService;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.mapper.BizUserMapper;
import vip.xiaonuo.biz.modular.userfundchangerecord.entity.BizUserFundChangeRecord;
import vip.xiaonuo.biz.modular.userfundchangerecord.service.BizUserFundChangeRecordService;
import vip.xiaonuo.common.timer.CommonTimerTaskRunner;
import vip.xiaonuo.dev.api.DevConfigApi;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author wulei
 * @date 2025/2/8
 * @Version 1.0
 * @Description 代金券生效定时任务
 */
@Slf4j
@Component
public class rebateEffectTask implements CommonTimerTaskRunner {

    @Resource
    private DevConfigApi devConfigApi;

    @Resource
    private BizRebateRecordService bizRebateRecordService;
    @Resource
    private BizUserMapper bizUserMapper;
    @Resource
    private BizUserFundChangeRecordService bizUserFundChangeRecordService;
    // 代金券生效期限配置
    private static final String REBATE_EFFECTIVE_DATE = "rebateEffectiveDate";
    @Resource
    private PlatformTransactionManager transactionManager;

    @Override
    public void action(String extJson) {
        log.info("代金券生效定时任务正在执行==================");
        TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            // 获取代金券生效期限配置
            String date = devConfigApi.getValueByKey(REBATE_EFFECTIVE_DATE);
            DateTime daysAgo = DateUtil.offsetDay(DateUtil.date(), -Integer.parseInt(date));
            log.info("代金券生效时间：{}", daysAgo);
            // 查询未生效且代金券创建时间距离当前生效期限的代金券
            List<BizRebateRecord> list = bizRebateRecordService.list(new LambdaQueryWrapper<BizRebateRecord>()
                    .eq(BizRebateRecord::getRebateStatus, "1")
                    .le(BizRebateRecord::getCreateTime, daysAgo));
            for (BizRebateRecord bizRebateRecord : list) {
                bizRebateRecord.setRebateStatus("2");
                bizRebateRecordService.updateById(bizRebateRecord);
                // 更新用于代金券余额数据
                BizUser bizUser = bizUserMapper.selectById(bizRebateRecord.getRecommendUserId());
                if (ObjectUtil.isNotNull(bizUser)) {
                    BigDecimal oldVoucherBalance = bizUser.getVoucherBalance();
                    BigDecimal newVoucherBalance = oldVoucherBalance.add(bizRebateRecord.getRebateAmount());
                    bizUser.setVoucherBalance(newVoucherBalance);
                    bizUserMapper.updateById(bizUser);
                    // 记录用户账户资金变动记录
                    BizUserFundChangeRecord bizUserFundChangeRecord = new BizUserFundChangeRecord();
                    bizUserFundChangeRecord.setChangeType(FundChangeTypeEnum.VOUCHER_EFFECT.getValue());
                    bizUserFundChangeRecord.setUserId(bizRebateRecord.getRecommendUserId());
                    bizUserFundChangeRecord.setOldAccountBalance(bizUser.getAccountBalance());
                    bizUserFundChangeRecord.setNewAccountBalance(bizUser.getAccountBalance());
                    bizUserFundChangeRecord.setOldVoucherBalance(oldVoucherBalance);
                    bizUserFundChangeRecord.setNewVoucherBalance(newVoucherBalance);
                    bizUserFundChangeRecordService.save(bizUserFundChangeRecord);
                }
            }
            //手动提交事务
            transactionManager.commit(transactionStatus);
            log.info("代金券生效定时任务执行完毕=================");
        } catch (Exception e) {
            e.printStackTrace();
            transactionManager.rollback(transactionStatus);
            log.error("代金券生效定时任务执行异常=================");
        }
    }
}
