package cn.iocoder.yudao.module.system.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyContractDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyContractMapper;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class ElderContractUpdateJob implements JobHandler {
    private final static Logger logger = LoggerFactory.getLogger(ElderContractUpdateJob.class);

    @Resource
    private ElderlyContractMapper elderlyContractMapper;

    @Override
    @TenantJob
    public String execute(String param) throws Exception {
        Long tenantId = TenantContextHolder.getTenantId();
        logger.info("租户{},=====================合同更新===================", tenantId);
        updateElderContractStatus(tenantId);
        return String.format("租户{}合同更新情况", tenantId);
    }

    private void updateElderContractStatus(Long tenantId){
        LocalDate nowLocalDate = LocalDate.now();

        // 1) 修复：将“进行中(1)”但日期不匹配的合同纠正为“未开始(2)”或“过期(0)”
        //    使用批量 SQL，避免逐条 update
        Date nowDate = Date.from(nowLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        int fixToNotStartedCount = elderlyContractMapper.batchUpdateStatusToNotStarted(tenantId, nowDate);
        int fixToExpiredCount = elderlyContractMapper.batchUpdateStatusToExpired(tenantId, nowDate);
        if (fixToNotStartedCount > 0 || fixToExpiredCount > 0) {
            logger.info("租户{}合同状态修复：进行中->未开始 {} 条，进行中->过期 {} 条", tenantId, fixToNotStartedCount, fixToExpiredCount);
        }

        // 2) 原有逻辑：到期的旧合同置为过期(0)，并将符合条件的未开始合同置为进行中(1)
        //    这里先重新查询一次进行中合同（避免上一步修复后状态已变化造成遗漏/误判）
        List<ElderlyContractDO> elderlyContractDOList = elderlyContractMapper.selectList(new LambdaQueryWrapperX<ElderlyContractDO>()
                .eq(ElderlyContractDO::getTenantId, tenantId)
                .eq(ElderlyContractDO::getStatus, 1));
        for (ElderlyContractDO elderlyContractDO : elderlyContractDOList) {
            LocalDate expireLocalDate = elderlyContractDO.getExpireTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
            // 判断合同今天是否是到期时间
            if(expireLocalDate.isBefore(nowLocalDate)){   // 到期当日不算过期，次日才算
                // 查询未开始的合同（同一老人），并且截止时间 >= 今天（意味着该合同今天仍有效或未来有效）
                List<ElderlyContractDO> futureContractList = elderlyContractMapper.selectList(new LambdaQueryWrapperX<ElderlyContractDO>()
                        .eq(ElderlyContractDO::getElderId, elderlyContractDO.getElderId())
                        .eq(ElderlyContractDO::getStatus, 2)
                        .ge(ElderlyContractDO::getExpireTime, nowLocalDate));
                if(CollectionUtil.isEmpty(futureContractList)){
                    continue;
                }
                ElderlyContractDO futureContract = futureContractList.get(0);
                // 更新新合同状态
                futureContract.setStatus(1);
                // 更新旧合同状态
                elderlyContractDO.setStatus(0);
                elderlyContractMapper.updateById(elderlyContractDO);
                elderlyContractMapper.updateById(futureContract);
            }
        }
    }
}
