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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.exception.ChannelException;
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.AliPcOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.AliPcOrderRS;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.thirdparty.channel.alipay.AlipayKit;
import com.jeequan.jeepay.thirdparty.channel.alipay.AlipayPaymentService;
import com.jeequan.jeepay.thirdparty.channel.zftpay.ZftpayPaymentService;
import com.jeequan.jeepay.thirdparty.util.ApiResBuilder;
import org.springframework.stereotype.Service;

/*
* 支付宝 PC支付
*
* @author terrfly
*
* @date 2021/6/8 17:21
*/
@Service("zftpayPaymentByAliPcService") //Service Name需保持全局唯一性
public class AliPc extends ZftpayPaymentService {

    @Override
    public String preCheck(UnifiedOrderRQ rq, PayOrder payOrder) {
        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext){
        AliPcOrderRQ bizRQ = (AliPcOrderRQ) rq;
        AlipayTradePagePayRequest req = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = getPayModel(rq, payOrder, AlipayTradePagePayModel.class);
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        model.setQrPayMode("2"); //订单码-跳转模式
        req.setNotifyUrl(getNotifyUrl()); // 设置异步通知地址
        req.setReturnUrl(getReturnUrl()); // 同步跳转地址
        req.setBizModel(model);
        // 构造函数响应数据
        AliPcOrderRS res = ApiResBuilder.buildSuccess(AliPcOrderRS.class);
        try {
            if(CS.PAY_DATA_TYPE.FORM.equals(bizRQ.getPayDataType())){
                res.setFormContent(configContextQueryService.getZftpayClientWrapper(mchAppConfigContext).getAlipayClient().pageExecute(req).getBody());
            }else{
                res.setPayUrl(configContextQueryService.getZftpayClientWrapper(mchAppConfigContext).getAlipayClient().pageExecute(req, "GET").getBody());
            }
        }catch (AlipayApiException e) {
            throw ChannelException.sysError(e.getMessage());
        }
        ChannelRetMsg channelRetMsg = new ChannelRetMsg();
        res.setChannelRetMsg(channelRetMsg);

        //放置 响应数据
        channelRetMsg.setChannelState(ChannelRetMsg.ChannelState.WAITING);
        return res;
    }

}
