package com.fs.task;

import com.alibaba.fastjson.JSON;
import com.fs.common.annotation.QuartzRunnable;
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.util.List;

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

    @Autowired
    private FsStorePaymentMapper fsStorePaymentMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private PayService payService;


    /**
     * 补偿机制，定时反查台州银行
     */
    @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) {
            String json = configService.selectConfigByKey("store.pay");
            FsPayConfig fsPayConfig = JSON.parseObject(json, FsPayConfig.class);
            OrderQueryDTO orderQueryDTO = new OrderQueryDTO();
            orderQueryDTO.setAccount(fsPayConfig.getYbAccount());
            orderQueryDTO.setUpOrderId(fsStorePayment.getTradeNo());
            OrderResult order = payService.getOrder(orderQueryDTO);
            if(order != null) {
                fsStorePayment.setBankTransactionId(order.getBankTrxId());
                fsStorePayment.setBankSerialNo(order.getBankOrderId());
            }

            fsStorePaymentMapper.updateFsStorePayment(fsStorePayment);
        }
    }
}
