package com.fs.his.utils;

import com.fs.common.utils.ParseUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class PhoneUtil {

    public static String encryptPhone(String text) {
        String encryptedText=null;
        try {
            SecretKeySpec secretKey = new SecretKeySpec("AESAabCdeREssREA".getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            // Encryption
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(text.getBytes());
            encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedText;
    }
    /**
    * 解密
    */
    public static String decryptPhone(String encryptedText) {
        String text=null;
        try {
            SecretKeySpec secretKey = new SecretKeySpec("AESAabCdeREssREA".getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
            text = new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;
    }
    /**
    * 解密加*
    */
    public static String decryptPhoneMk(String encryptedText) {
        String text=null;
        try {
            SecretKeySpec secretKey = new SecretKeySpec("AESAabCdeREssREA".getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
            text = new String(decryptedBytes);
            text =text.replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;
    }

    public static String decryptAutoPhoneMk(String encryptedText) {
        String text=null;
        if (encryptedText!=null&&encryptedText!="") {
            if (encryptedText.length()>11){
                try {
                    SecretKeySpec secretKey = new SecretKeySpec("AESAabCdeREssREA".getBytes(), "AES");
                    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                    cipher.init(Cipher.DECRYPT_MODE, secretKey);
                    byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
                    text = new String(decryptedBytes);
                    text =text.replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                text =  ParseUtils.parsePhone(encryptedText);
            }
        }

        return text;
    }
}
