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

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.params.sxfpay.SxfpayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.thirdparty.channel.sxfpay.model.ReqMethod;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 关闭订单接口实现类
 */
@Slf4j
@Service
public class SxfpayPayOrderCloseService implements IPayOrderCloseService {

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Override
    public ChannelRetMsg close(PayOrder payOrder, MchAppConfigContext mchAppConfigContext){
        try {
            SxfpayIsvParams isvParams = (SxfpayIsvParams) configContextQueryService.queryIsvParams(mchAppConfigContext.getMchApplyment().getIsvNo(),payOrder.getIfCode());
            JSONObject bizContent = new JSONObject();
            // 商户号
            bizContent.put("mno", payOrder.getChannelMchNo());
            // 商户订单号
            bizContent.put("origOrderNo", payOrder.getPayOrderId());
            JSONObject respBizData = SxfpayKit.reqApi(ReqMethod.Method.TRADE_ORDER_CLOSE, isvParams, bizContent);
            String tranSts = respBizData.getString("tranSts");
            String uuid = respBizData.getString("uuid");
            switch (tranSts){
                case "CLOSED":
                    return ChannelRetMsg.confirmSuccess(uuid);
            }
            return ChannelRetMsg.confirmFail(respBizData.getString("bizCode"),respBizData.getString("bizMsg"));
        }catch (Exception e) {
            return ChannelRetMsg.sysError(e.getMessage());
        }
    }
}
