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

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.rqrs.AbstractRS;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.WxBarOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.WxBarOrderRS;
import com.jeequan.jeepay.thirdparty.channel.kqpay.KqpayKit;
import com.jeequan.jeepay.thirdparty.channel.kqpay.KqpayPaymentService;
import com.jeequan.jeepay.thirdparty.channel.kqpay.model.KqpayResp;
import com.jeequan.jeepay.thirdparty.channel.kqpay.util.KqpayConst;
import com.jeequan.jeepay.thirdparty.util.ApiResBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 银盛 微信 条码支付
 *
 * @author xiaoyu
 *
 * @date 2022/3/10 10:04
 */
@Slf4j
@Service("kqpayPaymentByWxBarService")
public class WxBar extends KqpayPaymentService {

    @Override
    public String preCheck(UnifiedOrderRQ rq, PayOrder payOrder) {
        WxBarOrderRQ bizRQ = (WxBarOrderRQ) rq;
        if(StringUtils.isEmpty(bizRQ.getAuthCode())){
            throw new BizException("用户支付条码[authCode]不可为空");
        }
        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {
        WxBarOrderRQ bizRQ = (WxBarOrderRQ) rq;
        WxBarOrderRS res = ApiResBuilder.buildSuccess(WxBarOrderRS.class);
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        res.setChannelRetMsg(channelRetMsg);
        JSONObject bizContent = new JSONObject();
        // 默认支付参数
        KqpayKit.setPayParams(mchAppConfigContext, bizContent);
        bizContent.put("cur","CNY");
        bizContent.put("amount",payOrder.getFindAmt());
        bizContent.put("qrCode",bizRQ.getAuthCode());
        bizContent.put("tr3Url",getNotifyUrl());
        String expiredTime = DateUtil.between(payOrder.getCreatedAt(), payOrder.getExpiredTime(), DateUnit.SECOND) + "";
        bizContent.put("expireMinutes",expiredTime);
        bizContent.put("terminalIp",payOrder.getClientIp());
        KqpayResp resp = KqpayKit.payRequest(KqpayConst.ReqMethod.A7001, mchAppConfigContext, bizContent,payOrder.getPayOrderId());
        this.initResult(resp,channelRetMsg);
        return res;
    }

}
