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.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.RefundResultResp;
import com.jeequan.jeepay.core.model.openapi.biz.query.QueryBizReq;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.db.entity.RefundOrder;
import com.jeequan.jeepay.pay.service.openapi.AbstractQueryOpenApiService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import com.jeequan.jeepay.service.impl.RefundOrderService;
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("queryRefundOpenApiService")
public class QueryRefundOpenApiService extends AbstractQueryOpenApiService {


    @Autowired
    private RefundOrderService refundOrderService;

    /**
     * 交易订单状态查询
     * @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.getMchRefundNo(), bizReq.getRefundOrderId())){
            throw new ParamException("商户退款订单号[mchRefundNo]参数和平台订单号[refundOrderId]不能同时为空");
        }
        RefundOrder refundOrder = refundOrderService.queryMchOrder(request.getAppInfo().getMchNo(), bizReq.getMchRefundNo(), bizReq.getRefundOrderId());
        if(refundOrder == null){
            throw new AccessMsgException(AccessError.dataError("订单数据不存在"));
        }
        RefundResultResp resp = refundOrder.bulidResult();
        return AccessResp.success(request,resp);
    }

}
