package com.sckw.payment.task;

import com.alibaba.fastjson2.JSONObject;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.utils.IdWorker;
import com.sckw.payment.dao.KwpSettlementLogisticsMapper;
import com.sckw.payment.dao.KwpSettlementRecordMapper;
import com.sckw.payment.dao.KwpSettlementTradeMapper;
import com.sckw.payment.model.KwpSettlementRecord;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.List;

/**
 * 财务定时任务
 *
 * @author xucaiqin
 * @date 2023-09-05 19:37:00
 */
@Slf4j
@Component
@EnableScheduling
public class FinanceTask {
    @Resource
    private KwpSettlementTradeMapper kwpSettlementTradeMapper;
    @Resource
    private KwpSettlementLogisticsMapper kwpSettlementLogisticsMapper;
    @Resource
    private KwpSettlementRecordMapper kwpSettlementRecordMapper;

    @Scheduled(cron = "0 0 0 ? * *")
//    @Scheduled(cron = "0 0/1 * * * ?")
    public void task() {
        LocalDate now = LocalDate.now().minusDays(1);
        log.info("结算记录归档:{}", now);
        List<KwpSettlementRecord> moneyArchivedDto = kwpSettlementTradeMapper.queryRecord();
        List<KwpSettlementRecord> kwpSettlementRecords = kwpSettlementLogisticsMapper.queryRecord();

        try {
            if (!CollectionUtils.isEmpty(moneyArchivedDto)) {
                for (KwpSettlementRecord kwpSettlementRecord : moneyArchivedDto) {
                    kwpSettlementRecord.setId(new IdWorker(NumberConstant.ONE).nextId());
                    kwpSettlementRecord.setOrderType(2);
                    kwpSettlementRecord.setCreateTime(now);
                }
                log.info("贸易归档：{}", JSONObject.toJSONString(moneyArchivedDto));
                kwpSettlementRecordMapper.insertBatch(moneyArchivedDto);
            }
            if (!CollectionUtils.isEmpty(kwpSettlementRecords)) {
                for (KwpSettlementRecord kwpSettlementRecord : kwpSettlementRecords) {
                    kwpSettlementRecord.setId(new IdWorker(NumberConstant.ONE).nextId());
                    kwpSettlementRecord.setOrderType(1);
                    kwpSettlementRecord.setCreateTime(now);
                }
                log.info("物流归档：{}", JSONObject.toJSONString(kwpSettlementRecords));
                kwpSettlementRecordMapper.insertBatch(kwpSettlementRecords);
            }
        } catch (Exception ex) {
            log.error("结算记录归档异常：{}", ex, ex);
        }
    }
}
