package com.jeequan.jeepay.pay.service.openapi.impl;

import com.alibaba.fastjson.JSON;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.AccessMsgException;
import com.jeequan.jeepay.core.interfaces.paychannel.IPaymentService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.openapi.AccessError;
import com.jeequan.jeepay.core.model.openapi.AccessReq;
import com.jeequan.jeepay.core.model.openapi.AccessResp;
import com.jeequan.jeepay.core.model.openapi.biz.app.AppBizReq;
import com.jeequan.jeepay.core.model.openapi.biz.app.AppBizResp;
import com.jeequan.jeepay.core.model.rqrs.AbstractRS;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRS;
import com.jeequan.jeepay.core.model.rqrs.payorder.payway.AliAppOrderRS;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.pay.model.OpenApiExt;
import com.jeequan.jeepay.pay.service.openapi.AbstractPayOpenApiService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import com.jeequan.jeepay.thirdparty.util.ApiResBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * TODO
 * APP支付逻辑
 * @author crystal
 * @date 2024/4/8 11:49
 */
@Service("appOpenApiService")
public class AppOpenApiService extends AbstractPayOpenApiService {

    @Autowired
    private PayOrderService payOrderService;

    /**
     * 聚合扫码支付
     * @param request
     * @return
     * @throws AccessMsgException
     */
    @Override
    public AccessResp execute(AccessReq request) throws AccessMsgException {
        AppBizReq bizReq = JSON.parseObject(request.getBizData(), AppBizReq.class);
        UnifiedOrderRQ req = bizReq.preCheck().setIsAppletCheck(true);
        OpenApiExt apiExt = checkMchInfo(req, request.getAppInfo());
        checkPay(apiExt.getConfigContext(),req, request.getAppInfo());
        //获取支付接口
        IPaymentService paymentService = getPayRoute(apiExt.getConfigContext());
        PayOrder payOrder = genPayOrder(req, apiExt.getConfigContext(),apiExt.getRouteManage());
        //校验参数
        paymentService.preCheck(req,payOrder);
        payOrderService.saveOrUpdate(payOrder);
        AppBizResp resp = null;
        try {
            if(req.getIsReqChannel()){
                UnifiedOrderRS rs = (UnifiedOrderRS)paymentService.pay(bizReq, payOrder, apiExt.getConfigContext());
                this.processChannelMsg(rs,rs.getChannelRetMsg(),payOrder);
                resp = new AppBizResp(payOrder,rs.getPayData());
            }else{
                //是否请求渠道
                resp = getAppPayData(payOrder);
            }
            return AccessResp.success(request,resp);
        } catch (Exception e) {
            throw new AccessMsgException(AccessError.commonError(e.getMessage()));
        }
    }
}
