package com.yd.csf.api.handler;

import com.alibaba.fastjson.JSON;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yd.common.enums.CommonEnum;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.csf.api.service.ApiAgentDetailFycService;
import com.yd.csf.feign.enums.FycSourceTypeEnum;
import com.yd.csf.feign.enums.OprSourceEnum;
import com.yd.csf.service.model.*;
import com.yd.csf.service.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 冷静期定时发送任务处理器 - XXL-Job定时任务执行器
 * 使用@XxlJob注解方式
 */
@Component
@Slf4j
public class CalmSendJobHandler {

    @Resource
    private ICalmTaskService iCalmTaskService;
    @Resource
    private IAgentDetailFycService iAgentDetailFycService;
    @Resource
    private IAgentAccumulatedFycService iAgentAccumulatedFycService;
    @Resource
    private IAgentAccumulatedFycLogService iAgentAccumulatedFycLogService;

    /**
     * XXL-Job任务执行入口方法
     */
    @XxlJob("calmSendJobHandler")
    public void execute() throws Exception {
        //主任务发送时间
        LocalDateTime taskSendTime = LocalDateTime.now();
        // 从XXL-Job参数中获取任务ID
        String param = XxlJobHelper.getJobParam();
        // 记录任务开始日志
        log.info("开始冷静期定时发送任务，参数: {}", param);

        // 解析任务参数（参数为冷静期定时任务业务ID）
        String taskBizId = param;
        // 根据冷静期定时任务业务ID查询冷静期定时任务信息
        CalmTask calmTask = iCalmTaskService.queryOne(taskBizId);
        log.info("根据冷静期定时发送任务业务ID查询冷静期定时任务信息: {}: " + JSON.toJSONString(calmTask));

        // 检查冷静期定时任务是否存在
        if (Objects.isNull(calmTask)) {
            // 记录错误并返回
            XxlJobHelper.log("冷静期定时发送任务不存在: " + taskBizId);
            XxlJobHelper.handleFail("冷静期定时发送任务不存在");
            return;
        }

        //更新保单冷静期定时任务对象字段
        //执行状态: 2-已执行
        calmTask.setExecutionStatus("2");
        iCalmTaskService.saveOrUpdate(calmTask);

        //更新保单冷静期定时任务对应的积分明细对象字段
        //查询积分明细
        AgentDetailFyc agentDetailFyc = iAgentDetailFycService.queryOne(calmTask.getDetailFycBizId());
        if (agentDetailFyc != null) {
            //状态：生效
            agentDetailFyc.setStatus(1);
            iAgentDetailFycService.saveOrUpdate(agentDetailFyc);
        }

        //更新积分总表的字段（此时积分都已经生效）
        //查询积分总表对象 弄好了，差一个每月1号晋升职级定时任务未开发，还有个基本法要根据保单生效日所在月对应的积分总表操作日志记录表来找出对应月的最大职级（晋升职级累计积分）（少个积分总表操作日志记录表）
        AgentAccumulatedFyc agentAccumulatedFyc = iAgentAccumulatedFycService.queryOne(calmTask.getBrokerBizId());
        if (agentAccumulatedFyc != null) {
            //未生效累计积分（不限业务场景）= 未生效累计积分（不限业务场景） - 增量积分
            BigDecimal noEffect = agentAccumulatedFyc.getNoEffect().subtract(calmTask.getFyc());
            agentAccumulatedFyc.setNoEffect(noEffect.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : noEffect);
            //已生效累计积分（不限业务场景） = 已生效累计积分（不限业务场景） + 增量积分
            BigDecimal effect = agentAccumulatedFyc.getEffect().add(calmTask.getFyc());
            agentAccumulatedFyc.setEffect(effect);
            //累计积分 = 未生效累计积分 + 已生效累计积分
            agentAccumulatedFyc.setTotalFyc(agentAccumulatedFyc.getNoEffect().add(agentAccumulatedFyc.getEffect()));
            if (calmTask.getFortunePeriod() == 1) {
                //首期
                //已生效累计首期佣金积分值（佣金场景） = 已生效累计首期佣金积分值（佣金场景） + 增量积分
                BigDecimal firstCommission = agentAccumulatedFyc.getFirstCommission().add(calmTask.getFyc());
                agentAccumulatedFyc.setFirstCommission(firstCommission);
                //未生效累计首期佣金积分值（佣金场景）= 未生效累计首期佣金积分值（佣金场景）- 增量积分
                BigDecimal noFirstCommission = agentAccumulatedFyc.getNoFirstCommission().subtract(calmTask.getFyc());
                agentAccumulatedFyc.setNoFirstCommission(noFirstCommission.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : noFirstCommission);
            }else {
                //非首期
                //已生效累计非首期佣金积分值（佣金场景） = 已生效累计非首期佣金积分值（佣金场景） + 增量积分
                BigDecimal ryc = agentAccumulatedFyc.getRyc().add(calmTask.getFyc());
                agentAccumulatedFyc.setRyc(ryc);
                //未生效累计非首期佣金积分值（佣金场景）= 未生效累计非首期佣金积分值（佣金场景）- 增量积分
                BigDecimal noRyc = agentAccumulatedFyc.getNoRyc().subtract(calmTask.getFyc());
                agentAccumulatedFyc.setNoRyc(noRyc.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : noRyc);
            }
            //晋升职级累计积分 = 已生效累计积分 - 已生效累计非首期佣金积分值
            BigDecimal promotion = agentAccumulatedFyc.getEffect().subtract(agentAccumulatedFyc.getRyc());
            agentAccumulatedFyc.setPromotion(promotion.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : promotion);
            //最后计算日期，记录最后一次计算累计FYC的日期
            agentAccumulatedFyc.setLastCalcDate(LocalDateTime.now());
            iAgentAccumulatedFycService.saveOrUpdate(agentAccumulatedFyc);

            //新增积分总表日志表
            AgentAccumulatedFycLog log = new AgentAccumulatedFycLog();
            BeanUtils.copyProperties(agentAccumulatedFyc,log);
            log.setId(null);
            log.setFycBizId(agentAccumulatedFyc.getFycBizId());
            log.setFycLogBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_AGENT_ACCUMULATED_FYC_LOG.getCode()));
            //操作来源枚举-解冻
            log.setSourceType(OprSourceEnum.CALM_TASK_FREEZE.getItemValue());
            iAgentAccumulatedFycLogService.saveOrUpdate(log);
        }


    }


}