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

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.lklspay.model.LKlCardType;
import com.jeequan.jeepay.thirdparty.channel.lklspay.model.LklOrderStatus;
import com.jeequan.jeepay.thirdparty.channel.lklspay.model.LklPayMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

    @Override
    public ChannelRetMsg query(PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        JSONObject bizContent = new JSONObject();
        LklspayKit.setPayParams(mchAppConfigContext,bizContent,null);
        bizContent.put("out_trade_no",payOrder.getPayOrderId());
        bizContent.put("trade_no",payOrder.getChannelOrderNo());
        JSONObject response = LklspayKit.payRequest(LklPayMethod.Api.TRANS_QUERY, mchAppConfigContext.getMchApplyment(), bizContent);
        LklOrderStatus state = LklOrderStatus.getVal(response.getString("trade_state"));
        LKlCardType card_type = LKlCardType.getVal(response.getString("card_type"));
        String drType = card_type.getType();
        switch (card_type){
            case LKL_ACCOUNT:
            case ALI_OTHER:
                drType = CS.DrType.OTHER.getType();
                break;
            case DECP:
                drType = CS.DrType.DCEP.getType();
                break;
        }
        ChannelRetMsg retMsg = ChannelRetMsg.confirmSuccess(response.getString("log_no"), response.getString("acc_trade_no"), response.getString("trade_no"),drType);
        retMsg.setChannelUserId(response.getString("user_id2"));
        switch (state){
            case SUCCESS:
                retMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
                break;
            case FAIL:
                retMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                break;
            case CLOSE:
                retMsg.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                break;
            default:
                retMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                return retMsg;
        }
        return retMsg;
    }
}
