package org.jeecg.modules.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.resource.ResourceUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * <p> 开放平台提供的 接口的des 加解密更加
 * 其中 密码是固定的，请不要修改
 * </p>
 */
public class DESUtil {

	/**
	 * 发票做des加解密的密钥
	 */
	private static final String INVOICE_KEY = "04810679";

	private static final String L_KEY = "foreseedzswj_2017";

	private static final Log log = LogFactory.getLog(DESUtil.class);

    private static byte[] encryptOrDecrypt(boolean encrypt, byte[] desKey, byte[] data) {
        if (data == null || data.length <= 0) {
            return null;
        }

        try {
            Cipher cipher;
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(desKey);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(dks);
            if (encrypt) {
                cipher = Cipher.getInstance("DES");
                cipher.init(Cipher.ENCRYPT_MODE, key, sr);
            } else {
                cipher = Cipher.getInstance("DES/ECB/NoPadding");
                //cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, key, sr);
            }

            return cipher.doFinal(data);
        } catch (Exception e) {
            return null;
        }
    }

    public static String encrypt(byte[] data, byte[] desKey) throws Exception {
        return Base64.encode(encryptOrDecrypt(true, desKey, data));
    }

    public static byte[] decrypt(String data, byte[] desKey) throws Exception {
        return encryptOrDecrypt(false, desKey, Base64.decode(data));
    }

    public static String encrypt(String data, String key) throws Exception {
        return Base64.encode(encryptOrDecrypt(true, key.getBytes(), data.getBytes()));
    }

    public static String decrypt(String data, String key) throws Exception {
        return new String(encryptOrDecrypt(false, key.getBytes(), Base64.decode(data)), StandardCharsets.UTF_8).trim();
    }

    public static String decrypt(String data, String key,String charSet) throws Exception {
        return new String(encryptOrDecrypt(false, key.getBytes(), Base64.decode(data)),charSet).trim();
    }






	public  static String encrypt(String json){
        //没配置openquery.desPassword 不加密
		if(StringUtils.isBlank(INVOICE_KEY)){
            return json;
        }
        //空值不加密
		if(StringUtils.isBlank(json)){
            return json;
        }
		String requestJson=json;
		try {
			requestJson = encrypt(json, INVOICE_KEY );
		} catch (Exception e) {
//			e.printStackTrace();
			log.info((new StringBuilder()).append("json:").append(json).append(" desPassword:").append(INVOICE_KEY).append(" err:").append(e.getMessage()));
		}
		return requestJson;
	}
	public  static String decrypt(String json){
        //没配置openquery.desPassword 不解密
		if(StringUtils.isBlank(INVOICE_KEY)){
            return json;
        }
        //空值不解密
		if(StringUtils.isBlank(json)){
            return json;
        }
		String requestJson=json;
		try {
			requestJson = decrypt(json, INVOICE_KEY );
		} catch (Exception e) {
			log.info((new StringBuilder()).append("json:").append(json).append(" desPassword:").append(INVOICE_KEY).append(" err:").append(e.getMessage()));
		}
		return requestJson;
	}

	public static String dlEncrypt(String data) throws Exception {
        return encrypt(data, L_KEY);
    }

	public static String dlDecrypt(String data) throws Exception {
        return decrypt(data, L_KEY);
    }


    public static void main(String[] args) throws Exception {
//        String aa="uCYJ7O/0wpVffoHaZcrKWA==";
//        String s = dlDecrypt(aa);
        String str = ResourceUtil.readUtf8Str("fx/temp/test.txt");
        String s = decrypt(str,"04810679");
        System.out.println(s);

//        System.out.println(aa);
//        System.out.println(dlEncrypt(s));

    }

}
