package com.dsideal.sso.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONObject;
import com.dsideal.sso.Model.LoginModel;
import com.jfinal.kit.PropKit;
import org.apache.commons.codec.digest.DigestUtils;

import org.apache.commons.codec.binary.Base64;


public class CommonUtil {
    /**
     * 功能：封装一个返回json信息的函数
     * 作者：黄海
     * 时间：2018-11-06
     *
     * @param result
     * @param message
     */
    public static Map<String, Object> returnMessageJson(boolean result, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", result);
        map.put("message", message);
        return map;
    }

    public static Map<String, Object> returnMessageJson(boolean result, JSONObject jo) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", result);
        map.put("result", jo);
        return map;
    }

    public static Map<String, Object> returnMessageJson(boolean result, List<Record> list) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", result);
        map.put("result", list);
        return map;
    }

    /**
     * 将字符串参数转为Map
     *
     * @param strUrlParam
     * @return
     */
    public static Map<String, String> urlSplit(String strUrlParam) {
        Map<String, String> mapRequest = new HashMap<>();
        String[] arrSplit;
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");
            if (arrSplitEqual.length > 1) {
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    /**
     * 获取6位随机数
     *
     * @return
     */
    public static String getRandom() {
        String sources = "0123456789";
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 6; j++) {
            flag.append(sources.charAt(rand.nextInt(9)) + "");
        }

        return flag.toString();
    }

    /**
     * 验证是否为手机号
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     *
     * @param phoneNum
     * @return
     */
    public static boolean getIsPhoneLegal(String phoneNum) {
        try {
            String regExp = "^((13[0-9])|(19[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
            Pattern p = Pattern.compile(regExp);
            Matcher m = p.matcher(phoneNum);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 功能：将文本文件的内容读到字符串里
     * 作者：黄海
     * 时间：2018-11-22
     *
     * @param file
     * @return
     */
    public static String txt2String(File file) {
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 验证是否为邮箱
     *
     * @param eMail
     * @return
     */
    public static boolean getIsEmailLegal(String eMail) {
        try {
            String regExp = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern p = Pattern.compile(regExp);
            Matcher m = p.matcher(eMail);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 功能：校验密码强度
     * 作者：吴缤
     * 日期：2019-01-19
     *
     * @param pwd
     * @return
     */
    public static boolean getPwdLegal(String pwd) {
        boolean flag = false;
        try {
            String regExp = "[a-z0-9A-Z]+";
            Pattern p = Pattern.compile(regExp);
            Matcher m = p.matcher(pwd);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 判断账户是是用户名还是手机号还是邮箱
     * 1:用户名
     * 2:手机号
     * 3:邮箱
     *
     * @param userName
     * @return
     */
    private static int getUserNameType(String userName) {
        int flag = 1;
        try {
            if (getIsPhoneLegal(userName)) {
                flag = 2;
            } else if (getIsEmailLegal(userName)) {
                flag = 3;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 根据用户类型获取登录信息
     *
     * @param userName
     * @return
     */
    public static Map<String,String>  getLoginRouteMap(String userName) {
        LoginModel lm = new LoginModel();
        return lm.getLoginInfoByUserName(userName);
    }

    /**
     * 功能：简单的md5加密
     * 作者：黄海
     * 时间：2018-11-06
     *
     * @param target
     * @return
     */
    public static String md5(String target) {
        return DigestUtils.md5Hex(target);
    }

    //算法：将密码经过 MD5 运算，得到 32 字节的字符串，然后每2个字节压缩成一个十六进制字符，
    // 这样得到16字节的字符串，最后经过Base64编码。
    public static String getLdapPassword(String password) {
        try {
            String md5pass = md5(password);
            byte[] baKeyword = new byte[md5pass.length() / 2];
            for (int i = 0; i < baKeyword.length; i++) {
                try {
                    baKeyword[i] = (byte) (0xff & Integer.parseInt(md5pass.substring(i * 2, i * 2 + 2), 16));
                } catch (Exception e) {
                    //log.error("======================错误密码：" + md5pass);
                    e.printStackTrace();
                }
            }
            String newstr = Base64.encodeBase64String(baKeyword);
            return newstr;
        } catch (Exception err) {
            //log.error("出错的密码：" + password);
            return null;
        }
    }

    /**
     * 功能：获取当前时间，按年月日+时分秒格式返回
     * 作者：黄海
     * 时间：2018-11-30
     *
     * @return
     */
    public static String GetCurrentTimeString() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        String nowTime = sdf.format(date);
        return nowTime;
    }

    /**
     * 功能：获取6位随机数
     * 作者：吴缤
     * 日期：2018-11-27
     *
     * @return
     */
    public static String getSixRandom() {
        String sources = "0123456789";
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 6; j++) {
            flag.append(sources.charAt(rand.nextInt(9)) + "");
        }
        return flag.toString();
    }


    public static String handleRedirectUrlParas(String redirect_url) {
        String redirectUrl = redirect_url;
        String[] paras = redirect_url.split("\\?");
        if (paras.length > 1) {
            String uri = paras[0];
            Map<String, String> parasMap = URLRequest(redirect_url);
            for (Map.Entry<String, String> entry : parasMap.entrySet()) {
                if (!entry.getKey().equals(PropKit.get("sso.sessionid"))) {
                    if (uri.indexOf("?") == -1) {
                        uri += "?" + entry.getKey() + "=" + entry.getValue();
                    } else {
                        uri += "&" + entry.getKey() + "=" + entry.getValue();
                    }
                }
            }
            redirectUrl = uri;
        }

        return redirectUrl;
    }

    private static Map<String, String> URLRequest(String URL) {
        Map<String, String> mapRequest = new HashMap<String, String>();

        String[] arrSplit;

        String strUrlParam = TruncateUrlPage(URL);
        if (strUrlParam == null) {
            return mapRequest;
        }
        // 每个键值为一组 www.2cto.com
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            // 解析出键值
            if (arrSplitEqual.length > 1) {
                // 正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    // 只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    private static String TruncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit;
        strURL = strURL.trim();
        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            }
        }
        return strAllParam;
    }
}
