package io.renren.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.math.BigInteger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;

/**
 * MyUtil by huwhois time 2019/11/12
 */
public class MyUtils {
    /**
     * 获取提交请求的ip
     * 
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 判断手机号phone是否正确格式
     * @param phone
     * @return
     */
    public static boolean checkPhone(String phone){
        Pattern pattern = Pattern.compile("^(1[3-9]\\d{9}$)");
        Matcher matcher = pattern.matcher(phone);
        
        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    public static List<Map<String, Object>> makeClassListTree(List<Map<String, Object>> list, String pid){
        List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
        for(Map<String, Object> map : list){
            if(pid.equals(map.get("pid").toString())){
                // System.out.println(map.get("id"));
                map.put("children", addChildClass(map,list));
                treeList.add(map);
            }
        }
        return treeList;
    }
     
    public static List<Object> addChildClass(Map<String, Object> parentMap, List<Map<String, Object>> list){
        List<Object> childList = new ArrayList<Object>();
        // 为每一个父节点增加子树（List形式，没有则为空的list）
        parentMap.put("children", childList);
         for (Map<String, Object> childMap : list){
            //如果子节点的pid等于父节点的ID，则说明是父子关系
            if(childMap.get("pid").toString().equals(parentMap.get("id").toString())){
                // 是父子关系，则将其放入子list字面
                childList.add(childMap);
                // 继续调用递归算法，将当前作为父节点，继续找他的子节点，反复执行。
                addChildClass(childMap, list);
            }
        }
        // 当遍历完成，返回调用的父节点的所有子节点
        return childList;
    }
}