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.exception.BizException;
import com.jeequan.jeepay.core.exception.openapi.ParamException;
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.query.QueryBizReq;
import com.jeequan.jeepay.core.model.rqrs.payorder.UnifiedOrderRQ;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.pay.service.openapi.AbstractQueryOpenApiService;
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
 * 交易查询
 * @author crystal
 * @date 2024/4/10 9:48
 */
@Service("queryTradeOpenApiService")
public class QueryTradeOpenApiService extends AbstractQueryOpenApiService {


    @Autowired
    private PayOrderService payOrderService;

    /**
     * 交易订单状态查询
     * @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("订单数据不存在"));
        }
        PayResultResp resp = new PayResultResp(payOrder);
        return AccessResp.success(request,resp);
    }

}
