package com.emergency.avenue.storage.util;

import cn.hutool.core.convert.Convert;
import com.emergency.avenue.storage.api.request.EyeCommonReq;

import java.security.PublicKey;

public class EyeUtils {

	/**
	 * 鹰眼公共参数组装
	 *
	 * @param req
	 * @return
	 */
	public static EyeCommonReq bindCommonReq(String appKey, String appSecret, String publicKey,String req) throws Exception {
		EyeCommonReq commonReq = new EyeCommonReq();
		// 平台申请提供
		commonReq.setAppKey(appKey);
		// 平台申请提供
		PublicKey publicKeyObject = RSAUtil.string2PublicKey(publicKey);
		byte[] publicEncrypt = RSAUtil.publicEncrypt(appSecret.getBytes(), publicKeyObject);
		String s = RSAUtil.byte2Base64(publicEncrypt);
		commonReq.setAppSecret(s);
		// 固定为json
		commonReq.setFormat("json");
		// 固定为md5
		commonReq.setSign_method("md5");
		// 固定为1.0
		commonReq.setVersion("1.0");
		// 请求时间戳、需要返回给前端
		commonReq.setTimestamp(Convert.toStr(System.currentTimeMillis()));
		// 请求参数、和前端保持一致
		commonReq.setParams(req);
		// 请求签名、需要返回给前端
		commonReq.setSign(signParam(commonReq));
		return commonReq;
	}

	/**
	 * signParam组建
	 *
	 * @param commonReq
	 * @return
	 */
	private static String signParam(EyeCommonReq commonReq) {
		StringBuilder sb = new StringBuilder();
		sb.append("appKey").append(commonReq.getAppKey());
		sb.append("format").append(commonReq.getFormat());
		sb.append("params").append(commonReq.getParams());
		sb.append("sign_method").append(commonReq.getSign_method());
		sb.append("timestamp").append(commonReq.getTimestamp());
		sb.append("version").append(commonReq.getVersion());
		sb.insert(0, commonReq.getAppSecret());
		sb.append(commonReq.getAppSecret());
		return MD5Util.MD5(sb.toString()).toUpperCase();
	}

}
