package com.jeequan.jeepay.pay.ctrl;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.ctrls.AbstractCtrl;
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.db.entity.MchAppEntity;
import com.jeequan.jeepay.pay.service.ValidateService;
import com.jeequan.jeepay.pay.util.ApiResKit;
import com.jeequan.jeepay.service.impl.MchAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * api 抽象接口， 公共函数
 * @author crystal
 */
@Slf4j
public abstract class OpenApiController extends AbstractCtrl {

    @Autowired private ValidateService validateService;
    @Autowired private MchAppService mchAppService;
    @Autowired private MchInfoConverter mchInfoConverter;


    /** 获取请求参数并转换为对象，通用验证  **/
    protected AccessReq getRQ(){
        AccessReq bizRQ = getObject(AccessReq.class);
        // [1]. 验证通用字段规则
        validateService.checkV1(bizRQ);
        preCheck(bizRQ);
        return bizRQ;
    }

    /** 获取请求参数并转换为对象，通用验证  **/
    protected AccessResp getRS(AccessReq bizRQ, Object bizRet){
        return AccessResp.success(bizRQ, bizRet);
    }

    /**
     * 公共参数校验
     * @param bizRQ
     */
    protected void preCheck(AccessReq bizRQ){
        log.info("【apiV2】接口请求参数:{}", JSON.toJSONString(bizRQ));
        MchAppEntity appEntity = mchAppService.getById(bizRQ.getAppId());

        if (!ObjUtil.isEmpty(bizRQ.getBizData())) {
            try {
                bizRQ.setBizDataJSON(JSON.parseObject(bizRQ.getBizData()));
            } catch (JSONException e) {
                log.info("业务参数格式异常, 业务参数: {}", bizRQ.getBizData());
                throw new BizException("业务参数格式异常");
            }
        }

        if(appEntity == null){
            throw new ParamException("未知的应用[appId]参数");
        }

        bizRQ.setAppInfo(mchInfoConverter.toModel(appEntity));
        bizRQ.setPlatPriKey(ApiResKit.getKey());
        if(MchAppEntity.NORMAL.byteValue() != appEntity.getState()){
            throw new AccessMsgException(AccessError.stateError("应用已被停用或已被关闭，不支持当前操作"));
        }
        List<String> appSignType = JSON.parseArray(appEntity.getAppSignType(), String.class);
        if(!appSignType.contains(bizRQ.getSignType())){
            throw new ParamException("非法的签名类型[signType]参数");
        }
    }
}
