package com.izouma.nineth.task;

import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.domain.TransferMoneyInfo;
import com.izouma.nineth.dto.DivMoneyDTO;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.lock.RedisLockable;
import com.izouma.nineth.repo.TransferMoneyInfoRepo;
import com.izouma.nineth.service.DivMoneyExecuteService;
import com.izouma.nineth.service.DivMoneyService;
import com.izouma.nineth.service.IkudotpayService;
import com.izouma.nineth.service.SandpayService;
import com.izouma.nineth.service.pay.UniformPayConstants;
import com.izouma.nineth.utils.DateTimeUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 分账定时任务
 *
 */
@Service
@AllArgsConstructor
@Slf4j
public class DivMoneyServiceTask {


    private DivMoneyService divMoneyService;

    private DivMoneyExecuteService divMoneyExecuteService;

    private TransferMoneyInfoRepo transferMoneyInfoRepo;


    /**
     * 自动分账任务
     * TODO 暂时是人工分账
     */
    //@Scheduled(cron="0 0 12 * * ?")
    @RedisLockable(prefix= RedisKeys.AUTO_TASK_LOCK, key="'batchDivMoney'")
    public void batchDivMoney(){
        PageQuery pageQuery = new PageQuery();
        //D+1模式，分账日期为前一天的数据
        LocalDateTime divDate = LocalDateTime.now().minusDays(1);
        //查询两天的数据，防止未处理成功，由第二天的定时任务处理
        LocalDateTime startTime = divDate.minusDays(2);
        LocalDateTime endTime = divDate;
        String startStr = DateTimeUtils.format(startTime, DateTimeUtils.DATE_TIME_FORMAT);
        String endStr = DateTimeUtils.format(endTime, DateTimeUtils.DATE_TIME_FORMAT);

        final String batchNo = DateTimeFormatter.ofPattern("yyyyMMddHHmm").format(LocalDateTime.now());
        List<String> createdAtRange = Arrays.asList(startStr, endStr);
        pageQuery.getQuery().put("createdAt", createdAtRange);
        List<DivMoneyDTO> dataList = divMoneyService.getCheckData(pageQuery);
        log.info("自动分账数据，批次：{}， 时间范围：{}， 数量：{} ",batchNo, createdAtRange, dataList.size());
        dataList.forEach(divMoneyDTO -> {
            try {
                Long divMoneyId = Long.valueOf(divMoneyDTO.getId());
                divMoneyExecuteService.executeDivMoney(divMoneyId, "自动分润", batchNo);
            }catch(Exception e){
                log.error("分账错误，分账ID:" + divMoneyDTO.getId() + ",原因：" +  e.getMessage());
            }

        });
    }


    /**
     * 定时查询交易中的数据
     *
     */
    @Scheduled(cron="0 0 * * * ?")
    public void checkTransferResultTask(){
        //查找待处理的数据
        List<TransferMoneyInfo> transferMoneyInfoList = transferMoneyInfoRepo.findProcessingList();
        if(transferMoneyInfoList.size() > 0){
            log.info("待检查转账中的交易数量：" + transferMoneyInfoList.size());
        }
        transferMoneyInfoList.forEach(transferMoneyInfo -> {
            try {
                divMoneyExecuteService.checkTransferResult(transferMoneyInfo.getId());
             } catch (Exception e) {
                log.error("转账结果查询失败，转账记录ID:" + transferMoneyInfo.getId(), e);
             }

            try {
                //基于单笔订单查询每次间隔如下:5秒、10秒、30秒、60秒、120秒、600秒、3600秒
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });
    }

}
