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

import com.alibaba.fastjson.JSON;
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.PayResultResp;
import com.jeequan.jeepay.core.model.openapi.biz.micro.MicroBizReq;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRS;
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 org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

    @Autowired
    private PayOrderService payOrderService;

    /**
     * jsapi支付
     * @param request
     * @return
     * @throws AccessMsgException
     */
    @Override
    public AccessResp execute(AccessReq request) throws AccessMsgException {
        MicroBizReq bizReq = JSON.parseObject(request.getBizData(), MicroBizReq.class);
        UnifiedOrderRQ req = bizReq.preCheck().buildBizRQ();
        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());
        //参数转换
        String errMsg = paymentService.preCheck(req, payOrder);
        if(StringUtils.isNotEmpty(errMsg)){
            throw new AccessMsgException(AccessError.commonError(errMsg));
        }
        payOrderService.saveOrUpdate(payOrder);
        try {
            UnifiedOrderRS rs = (UnifiedOrderRS) paymentService.pay(req, payOrder, apiExt.getConfigContext());
            this.processChannelMsg(rs,rs.getChannelRetMsg(),payOrder);
            PayResultResp resp = new PayResultResp(payOrder);
            return AccessResp.success(request,resp);
        } catch (Exception e) {
            throw new AccessMsgException(AccessError.commonError(e.getMessage()));
        }
    }
}
