package com.jeequan.jeepay.thirdparty.channel.dgpay;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.interfaces.paychannel.IPayOrderCloseService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.DateKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 订单关闭
 *
 * @author xiaoyu
 *
 * @date 2023/2/28 16:30
 */
@Service
public class DgpayPayOrderCloseService implements IPayOrderCloseService {

    @Override
    public ChannelRetMsg close(PayOrder payOrder, MchAppConfigContext mchAppConfigContext){

        try {
            ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
            JSONObject reqParams = new JSONObject();
            // 请求日期
            reqParams.put("req_date", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
            // 请求流水号
            reqParams.put("req_seq_id", DateKit.currentTimeMillis()+"");
            // 交易流水号
            reqParams.put("org_hf_seq_id", payOrder.getChannelOrderNo());
            // 商户号
            reqParams.put("huifu_id", payOrder.getChannelMchNo());
            // 原机构请求日期
            reqParams.put("org_req_date", DateUtil.format(payOrder.getCreatedAt(), DatePattern.PURE_DATE_PATTERN));
            JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, "/trade/payment/scanpay/close", payOrder.getIfCode());
            JSONObject resData = response.getJSONObject("data");
            String code = resData.getString("resp_code");
            //如果查询请求成功
            if(DgPayKit.STATE_SUCCESS.equals(code)){
                String transStat = resData.getString("trans_stat");
                if (DgPayKit.STATE_SUCCESS_S.equals(transStat)) {
                    return ChannelRetMsg.confirmSuccess(null);
                }else if (DgPayKit.STATE_FAIL_F.equals(transStat)) {
                    // 失败
                    return ChannelRetMsg.confirmFail(resData.getString("resp_desc"));
                }
            }else if(DgPayKit.STATE_ING.equals(code)) {
                return ChannelRetMsg.confirmSuccess(null);
            }
            //支付中
            return ChannelRetMsg.waiting();
        }catch (Exception e) {
            //支付中
            return ChannelRetMsg.waiting();
        }
    }


}
