package com.jeequan.jeepay.pay.ctrl.payorder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.rqrs.payorder.QueryPayOrderRQ;
import com.jeequan.jeepay.core.model.rqrs.payorder.QueryPayOrderRS;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.pay.ctrl.ApiController;
import com.jeequan.jeepay.pay.util.ApiResKit;
import com.jeequan.jeepay.service.impl.MchConfigService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/*
* 商户查单controller
*
* @author terrfly
*
* @date 2021/6/8 17:26
*/
@Slf4j
@RestController
public class QueryOrderController extends ApiController {

    @Autowired private PayOrderService payOrderService;
    @Autowired private MchConfigService mchConfigService;
    @Autowired private IConfigContextQueryService configContextQueryService;

    /**
     * 查单接口
     * **/
    @MethodLog(remark = "查询支付订单API")
    @RequestMapping("/api/pay/query")
    public ApiRes queryOrder(){

        //获取参数 & 验签
        QueryPayOrderRQ rq = getRQByWithMchSign(QueryPayOrderRQ.class);

        if(StringUtils.isAllEmpty(rq.getMchOrderNo(), rq.getPayOrderId())){
            throw new BizException("mchOrderNo 和 payOrderId不能同时为空");
        }

        PayOrder payOrder = payOrderService.queryMchOrder(rq.getMchNo(), rq.getPayOrderId(), rq.getMchOrderNo());
        if(payOrder == null){
            throw new BizException("订单不存在");
        }

        QueryPayOrderRS bizRes = QueryPayOrderRS.buildByPayOrder(payOrder);

        JSONObject jsonObject = (JSONObject)JSONObject.toJSON(bizRes);

        // 查询扩展参数
        MchConfig mchConfig = mchConfigService.getByMchNoAndConfigKey(payOrder.getMchNo(), "payOrderNotifyExtParams");
        List<String> extParams = new ArrayList<>();
        if(mchConfig != null && StringUtils.isNotBlank(mchConfig.getConfigVal())){
            extParams = JSON.parseArray(mchConfig.getConfigVal(), String.class);
        }
        for (String key : QueryPayOrderRS.EXT_PRAMS) {
            if(!extParams.contains(key)){
                jsonObject.remove(key);
            }
        }

        // 报文签名
        return ApiResKit.okWithSign(jsonObject, configContextQueryService.queryMchApp(rq.getMchNo(), rq.getAppId()), rq.getSignType());
    }

}
