package com.gree.mall.manager.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.*;

/**
 * @Author: duke
 * @Date: 2019-08-07 09:29
 */
public class Utils {

    public static HashMap<String,Object> jsonToMap(String json){
        JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
        HashMap<String, Object> map = JSON.parseObject(json, new TypeReference<HashMap<String, Object>>(){});
        return map;
    }

    /**
     *
     * @param objectInstance
     * @return
     */
    public static HashMap<String,Object> objectToMap(Object objectInstance){
        JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
        String str = JSON.toJSONString(objectInstance, SerializerFeature.WriteDateUseDateFormat);
        HashMap<String, Object> map = JSON.parseObject(str, new TypeReference<HashMap<String, Object>>(){});
        return map;
    }

    /**
     * 输出堆栈信息
     * @param e
     * @return
     */
    public static String excptionStackToString(Exception e) {

        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            //将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }

        return pw.toString();

    }

    /**
     * 返回http请求URL
     * @param request
     * @return
     */
    public static String getRequstUrl(HttpServletRequest request){
        if(request.getQueryString() != null){
            return request.getMethod() + " " + request.getRequestURL() + "?" + request.getQueryString();
        }

        return request.getMethod() + " " + request.getRequestURL().toString();
    }

    public static HashMap<String, Object> stringToMap(String content) {

        JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

        HashMap<String, Object> map = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {
        });

        return map;

    }

    /**
     * 解密：对加密后的十六进制字符串(hex)进行解密，并返回字符串
     *
     * @return 解密后的字符串
     */
    public static String decrypt(String data, String key, String iv, String encodingFormat){

        //被加密的数据
        byte[] dataByte = Base64.decodeBase64(data);
        //加密秘钥
        byte[] keyByte = Base64.decodeBase64(key);
        //偏移量
        byte[] ivByte = Base64.decodeBase64(iv);

        try {

            Security.addProvider(new BouncyCastleProvider());

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");

            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));

            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化

            System.out.println("dataByte:"+dataByte);

            byte[] resultByte = cipher.doFinal(dataByte);

            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, encodingFormat);
                return result;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据指定大小分割list
     * 非均分，最后一组数量可能小于其它组数量
     * @param list
     * @param unitSize
     * @return
     */
    public static <T> List<List<T>> splitList(List<T> list, int unitSize) {
        if (list == null || list.isEmpty() || unitSize < 1)
            return null;

        int wholeSize = list.size();
        int groupNum = wholeSize / unitSize;
        List<List<T>> result = new ArrayList<List<T>>();

        for (int i = 0; i < groupNum; i++) {
            List<T> subList = list.subList(i * unitSize, (i + 1) * unitSize);
            result.add(subList);
        }

        if(unitSize * groupNum < wholeSize){
            List<T> restList = list.subList(unitSize * groupNum, wholeSize);
            result.add(restList);
        }

        return result;
    }


    /**
     * 获取兑换码
     * @param num
     * @return
     */
    public static Set<String> getExchangeCode(int num){

        Set<String> set = new HashSet<>();
        for(int i = 0;i < num; i++) {
            set.add(RC4Utils.encry_RC4_string(String.format("%04d", i), UUID.randomUUID().toString()));
        }
        return set;
    }

    /**
     * 报名码
     */
    public static String signUpNo(String str){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.toCharArray().length; i++) {
            char[] charArray = str.toCharArray();

            if(i > 0 && i % 4 == 0){
                sb.append("-");
            }
            sb.append(charArray[i]);
        }
        return sb.toString();
    }


}
