package com.pj.project.tb_order;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.bo.NotifyBO;
import com.pj.api.wx.service.WxService;
import com.pj.current.config.JhConfig;
import com.pj.project.tb_business.TbBusiness;
import com.pj.project.tb_business.TbBusinessMapper;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.pj.utils.sg.*;

import javax.annotation.Resource;

/**
 * Service: tb_order -- 临时订单表
 *
 * @author qzy
 */
@Service
public class TbOrderService extends ServiceImpl<TbOrderMapper, TbOrder> implements IService<TbOrder> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbOrderMapper tbOrderMapper;
    @Resource
    JhHttpUtils jhHttpUtils;
    @Resource
    JhConfig jhConfig;
    @Resource
    @Lazy
    JhService jhService;


    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    List<TbOrder> getList(SoMap so) {
        return tbOrderMapper.getList(so);
    }

    @Async
    public void check() {
        QueryWrapper<TbOrder> ew = new QueryWrapper<>();
        ew.eq("order_status", "WAITING_PAYMENT");
        ew.ge("date_format(order_time,'%Y-%m-%d %H:%i:%s')", LocalDateTime.now().minusMinutes(10).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        List<TbOrder> list = this.list(ew);
        String url = jhConfig.getServerUrl() + "/uaps-web-gateway/query/singleOrder";
        list.forEach(tbOrder -> {
            Map<String, Object> params = jhService.buildCheckParams(tbOrder.getOutTradeNo());
            JSONObject result = jhHttpUtils.checkStatus(url, params);
            String orderStatus = result.getStr("orderStatus");
            if (StrUtil.equals(orderStatus, "SUCCESS") || StrUtil.equals(orderStatus, "FINISH")) {
                tbOrder.setOrderStatus(orderStatus)
                        .setTransactionId(result.getStr("bankTrxNo"))
                        .setCompleteDate(result.getStr("completeDate"));
                this.updateById(tbOrder);
                JhNotifyBO notifyBO = new JhNotifyBO();
                notifyBO.setAttach(tbOrder.getAttach()).setBankTrxNo(tbOrder.getTransactionId()).setTradeStatus(orderStatus)
                        .setOutTradeNo(tbOrder.getOutTradeNo()).setOrderPrice(tbOrder.getPrice());
                jhService.notifyResult(notifyBO);
            }
        });
    }

    public TbOrder findByOutTradeNo(String outTradeNo) {
        QueryWrapper<TbOrder> ew = new QueryWrapper<>();
        ew.eq("out_trade_no", outTradeNo);
        return getOne(ew);
    }
}
