package org.springblade.smartapplication.vcdevice.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.tool.utils.UrlUtil;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class VideoCloudUtil {

	/**
	 * 获取加密字段
	 * @param params 业务参数
	 * @param secret 加密密钥
	 * @return
	 */
	public static String getSign(Map<String, Object> params, String secret){
		if(params == null){
			params = new HashMap<>();
		}
		//构建连接字段
		List<String> keys = new ArrayList(params.keySet());
		Collections.sort(keys);
		StringBuilder content = new StringBuilder();
		for(int i = 0; i < keys.size(); ++i) {
			String key = keys.get(i);
			String value = (String)params.get(key);
			content.append(key).append(value);
		}
		String linkString = secret + content.toString() + secret;
		String sign = StringUtils.upperCase(SecureUtil.md5(linkString));
		return sign;
	}

	public static String getUrlParamsLink(Map<String, Object> params, String connStr){
		List<String> keys = new ArrayList(params.keySet());
		Collections.sort(keys);
		StringBuilder content = new StringBuilder();
		for(int i = 0; i < keys.size(); ++i) {
			String key = keys.get(i);
			String value = (String) params.get(key);
			if (i == keys.size() - 1) {
				content.append(key).append("=").append(UrlUtil.encodeURL(value, StandardCharsets.UTF_8));
			}else {
				content.append(key).append("=").append(UrlUtil.encodeURL(value, StandardCharsets.UTF_8)).append(connStr);
			}
		}
		return content.toString();
	}

	public static String getAESPassword(String pwd, String key){
		byte[] keyBytes = key.getBytes();
		AES aes = SecureUtil.aes(keyBytes);
		byte[] encrypt = aes.encrypt(pwd);
		String password = Base64.getEncoder().encodeToString(encrypt);
		return password;
	}

	public static Map<String, Object> getSysParams(String appKey, String format, String method, String signMethod, String v, String token){
		Map<String, Object> map = new HashMap<>();
		map.put("app_key", appKey);
		map.put("format", format);
		map.put("method", method);
		map.put("sign_method", signMethod);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timestamp = simpleDateFormat.format(new Date());
		map.put("timestamp", timestamp);
		map.put("v", v);
		if(StringUtils.isNotBlank(token)){
			map.put("token", token);
		}
		return map;
	}

	/**
	 * 一键构建url请求参数
	 * @param map
	 * @param connStr
	 * @param sysParams
	 * @return
	 */
//	public static String buildRequestParams(Map<String, Object> map, String connStr, SysParams sysParams){
//
//	}
}
