package org.springblade.bbc.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springblade.bbc.config.LdtBbcConfig;
import org.springblade.bbc.request.SignAuthenticationRequest;
import org.springblade.common.utils.SpringContextHolder;
import org.springblade.core.tool.utils.BeanUtil;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author: Silent
 * @Description BBC签名工具
 * @Date: Created in 10:47 2021/12/28
 * @Modified By:
 */
@Slf4j
public class BbcSignUtil {

	private static final LdtBbcConfig ldtBbcConfig = SpringContextHolder.getBean(LdtBbcConfig.class);

	/**
	 * 签名认证方式，进行参数签名
	 *
	 * @return
	 */
	public static SignAuthenticationRequest paramsSignAuthentication(SignAuthenticationRequest signAuthenticationRequest) {
		String sortParams = sortParams(signAuthenticationRequest);
		signAuthenticationRequest.setSign(SecureUtil.md5(sortParams));

		String afterSign = JSONObject.toJSONString(signAuthenticationRequest);
		log.info("BBC-签名后参数:[{}]", afterSign);
		return signAuthenticationRequest;
	}

	/**
	 * 排序参数
	 *
	 * @param object
	 * @return
	 */
	private static String sortParams(Object object) {
		//转化为参数
		Map<String, Object> stringObjectMap = new TreeMap<>();
		stringObjectMap.putAll(BeanUtil.toMap(object));
		//参数集合
		List<String> param = new LinkedList<>();
		for (Map.Entry<String, Object> stringObjectEntry : stringObjectMap.entrySet()) {
			//排除空值和请求号
			if (ObjectUtils.isNotEmpty(stringObjectEntry.getValue())) {
				param.add(stringObjectEntry.getValue().toString());
			}
		}

		//添加签名key
		String paramValue = ArrayUtil.join(param.toArray(), "");
		paramValue = paramValue + ldtBbcConfig.getSignKey();

		log.info("BBC-排序后参数:[{}]", paramValue);

		return paramValue;
	}
}
