package com.jkcredit.invoice.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.Key;

/**
 *
 * @author Administrator
 * @date 2017/11/25
 * base64加解密工具类
 */
public class LogUtils {
    private static final String PASSWORD_CRYPT_KEY = "3cm.xin.";

    private static final String MOBILE = "mobile";


    private static final String NAME = "name";


    private static final String ID_NUMBER = "id_number";


    private static final String IDCARD = "idcard";


    private static final String BANK_CARD_NUMBER = "bank_card_number";


    private static final String BANK_NO = "bank_no";

    private static final String UTF = "UTF-8";

    private static final int EIGHT = 8;

    /**
     * @param data
     * @return
     * @throws Exception
     */
    public static String decode(String data) throws Exception {
        JSONObject object = JSONObject.parseObject(data);
        if (object.get(MOBILE) != null) {
            object.put(MOBILE, decryptDes(object.getString(MOBILE)));
        }
        if (object.get(NAME) != null) {
            object.put(NAME, decryptDes(object.getString(NAME)));
        }
        if (object.get(ID_NUMBER) != null) {
            object.put(ID_NUMBER, decryptDes(object.getString(ID_NUMBER)));
        }
        if (object.get(IDCARD) != null) {
            object.put(IDCARD, decryptDes(object.getString(IDCARD)));
        }
        if (object.get(BANK_CARD_NUMBER) != null) {
            object.put(BANK_CARD_NUMBER, decryptDes(object.getString(BANK_CARD_NUMBER)));
        }
        if (object.get(BANK_NO) != null) {
            object.put(BANK_NO, decryptDes(object.getString(BANK_NO)));
        }
        return object.toString();
    }

    /**
     * 二进制数据编码为BASE64字符串
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encode(String data) {
        try {
            data = URLDecoder.decode(data, "utf-8");
            JSONObject object = JSONObject.parseObject(data);
            if (object.get(MOBILE) != null) {
                object.put(MOBILE, encryptDes(object.getString(MOBILE)));
            }
            if (object.get(NAME) != null) {
                object.put(NAME, encryptDes(object.getString(NAME)));
            }
            if (object.get(ID_NUMBER) != null) {
                object.put(ID_NUMBER, encryptDes(object.getString(ID_NUMBER)));
            }
            if (object.get(IDCARD) != null) {
                object.put(IDCARD, encryptDes(object.getString(IDCARD)));
            }
            if (object.get(BANK_CARD_NUMBER) != null) {
                object.put(BANK_CARD_NUMBER, encryptDes(object.getString(BANK_CARD_NUMBER)));
            }
            if (object.get(BANK_NO) != null) {
                object.put(BANK_NO, encryptDes(object.getString(BANK_NO)));
            }
            return object.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 加密数据
     *
     * @param encryptString 注意：这里的数据长度只能为8的倍数
     * @return
     * @throws Exception
     */
    public static String encryptDes(String encryptString) {
        try {
            StringBuffer sb = new StringBuffer();
            sb.append(encryptString);
            for (int i = 0; i < EIGHT - encryptString.getBytes(UTF).length % EIGHT; i++) {
                sb.append("=");
            }
            encryptString = sb.toString();
            SecretKeySpec key = new SecretKeySpec(getKey(PASSWORD_CRYPT_KEY), "DES");
            Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptedData = cipher.doFinal(encryptString.getBytes(StandardCharsets.UTF_8));
            return Base64.encodeBase64String(encryptedData);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return encryptString;
    }

    /***
     * 解密数据
     * @param decryptString
     * @return
     * @throws Exception
     */
    public static String decryptDes(String decryptString) throws Exception {
        SecretKeySpec key = new SecretKeySpec(getKey(PASSWORD_CRYPT_KEY), "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(Base64.decodeBase64(decryptString));
        return new String(decryptedData).replaceAll("=", "");
    }

    /**
     * 自定义一个key
     *
     * @param keyRule
     */
    public static byte[] getKey(String keyRule) {
        Key key = null;
        byte[] keyByte = keyRule.getBytes();
        // 创建一个空的八位数组,默认情况下为0
        byte[] byteTemp = new byte[8];
        // 将用户指定的规则转换成八位数组
        for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
            byteTemp[i] = keyByte[i];
        }
        key = new SecretKeySpec(byteTemp, "DES");
        return key.getEncoded();
    }

    public static void main(String[] args) throws Exception {
        String a = "{\"id_number\":\"36042919960907151X\",\"bank_card_number\":\"6214680048545055\",\"name\":\"刘玺\",\"mobile\":\"13875012909\",\"sign\":\"a93471e386fed0427c68bd6e9967011b\"}";
        System.out.println(encode(a));
        String b = "{\"sign\":\"a93471e386fed0427c68bd6e9967011b\",\"id_number\":\"nzJWETbb5o7owivoUsg/TQ==\",\"name\":\"5YiY5466\",\"bank_card_number\":\"NjIxNDY4MDA0ODU0NTA1NQ==\",\"mobile\":\"MTU4NzMwNTI4MzY=\"}";
        System.out.println(decode(encode(a)));
        System.out.println(decode(b));
    }
}
