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

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.interfaces.paychannel.IPayOrderQueryService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.thirdparty.channel.kqpay.model.KqpayOrderStatus;
import com.jeequan.jeepay.thirdparty.channel.kqpay.model.KqpayResp;
import com.jeequan.jeepay.thirdparty.channel.kqpay.util.KqpayConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 查询订单 快钱支付
 *
 * @author xiaoyu
 *
 * @date 2022/4/15 14:29
 */
@Service
@Slf4j
public class KqpayPayOrderQueryService implements IPayOrderQueryService {

    @Override
    public ChannelRetMsg query(PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        JSONObject bizContent = new JSONObject();
        KqpayKit.setPayParams(mchAppConfigContext,bizContent);
        bizContent.put("idOrderCtrl",payOrder.getChannelOrderNo());
        KqpayResp resp = KqpayKit.payRequest(KqpayConst.ReqMethod.A7006,mchAppConfigContext,bizContent,payOrder.getPayOrderId());
        JSONObject responseBody = resp.getResponseBody();
        KqpayOrderStatus txnStatus = KqpayOrderStatus.getVal(responseBody.getString("txnStatus"));
        String transNo = responseBody.getString("idOrderCtrl");
        String channelTradeNo = responseBody.getString("channelTradeNo");
        String channelSendSn = responseBody.getString("idTxnCtrl");
        String bizResponseCode = responseBody.getString("bizResponseCode");
        String bizResponseMessage = responseBody.getString("bizResponseMessage");
        ChannelRetMsg retMsg = ChannelRetMsg.confirmSuccess(transNo, channelTradeNo, channelSendSn,null);
        retMsg.setChannelUserId(responseBody.getString("thirdPartyBuyerId"));
        switch (txnStatus){
            case PROCESS:
                return ChannelRetMsg.waiting();
            case FAIL:
                return ChannelRetMsg.confirmFail(bizResponseCode,bizResponseMessage);
            case CORRECT:
                return ChannelRetMsg.waiting();
            default:
                return retMsg;
        }
    }
}
