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.enums.RuleItemEnum;
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);
        }

        // 更新积分总表的字段（此时积分都已经生效）
        AgentAccumulatedFyc agentAccumulatedFyc = iAgentAccumulatedFycService.queryOne(calmTask.getBrokerBizId());
        if (agentAccumulatedFyc != null) {
            // 安全获取任务佣金增量值，若为 null 则用 0 代替
            BigDecimal fycValue = calmTask.getAfterFyc() == null ? BigDecimal.ZERO : calmTask.getAfterFyc();

            // 安全获取原有字段值，若为 null 则视为 0
            BigDecimal noEffectOld = agentAccumulatedFyc.getNoEffect() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getNoEffect();
            BigDecimal effectOld = agentAccumulatedFyc.getEffect() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getEffect();
            BigDecimal firstCommissionOld = agentAccumulatedFyc.getFirstCommission() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getFirstCommission();
            BigDecimal noFirstCommissionOld = agentAccumulatedFyc.getNoFirstCommission() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getNoFirstCommission();
            BigDecimal rycOld = agentAccumulatedFyc.getRyc() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getRyc();
            BigDecimal noRycOld = agentAccumulatedFyc.getNoRyc() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getNoRyc();
            BigDecimal firstSalesCommissionOld = agentAccumulatedFyc.getFirstSalesCommission() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getFirstSalesCommission();
            BigDecimal noFirstSalesCommissionOld = agentAccumulatedFyc.getNoFirstSalesCommission() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getNoFirstSalesCommission();

            //未生效累计积分（不限业务场景）= 未生效累计积分（不限业务场景） - 增量积分
            BigDecimal noEffect = noEffectOld.subtract(fycValue);
            agentAccumulatedFyc.setNoEffect(noEffect.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : noEffect);
            //已生效累计积分（不限业务场景） = 已生效累计积分（不限业务场景） + 增量积分
            BigDecimal effect = effectOld.add(fycValue);
            agentAccumulatedFyc.setEffect(effect);
            //累计积分 = 未生效累计积分 + 已生效累计积分
            agentAccumulatedFyc.setTotalFyc(agentAccumulatedFyc.getNoEffect().add(agentAccumulatedFyc.getEffect()));

            if (calmTask.getFortunePeriod() != null && calmTask.getFortunePeriod() == 1) {
                //首期
                //已生效累计首期佣金积分值（佣金场景） = 已生效累计首期佣金积分值（佣金场景） + 增量积分
                BigDecimal firstCommission = firstCommissionOld.add(fycValue);
                agentAccumulatedFyc.setFirstCommission(firstCommission);
                //未生效累计首期佣金积分值（佣金场景）= 未生效累计首期佣金积分值（佣金场景）- 增量积分
                BigDecimal noFirstCommission = noFirstCommissionOld.subtract(fycValue);
                agentAccumulatedFyc.setNoFirstCommission(noFirstCommission.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : noFirstCommission);

                if (RuleItemEnum.SALES.getRuleItemBizId().equals(calmTask.getRuleItemBizId())) {
                    //销售佣金项目
                    //已生效累计首期销售佣金积分值（销售佣金场景（佣金场景的其中一个）） = 已生效累计首期销售佣金积分值（销售佣金场景（佣金场景的其中一个）） + 增量积分
                    BigDecimal firstSalesCommission = firstSalesCommissionOld.add(fycValue);
                    agentAccumulatedFyc.setFirstSalesCommission(firstSalesCommission);
                    //未生效累计首期销售佣金积分值（销售佣金场景（佣金场景的其中一个））= 未生效累计首期销售佣金积分值（销售佣金场景（佣金场景的其中一个））- 增量积分
                    BigDecimal noFirstSalesCommission = noFirstSalesCommissionOld.subtract(fycValue);
                    agentAccumulatedFyc.setNoFirstSalesCommission(noFirstSalesCommission.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : noFirstSalesCommission);
                }
            } else {
                //非首期
                //已生效累计非首期佣金积分值（佣金场景） = 已生效累计非首期佣金积分值（佣金场景） + 增量积分
                BigDecimal ryc = rycOld.add(fycValue);
                agentAccumulatedFyc.setRyc(ryc);
                //未生效累计非首期佣金积分值（佣金场景）= 未生效累计非首期佣金积分值（佣金场景）- 增量积分
                BigDecimal noRyc = noRycOld.subtract(fycValue);
                agentAccumulatedFyc.setNoRyc(noRyc.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : noRyc);
            }
            //晋升职级累计积分 = 已生效累计积分 - 已生效累计非首期佣金积分值
            // 注意：此处 effect 和 ryc 已更新，使用更新后的值，但仍需判空保护
            BigDecimal effectAfter = agentAccumulatedFyc.getEffect() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getEffect();
            BigDecimal rycAfter = agentAccumulatedFyc.getRyc() == null ? BigDecimal.ZERO : agentAccumulatedFyc.getRyc();
            BigDecimal promotion = effectAfter.subtract(rycAfter);
            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());
            log.setCreateTime(LocalDateTime.now());
            log.setUpdateTime(LocalDateTime.now());
            iAgentAccumulatedFycLogService.saveOrUpdate(log);
        }


    }


}