package com.hzya.frame.cbs8.util;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author xiangerlin
 * @Date 2024/6/7 15:38
 **/
@Component
public class CBSUtil {
    /**
     * 集中支付模式
     */
    public static final String CENTRALIZED_PAYMENT_TYPE = "401";
    /**
     * 分页查询 最大条数
     */
    public static final int MAX_PAGE_SIZE = 1000;
    /**
     * 默认分页查询条数
     */
    public static final int DEFAULT_PAGE_SIZE = 100;
    /**
     * 默认页码
     */
    public static final int DEFAULT_CURRENT_PAGE = 1;
    static Logger logger = LogManager.getLogger(CBSUtil.class);

    /**
     * 请求参数格式
     */
    public static String TARGET_CONTENT_TYPE = "application/json";

    /**
     * 签名请求头参数名
     */
   public static String SIGN_HEADER_NAME = "X-MBCLOUD-API-SIGN";
    /**
     * 时间戳请求头参数名
     */
    public static String TIMESTAMP_HEADER = "X-MBCLOUD-TIMESTAMP";

    public static String ENCRYPTION_ENABLED_HEADER_NAME = "X-MBCLOUD-ENCRYPTION-ENABLED";

    public static String X_MBCLOUD_COMPRESS = "X-Mbcloud-Compress";

    /**
     * 请求头token参数名
     */
    public static String AUTHORIZATION = "Authorization";

    /**
     *token前缀
     */
    public static String BEARER = "Bearer ";

    /**
     * 财资管理云公钥(平台公钥)
     */
    public static String bodyEncryptionKey;

    /**
     * 企业私钥（加密）
     */
    public static String signEncryptionPrivateKey;

    /**
     * 企业私钥（解密）
     */
    public static String bodyDecryptionKey;

    /**
     * 财资管理云公钥(平台公钥)
     */
    @Value("${cbs8.cbs_public_key:}")
    public  void setBodyEncryptionKey(String bodyEncryptionKey) {
        CBSUtil.bodyEncryptionKey = bodyEncryptionKey;
    }
    /**
     * 企业私钥（解密）
     */
    @Value("${cbs8.ya_private_key:}")
    public  void setSignEncryptionPrivateKey(String signEncryptionPrivateKey) {
        CBSUtil.signEncryptionPrivateKey = signEncryptionPrivateKey;
    }
    /**
     * 企业私钥（解密）
     */
    @Value("${cbs8.ya_private_key:}")
    public  void setBodyDecryptionKey(String bodyDecryptionKey) {
        CBSUtil.bodyDecryptionKey = bodyDecryptionKey;
    }

    //将json数组转为list
    public static <T> List<T> convertJsonArrayToList(List<JSONObject> list, Class<T> clazz) {
        String jsonArray = JSON.toJSONString(list);
        List<T> result = JSON.parseObject(jsonArray, new TypeReference<List<T>>(clazz) {});
        return result;
    }

    /**
     * 将时间戳转换成日期字符串
     * @param timestamp
     * @return
     */
    public static String convertTimestampToString(String timestamp) {
        if (StrUtil.isNotEmpty(timestamp) && NumberUtil.isNumber(timestamp)){
            // 创建SimpleDateFormat对象，指定日期时间格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 将时间戳转换为Date对象
            Date date = new Date(Long.valueOf(timestamp));

            // 使用SimpleDateFormat格式化Date对象，得到字符串表示
            return sdf.format(date);
        }
        return null;
    }

    /**
     * 签名
     * @param requestData
     * @return
     */
    public static String sign(String requestData){
        long timestamp = System.currentTimeMillis();
        return sign(requestData,timestamp);
    }

    /**
     * 签名
     * @param requestData
     * @param timestamp
     * @return
     */
    public static String sign(String requestData,long timestamp){

        // 请求数据拼接：  报文体+时间戳
        byte[] requestDataBytes = requestData.getBytes(StandardCharsets.UTF_8);
        byte[] timestampBytes = ("&timestamp=" + timestamp).getBytes(StandardCharsets.UTF_8);
        byte[] newBytes = new byte[requestDataBytes.length + timestampBytes.length];
        System.arraycopy(requestDataBytes, 0, newBytes, 0, requestDataBytes.length);
        System.arraycopy(timestampBytes, 0, newBytes, requestDataBytes.length, timestampBytes.length);

        // 生成签名
        byte[] signature = SM2Util.sign(signEncryptionPrivateKey, newBytes);
        String sign = Base64.encodeBase64String(SM2Util.encodeDERSignature(signature));
        logger.info("签名:{}", sign);
        return sign;
    }

    /**
     * 加密
     * @param requestData
     * @return
     */
    public static byte[] encrypt(String requestData){
        byte[] encrypt = SM2Util.encrypt(bodyEncryptionKey, requestData.getBytes(StandardCharsets.UTF_8));
        return encrypt;
    }

    public static String decrypt(byte[] cipherData){
        try {
            byte[] decrypt = SM2Util.decrypt(bodyDecryptionKey, cipherData);
            String text = new String(decrypt);
            return text;
        }catch (Exception e){
            logger.error("解密失败",e);
            e.printStackTrace();
        }
        return null;
    }
}
