package com.jeequan.jeepay.mch.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.AccountOperate;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.exception.ChannelException;
import com.jeequan.jeepay.core.interfaces.paychannel.IMchApiService;
import com.jeequan.jeepay.core.interfaces.paychannel.IRepayApiService;
import com.jeequan.jeepay.core.model.DBPaymentConfig;
import com.jeequan.jeepay.core.model.params.IsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
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.AccountChangeInfo;
import com.jeequan.jeepay.db.entity.AccountInfo;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.SettleInfo;
import com.jeequan.jeepay.service.impl.AccountInfoService;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.SettleInfoService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.service.mapper.AccountChangeInfoMapper;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * TODO
 * 通用处理
 * @author crystal
 * @date 2024/3/14 14:24
 */
@Service
public class CommonApiService {

    @Autowired private SettleInfoService settleInfoService;
    @Autowired private ConfigContextQueryService configContextQueryService;
    @Autowired private MchInfoConverter mchInfoConverter;
    @Autowired private MchApplymentService mchApplymentService;
    /**
     * 同步结算记录
     * @param recordId
     */
    public void syncSettleResult(String recordId){
        SettleInfo settle = settleInfoService.getById(recordId);
        if(settle == null){
            throw new BizException("未知的数据");
        }
        if(SettleInfo.FAIL != settle.getState() && SettleInfo.WAIT != settle.getState() && SettleInfo.PROGRESS != settle.getState()){
            throw new BizException("当前数据结算状态不支持，只支持处理结算失败，结算中或待结算的数据");
        }
        MchApplyment mchApplyment = mchApplymentService.getById(settle.getMchExtNo());
        IsvParams isvParams = configContextQueryService.queryIsvParams(mchInfoConverter.toModel(mchApplyment));
        IMchApiService api = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(settle.getIfCode()) + "MchApiService", IMchApiService.class);
        if(api == null){
            throw new BizException("当前通道不支持");
        }
        //不支持结算记录处理 更改成待确认状态
        if(!api.preCheck()){
            settle.setState(SettleInfo.CONFIRM);
            settle.setRemark("当前通道不支持通过接口查结算状态，请核实结算卡到账流水");
            settleInfoService.updateById(settle);
            return;
        }
        ChannelSettleRq settleRq = new ChannelSettleRq(settle.getChannelMchNo(),settle.getBillNo(),settle.getCreatedAt(),settle.getCreatedAt(),settle.getTransDateScope());
        String succResParameter = mchApplyment.getSuccResParameter();
        if(StringUtils.isNotEmpty(succResParameter)){
            JSONObject extParams = JSON.parseObject(succResParameter);
            settleRq.setExtMchNo(extParams.getString("merInId"));
        }
        List<JSONObject> resultList = api.querySettleInfo(settleRq, settle.getIsvNo(), isvParams);
        if(resultList == null || resultList.isEmpty()){
            throw new BizException("结算数据获取失败");
        }
        SettleInfo syncSettle = resultList.get(0).toJavaObject(SettleInfo.class);
        if(syncSettle.getState().byteValue() == settle.getState().byteValue()){
            throw new BizException("结算状态无变化，请稍后再试");
        }
        Date settleTime = syncSettle.getSettleTime() == null ?  new Date() : syncSettle.getSettleTime();
        settle.setUpdatedAt(settleTime);
        mchInfoConverter.cp(syncSettle,settle);
        settleInfoService.updateById(settle);
    }
}
