package com.jeequan.jeepay.pay.util;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.entity.MchApp;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.core.utils.JeepayRSA2Kit;
import com.jeequan.jeepay.pay.config.SystemYmlConfig;

public class ApiResKit {

    private static String sysPrivateKey = null;

    public static String getKey(){

        if(sysPrivateKey != null){
            return sysPrivateKey;
        }

        sysPrivateKey = SpringUtil.getBean(SystemYmlConfig.class).getSysRSA2PrivateKey();
        return sysPrivateKey;
    }


    /** 业务处理成功, 自动签名 **/
    public static ApiRes okWithSign(Object data, MchApp mchApp, String reqSignType){

        if(data == null){
            return new ApiRes(ApiCodeEnum.SUCCESS.getCode(), ApiCodeEnum.SUCCESS.getMsg(), null, null, null);
        }

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

        String sign = null;
        if(MchApp.SIGN_TYPE_MD5.equalsIgnoreCase(reqSignType)){
            sign = JeepayKit.getSign(jsonObject, mchApp.getAppSecret());
        }else if(MchApp.SIGN_TYPE_RSA2.equalsIgnoreCase(reqSignType)){
            try {
                sign = JeepayRSA2Kit.getSign(jsonObject, getKey());
            } catch (Exception e) {
                throw new BizException("签名异常");
            }
        }else{
            throw new BizException("不支持的签名方式");
        }

        return new ApiRes(ApiCodeEnum.SUCCESS.getCode(), ApiCodeEnum.SUCCESS.getMsg(), data, null, sign);
    }

}
