package com.fs.task;

import com.alibaba.fastjson.JSON;
import com.fs.common.annotation.QuartzRunnable;
import com.fs.huifuPay.domain.HuiFuQueryOrderResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayQueryRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.pay.pay.domain.OrderResult;
import com.fs.pay.pay.dto.OrderQueryDTO;
import com.fs.pay.pay.service.PayService;
import com.fs.store.domain.FsPayConfig;
import com.fs.store.domain.FsStorePayment;
import com.fs.store.mapper.FsStorePaymentMapper;
import com.fs.store.service.IFsStoreOrderService;
import com.fs.store.service.IFsStorePaymentService;
import com.fs.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;

@Slf4j
@Service("paymentTask")
public class PaymentTask {
    @Autowired
    private IFsStorePaymentService fsStorePaymentService;
    @Autowired
    private IFsStoreOrderService fsStoreOrderService;

    @Autowired
    private FsStorePaymentMapper fsStorePaymentMapper;

    @Autowired
    private HuiFuService huiFuService;

    /**
     * 补偿机制，定时反查台州银行
     */
    @QuartzRunnable(name="台州银行补偿机制")
    public void paymentSync() {
        fsStorePaymentService.paymentSync();
    }

    /**
     * 超时订单自动取消
     */
    @QuartzRunnable(name = "超时订单自动取消")
    public void orderCancel(){
        fsStoreOrderService.orderCancel();
    }

    /**
     * 同步银行参数为空的问题
     */
    @QuartzRunnable(name = "同步银行参数为空的问题")
    public void fixTransactionNull(){
        List<FsStorePayment> list = fsStorePaymentMapper.queryNormalData();
        for (FsStorePayment fsStorePayment : list) {

            V2TradePaymentScanpayQueryRequest request = new V2TradePaymentScanpayQueryRequest();
            request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(fsStorePayment.getCreateTime()));
            request.setOrgHfSeqId(fsStorePayment.getTradeNo());
            HuiFuQueryOrderResult huiFuQueryOrderResult;
            try {
                huiFuQueryOrderResult = huiFuService.queryOrder(request);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            log.info("汇付返回 {}",huiFuQueryOrderResult);
            if ("00000000".equals(huiFuQueryOrderResult.getResp_code())) {
                fsStorePayment.setBankTransactionId(huiFuQueryOrderResult.getOut_trans_id());
                fsStorePayment.setBankSerialNo(huiFuQueryOrderResult.getParty_order_id());
                fsStorePaymentMapper.updateFsStorePayment(fsStorePayment);
            }
        }
    }
}
