package com.propertyManagement.business.scheduled;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.propertyManagement.business.domain.WxPayRecord;
import com.propertyManagement.business.domain.WxProprietorLedger;
import com.propertyManagement.business.mapper.WxPayRecordMapper;
import com.propertyManagement.business.mapper.WxProprietorLedgerMapper;
import com.propertyManagement.common.core.domain.BaseEntity;
import com.propertyManagement.common.enums.IsEnableType;
import com.propertyManagement.common.enums.LiveBillType;
import com.propertyManagement.common.enums.PayState;
import com.propertyManagement.common.utils.spring.SpringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class RecordWarnTask {

    private final WxPayRecordMapper wxPayRecordMapper;
    private final WxProprietorLedgerMapper wxProprietorLedgerMapper;

    public RecordWarnTask() {
        this.wxProprietorLedgerMapper = SpringUtils.getBean(WxProprietorLedgerMapper.class);
        this.wxPayRecordMapper = SpringUtils.getBean(WxPayRecordMapper.class);
    }

    /**
     * cron：自定义规则
     * 每天凌晨一点执行
     * 功能：检查即将在一个月内到期的支付记录
     */
    @Scheduled(cron = "0 59 23 * * ?")
//    @Scheduled(cron = "0/30 * * * * ?")
    private void checkExpiringPayments() {
        Date currentDate = new Date();

        List<WxProprietorLedger> proprietorLedgerList = wxProprietorLedgerMapper.selectList();
        for (WxProprietorLedger ledger : proprietorLedgerList) {
            WxPayRecord payRecord = wxPayRecordMapper.selectOne(new LambdaQueryWrapper<WxPayRecord>()
                .eq(WxPayRecord::getProprietorId, ledger.getProprietorId())
                .eq(WxPayRecord::getOrderType, LiveBillType.property.getCode())
                .eq(WxPayRecord::getPayState, PayState.YES.getCode())
                .orderByDesc(WxPayRecord::getCreateTime)
                .last("limit 1")
            );
            if (null != payRecord && null != payRecord.getEndTime()) {
                // 3.2 使用Hutool计算日期差
                long daysRemaining = DateUtil.betweenDay(
                    DateUtil.date(payRecord.getEndTime()), // 转换为Hutool DateTime
                    currentDate,
                    false
                );
                // 未过期记录：检查是否在一个月内到期
                if (daysRemaining >= 0 && daysRemaining <= 30) {
                    ledger.setIsWarn(IsEnableType.YES.getCode());
                    wxProprietorLedgerMapper.updateById(ledger);
                }
            }
        }
    }
}
