package com.jeequan.jeepay.pay.task;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.interfaces.paychannel.IMchApiService;
import com.jeequan.jeepay.core.model.applyment.ApplymentBasicInfo;
import com.jeequan.jeepay.core.model.params.IsvParams;
import com.jeequan.jeepay.core.model.rqrs.settle.ChannelSettleRq;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.SettleInfo;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.SettleInfoService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * TODO
 * 通道渠道的结算记录的定时任务
 * @author crystal
 * @date 2023/12/8 9:57
 */
@Component
@Slf4j
public class SyncMchSettleInfoTask {

    @Autowired private SettleInfoService settleInfoService;

    @Autowired private MchInfoConverter mchInfoConverter;

    @Autowired private ConfigContextQueryService configContextQueryService;

    @Autowired private MchApplymentService mchApplymentService;

    @XxlJob("syncMchSettleInfoTaskHandler")
    public void start() {
        log.info("【同步渠道结算记录】定时任务开始");
        try {
            Date startDateTime = DateUtil.beginOfDay(new Date());
            Date endDateTime = DateUtil.endOfDay(new Date());
            LambdaQueryWrapper<SettleInfo> queryWrapper = SettleInfo.gw().in(SettleInfo::getSettleType, CS.SETTLEMENT_TYPE.D1,CS.SETTLEMENT_TYPE.T1).between(SettleInfo::getCreatedAt, startDateTime, endDateTime).in(SettleInfo::getState, SettleInfo.WAIT, SettleInfo.PROGRESS);
            List<SettleInfo> list = settleInfoService.list(queryWrapper);
            if(!list.isEmpty()){
                for (SettleInfo item:list) {
                    MchApplyment mchApplyment = mchApplymentService.getById(item.getMchExtNo());
                    IsvParams isvParams = configContextQueryService.queryIsvParams(mchInfoConverter.toModel(mchApplyment));
                    IMchApiService api = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(item.getIfCode()) + "MchApiService", IMchApiService.class);
                    if(api == null || !api.preCheck()){
                        item.setState(SettleInfo.CONFIRM);
                        item.setRemark("当前通道不支持通过接口查结算状态，请核实结算卡到账流水");
                        //获取结算账户和结算金额
                        ApplymentBasicInfo parse = JSON.parseObject(mchApplyment.getApplyDetailInfo(), ApplymentBasicInfo.class);
                        String cardNo = parse.getSettAccountNo();
                        String cardName = parse.bankAccountName();
                        String bankName = parse.getSettAccountBankName();
                        item.setAccountNo(cardNo);
                        item.setAccountName(cardName);
                        item.setBankName(bankName);
                        item.setSettleAmt(item.getPlanAmt() - item.getFee());
                        continue;
                    }
                    try {
                        ChannelSettleRq settleRq = new ChannelSettleRq(item.getChannelMchNo(),startDateTime,endDateTime,1L,50L);
                        String succResParameter = mchApplyment.getSuccResParameter();
                        if(StringUtils.isNotEmpty(succResParameter)){
                            JSONObject extParams = JSON.parseObject(succResParameter);
                            settleRq.setExtMchNo(extParams.getString("merInId"));
                        }
                        List<JSONObject> resultList = api.querySettleInfo(settleRq, item.getIsvNo(), isvParams);
                        if(resultList == null || resultList.isEmpty()){
                            item.setRemark("结算接口调用返回的数据为空");
                            continue;
                        }
                        SettleInfo settleInfo = resultList.get(0).toJavaObject(SettleInfo.class);
                        Date settleTime = settleInfo.getSettleTime() == null ?  new Date() : settleInfo.getSettleTime();
                        item.setUpdatedAt(settleTime);
                        mchInfoConverter.cp(settleInfo,item);
                    }catch (Exception e){
                        item.setState(SettleInfo.FAIL);
                        item.setRemark(e.getMessage());
                        continue;
                    }
                }
                settleInfoService.saveOrUpdateBatch(list);
            }
        }catch (Exception e){
            log.info("【同步渠道结算记录】定时任务异常：{}",e.getMessage());
        }
        log.info("【同步渠道结算记录】定时任务结束");
    }

    /**
     * 同步渠道D0结算任务
     */
//    @XxlJob("syncMchD0SettleInfoTaskHandler")
//    public void startD0() {
//        log.info("【同步渠道D0结算记录】定时任务开始");
//        LambdaQueryWrapper<SettleInfo> queryWrapper = SettleInfo.gw().eq(SettleInfo::getSettleType, CS.SETTLEMENT_TYPE.D0).in(SettleInfo::getState, SettleInfo.WAIT, SettleInfo.PROGRESS);
//        List<SettleInfo> list = settleInfoService.list(queryWrapper);
//        if(list.isEmpty()){
//            log.info("【同步渠道D0结算记录】定时任务结束,查询出符合数据为空");
//            return;
//        }
//        for (SettleInfo item:list) {
//            MchApplyment mchApplyment = mchApplymentService.getById(item.getMchExtNo());
//            IsvParams isvParams = configContextQueryService.queryIsvParams(mchInfoConverter.toModel(mchApplyment));
//            IMchApiService api = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(item.getIfCode()) + "MchApiService", IMchApiService.class);
//            if(api == null || !api.preCheck()){
//                item.setState(SettleInfo.CONFIRM);
//                item.setRemark("D0笔笔秒到银行卡需要自行在银行APP内查询到账明细");
//                continue;
//            }
//            try {
//                ChannelSettleRq settleRq = new ChannelSettleRq(item.getChannelMchNo(),item.getCreatedAt(),item.getCreatedAt(),1L,50L);
//                String succResParameter = mchApplyment.getSuccResParameter();
//                if(StringUtils.isNotEmpty(succResParameter)){
//                    JSONObject extParams = JSON.parseObject(succResParameter);
//                    settleRq.setExtMchNo(extParams.getString("merInId"));
//                }
//                List<JSONObject> resultList = api.querySettleInfo(settleRq, item.getIsvNo(), isvParams);
//                if(resultList == null || resultList.isEmpty()){
//                    item.setState(SettleInfo.CONFIRM);
//                    item.setRemark("D0笔笔秒到银行卡需要自行在银行APP内查询到账明细");
//                    continue;
//                }
//                SettleInfo settleInfo = resultList.get(0).toJavaObject(SettleInfo.class);
//                Date settleTime = settleInfo.getSettleTime() == null ?  new Date() : settleInfo.getSettleTime();
//                item.setUpdatedAt(settleTime);
//                mchInfoConverter.cp(settleInfo,item);
//            }catch (Exception e){
//                item.setState(SettleInfo.CONFIRM);
//                item.setRemark("D0笔笔秒到银行卡需要自行在银行APP内查询到账明细");
//                continue;
//            }
//        }
//        log.info("【同步渠道结算记录】定时任务结束");
//    }
}
