package com.cmeeting.util;

//import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONUtil;
import com.cmeeting.ad.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.text.MessageFormat;
import java.time.ZonedDateTime;

@Slf4j
public class AESUtils {

////    @Value("${aec.key}")
//    public static  String AES_KEY = "biaopin123456789" ;

    /**
     * AES加密+Base64转码
     *
     * @param data 明文（16进制）
     * @return
     */
    public static String encrypt(String data,String AES_KEY) {
        byte[] keyb = null;
        try {
            keyb = AES_KEY.getBytes("utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } // 明文
        SecretKeySpec sKeySpec = new SecretKeySpec(keyb, "AES");
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        byte[] bjiamihou = null;
        String miwen = "";
        try {
            bjiamihou = cipher.doFinal(data.getBytes("utf-8"));
            // byte加密后
            miwen = Base64.encode(bjiamihou);// 密文用base64加密
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }

        return miwen;
    }

    /**
     * Base64解码 + AES解码
     *
     * @param data 密文 （16进制）
     * @return
     */
    public static String decrypt(String data,String AES_KEY){
        byte[] keyb = null;
        try {
            keyb = AES_KEY.getBytes("utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        byte[] miwen = Base64.decode(data);
        SecretKeySpec sKeySpec = new SecretKeySpec(keyb, "AES");
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        byte[] bjiemihou = null;
        String mingwen = "";
        try {
            bjiemihou = cipher.doFinal(miwen);
            // byte加密后
            mingwen = new String(bjiemihou,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mingwen;
    }

    public static Boolean decryptSign(HttpServletRequest request, String AES_KEY){
        String lid = request.getHeader("lid");
        log.info("lid=============" + lid);
        String sign = request.getHeader("sign");
        log.info("sign=============" +sign);
        String decrypt = decrypt(sign, AES_KEY);
        log.info("decrypt=============" + decrypt);
        if (StringUtils.isEmpty(lid) && StringUtils.isEmpty(sign) && StringUtils.isEmpty(decrypt)){
            return true;
        }
        if(!lid.equals(decrypt)){
            log.info("----判定成功");
            return true;
        }
        return false;
    }

    public static void main(String[] args) throws Exception {
//        String filePath = "D:/desktop/a.txt";
//        try {
//            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
//            String longStr = new String(bytes, StandardCharsets.UTF_8);
//            String miwen = decrypt(longStr,"");// 加密
//            System.out.println(miwen);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        UserVo.Auth auth = new UserVo.Auth();
        auth.setId("00015545");
        auth.setNick("李");
        long expireTimestamp = ZonedDateTime.now().plusDays(2).toInstant().toEpochMilli();
        auth.setExpireDate(expireTimestamp);
        String s = JSONUtil.toJsonStr(auth);
        String encrypt = AESUtils.encrypt(s, "biaopin123456789");
        System.out.println(encrypt);
        String url = "https://chatbottest.cimc.com:5277/login?token={0}&source=email";
        System.out.println(MessageFormat.format(url, URLEncoder.encode(encrypt)));
    }



}
