package com.pj.api.jh.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.pj.api.jh.bo.JhNotifyBO;
import com.pj.api.jh.service.JhService;
import com.pj.api.jh.utils.JhHttpUtils;
import com.pj.api.wx.service.WxService;
import com.pj.current.config.JhConfig;
import com.pj.current.task.Task;
import com.pj.project.tb_order.TbOrder;
import com.pj.project.tb_order.TbOrderService;
import com.pj.project4sp.global.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Map;

@Slf4j
public class CheckPayStatusTask extends Task {
    private String outTradeNo;
    private LocalDateTime startTime;

    public CheckPayStatusTask(String id, long delayInMilliseconds, String outTradeNo) {
        super(id, delayInMilliseconds);
        this.outTradeNo = outTradeNo;
        this.startTime = LocalDateTime.now();
    }

    @Override
    public void run() {
        JhConfig jhConfig = SpringUtil.getBean(JhConfig.class);
        JhService jhService = SpringUtil.getBean(JhService.class);
        String url = jhConfig.getServerUrl() + "/uaps-web-gateway/query/singleOrder";
        Map<String, Object> params = jhService.buildCheckParams(outTradeNo);
        check(url, params);
    }

    private void check(String url, Map<String, Object> params) {
        LocalDateTime now = LocalDateTime.now();
        if (ChronoUnit.MINUTES.between(startTime,now)>5){
            log.error("超时订单，不再查单:{}",outTradeNo);
            return;
        }
        log.info("开始查单===：{}", JSONUtil.toJsonStr(params));
        JhHttpUtils jhHttpUtils = SpringUtil.getBean(JhHttpUtils.class);
        JSONObject result = jhHttpUtils.checkStatus(url, params);
        String orderStatus = result.getStr("orderStatus");
        if (StrUtil.equals(orderStatus, "WAITING_PAYMENT")) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.check(url, params);
        } else if (StrUtil.equals(orderStatus, "SUCCESS") || StrUtil.equals(orderStatus, "FINISH")) {
            TbOrderService tbOrderService = SpringUtil.getBean(TbOrderService.class);
            TbOrder tbOrder = tbOrderService.findByOutTradeNo(outTradeNo);
            if (StrUtil.equals("WAITING_PAYMENT", tbOrder.getOrderStatus())) {
                JhService jhService = SpringUtil.getBean(JhService.class);
                JhNotifyBO notifyBO = new JhNotifyBO();
                notifyBO.setAttach(tbOrder.getAttach()).setBankTrxNo(tbOrder.getTransactionId()).setTradeStatus(orderStatus)
                        .setOutTradeNo(tbOrder.getOutTradeNo()).setOrderPrice(tbOrder.getPrice());
                jhService.notifyResult(notifyBO);
            }

        }

    }


}
