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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
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.lklsb2bpay.Lklsb2bpayKit;
import com.jeequan.jeepay.thirdparty.channel.lklsb2bpay.model.LKlsb2bCardType;
import com.jeequan.jeepay.thirdparty.channel.lklsb2bpay.model.Lklsb2bOrderStatus;
import com.jeequan.jeepay.thirdparty.channel.lklsb2bpay.model.Lklsb2bPayMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 拉卡拉查询订单
 *
 * @author xiaoyu
 *
 * @date 2022/4/15 14:29
 */
@Service
@Slf4j
public class Lklsb2bpayPayOrderQueryService implements IPayOrderQueryService {

    @Override
    public ChannelRetMsg query(PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        ChannelRetMsg retMsg = new ChannelRetMsg();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_order_no",payOrder.getPayOrderId());
        bizContent.put("merchant_no",payOrder.getChannelMchNo());
        JSONObject response = Lklsb2bpayKit.payRequest(Lklsb2bPayMethod.Api.CASHIER_QUERY, mchAppConfigContext.getMchApplyment(), bizContent);
        retMsg.setChannelBizData(response);
        Lklsb2bOrderStatus state = Lklsb2bOrderStatus.getVal(response.getIntValue("order_status"));
        JSONArray order_trade_info_list = response.getJSONArray("order_trade_info_list");
        JSONObject bizData = order_trade_info_list.getJSONObject(0);
        LKlsb2bCardType acc_type = LKlsb2bCardType.getVal(bizData.getString("acc_type"));
        retMsg.setChannelUserId(bizData.getString("user_id2"));
        retMsg.setPlatformMchOrderNo(bizData.getString("trade_no"));
        retMsg.setChannelOrderId(bizData.getString("log_no"));
        retMsg.setPlatformOrderNo(bizData.getString("acc_trade_no"));
        retMsg.setDrType(acc_type.getType());
        switch (state){
            case SUCCESS:
                retMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
                break;
            case FAIL:
                retMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                break;
            default:
                retMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                return retMsg;
        }
        return retMsg;
    }
}
