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

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.params.sandpay.SandpayConfig;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 杉德查单
 *
 * @author xiaoyu
 *
 * @date 2021/12/16 11:31
 */
@Service
@Slf4j
public class SandpayPayOrderQueryService implements IPayOrderQueryService {

    @Override
    public ChannelRetMsg query(PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        String logPrefix = "【杉德("+payOrder.getWayCode()+")查单】";
        try {
            // 请求参数
            JSONObject bodyJson = new JSONObject();
            bodyJson.put("orderCode", payOrder.getPayOrderId());
            String productId = SandpayConfig.WAY_CODE_MAP.get(payOrder.getWayCode());
            if (StringUtils.isEmpty(productId)) {
                log.info("{}支付方式对应的产品编码不存在{}", payOrder.getWayCode(), productId);
                return ChannelRetMsg.waiting();
            }
            log.info("{} 查询订单 payorderId:{}, 请求参数:{}", logPrefix, payOrder.getPayOrderId(), bodyJson);
            JSONObject resJson = SandPayKit.requestServer(bodyJson, SandpayConfig.ORDER_QUERY, SandpayConfig.ORDERQUERY, productId, mchAppConfigContext);
            log.info("{} 查询订单 payorderId:{}, 返回结果:{}", logPrefix, payOrder.getPayOrderId(), resJson);

            JSONObject resHead = resJson.getJSONObject("head");
            //请求 & 响应成功， 判断业务逻辑
            String status = resHead.getString("respCode");
            //如果查询交易成功
            if(SandpayConfig.SUCCESS.equals(status)){
                JSONObject jsonObject = resJson.getJSONObject("body");
                String orderStatus = jsonObject.getString("orderStatus");
                if ("00".equals(orderStatus)) {
                    //交易成功，更新商户订单状态
                    return ChannelRetMsg.confirmSuccess(jsonObject.get("payOrderCode").toString());
                }else if ("01".equals(orderStatus)) {
                    //支付中
                    return ChannelRetMsg.waiting();
                }else if ("02".equals(orderStatus)) {
                    // 失败
                    return ChannelRetMsg.confirmFail();
                }
            }
            //支付中
            return ChannelRetMsg.waiting();
        }catch (Exception e) {
            //支付中
            return ChannelRetMsg.waiting();
        }
    }

}
