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.exception.openapi.ParamException;
import com.jeequan.jeepay.core.interfaces.paychannel.IPayOrderCloseService;
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.app.AppBizReq;
import com.jeequan.jeepay.core.model.openapi.biz.app.AppBizResp;
import com.jeequan.jeepay.core.model.openapi.biz.query.QueryBizReq;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.pay.service.openapi.AbstractPayOpenApiService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
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("closeOpenApiService")
public class CloseOpenApiService extends AbstractPayOpenApiService {

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private ConfigContextQueryService configContextQueryService;
    /**
     * 聚合扫码支付
     * @param request
     * @return
     * @throws AccessMsgException
     */
    @Override
    public AccessResp execute(AccessReq request) throws AccessMsgException {
        QueryBizReq bizReq = JSON.parseObject(request.getBizData(), QueryBizReq.class);
        if(StringUtils.isAllEmpty(bizReq.getMchOrderNo(), bizReq.getPayOrderId())){
            throw new ParamException("商户订单号[mchOrderNo]参数和平台订单号[payOrderId]不能同时为空");
        }
        PayOrder payOrder = payOrderService.queryMchOrder(request.getAppInfo().getMchNo(), bizReq.getPayOrderId(), bizReq.getMchOrderNo());
        if(payOrder == null){
            throw new AccessMsgException(AccessError.dataError("订单数据不存在"));
        }
        //查询支付接口是否存在
        IPayOrderCloseService closeService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(payOrder.getIfCode()) + "PayOrderCloseService", IPayOrderCloseService.class);
        PayResultResp resp = new PayResultResp(payOrder.getFindAmt(),payOrder.getMchOrderNo(),payOrder.getPayOrderId(), CS.OpenOrderState.CLOSE.getCode(),payOrder.getMchExtNo());
        if(PayOrder.STATE_INIT == payOrder.getState() || closeService == null){
            boolean isUpdate = payOrderService.updateIng2Close(payOrder.getPayOrderId());
            if(!isUpdate){
                throw new AccessMsgException(AccessError.commonError("数据操作异常"));
            }
            return AccessResp.success(request,resp);
        }
        if(PayOrder.STATE_ING == payOrder.getState()){
            //查询出商户应用的配置信息
            MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfoV2(payOrder.getMchNo(), payOrder.getAppId(),payOrder.getMchExtNo());
            try {
                ChannelRetMsg channelRetMsg = closeService.close(payOrder, mchAppConfigContext);
                if(channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) {
                    payOrderService.updateIng2Close(payOrder.getPayOrderId());
                }else{
                    String channelErrMsg = StringUtils.isNotEmpty(channelRetMsg.getChannelErrMsg()) ? channelRetMsg.getChannelErrMsg() : "渠道关闭失败";
                    throw new AccessMsgException(AccessError.commonError(channelErrMsg));
                }
                return AccessResp.success(request,resp);
            } catch (Exception e) {
                throw new AccessMsgException(AccessError.commonError(e.getMessage()));
            }
        }
        throw new AccessMsgException(AccessError.stateError("订单状态不支持当前操作"));
    }
}
