package com.zcloud.common.utils;

import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 说明：常用工具
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
public class Tools {

	/**
	 * 随机生成六位数验证码
	 * @return
	 */
	public static int getRandomNum(){
		Random r = new Random();
		return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
	}

	/**
	 * 随机生成四位数验证码
	 * @return
	 */
	public static int getRandomNum4(){
		Random r = new Random();
		return r.nextInt(9000)+1000;
	}

	/**
	 * 检测字符串是否不为空(null,"","null")
	 * @param s
	 * @return 不为空则返回true，否则返回false
	 */
	public static boolean notEmpty(String s){
		return s!=null && !"".equals(s) && !"null".equals(s);
	}

	/**
	 * 检测字符串是否为空(null,"","null")
	 * @param s
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmpty(String s){
		return s==null || "".equals(s) || "null".equals(s);
	}
	public static boolean isEmpty (Object obj) {
		return obj ==null || "".equals(obj);
	}
	/**
	 * 字符串转换为字符串数组
	 * @param str 字符串
	 * @param splitRegex 分隔符
	 * @return
	 */
	public static String[] str2StrArray(String str,String splitRegex){
		if(isEmpty(str)){
			return null;
		}
		return str.split(splitRegex);
	}

	/**
	 * 用默认的分隔符(,)将字符串转换为字符串数组
	 * @param str	字符串
	 * @return
	 */
	public static String[] str2StrArray(String str){
		return str2StrArray(str,",\\s*");
	}

	/**
	 * 比较两个数组，拿到不同的元素
	 * @param str	字符串
	 * @return
	 */
	public static <T> List<T> compare(T[] t1, T[] t2) {
		List<T> list1 = Arrays.asList(t1);
		List<T> list2 = Arrays.asList(t2);
		//用来保存最后结果的集合
		List<T> list3 = new ArrayList<>();
		for (T t : t2) {
			if (!list1.contains(t)) {
				list3.add(t);
			}
		}
		for (T t:t1) {
			if (!list2.contains(t)) {
				list3.add(t);
			}
		}
		return list3;
	}


	/**
	 * 验证邮箱
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email){
		boolean flag = false;
		try{
			String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		}catch(Exception e){
			flag = false;
		}
		return flag;
	}

	/**
	 * 验证手机号码
	 * @param mobileNumber
	 * @return
	 */
	public static boolean checkMobileNumber(String mobileNumber){
		boolean flag = false;
		try{
			Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
			Matcher matcher = regex.matcher(mobileNumber);
			flag = matcher.matches();
		}catch(Exception e){
			flag = false;
		}
		return flag;
	}

	/**
	 * 检测KEY是否正确
	 * @param paraname  传入参数
	 * @param FKEY		接收的 KEY
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean checkKey(String paraname, String FKEY){
		paraname = (null == paraname)? "":paraname;
		return MD5.md5(paraname+DateUtil.getDays()+",fh,").equals(FKEY);
	}
	/**
	 转半角的函数(DBC case)<br/><br/>
	 全角空格为12288，半角空格为32
	 其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
	 * @param input 任意字符串
	 * @return 半角字符串
	 *
	 */
	public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				//全角空格为12288，半角空格为32
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				//其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
	public static String excelHandle (String string) {
		String aString = string.replaceAll(" ", "");
		aString = ToDBC(aString);
		aString = replaceBlank(aString);
		return aString;
	}
	public static String excelHandle (Object object) {
		String aString = object.toString().replaceAll(" ", "");
		aString = ToDBC(aString);
		aString = replaceBlank(aString);
		return aString;
	}
	public static String get32UUID() {
		String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
		return uuid;
	}

	public static String uploadFile(MultipartFile file, String folder) {
		String ffile = DateUtil.getDays();
		String fileName = get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String path = "/uploadFiles/" + folder + "/" + ffile;
		FileUploadUtil.sshSftp(file, fileName, path);
		return "/uploadFiles/" + folder + "/" + ffile +"/" + fileName;
	}

	public static boolean isNotBlank(Object obj){
		return obj!=null &&!"".equals(obj);
	}



	/**
	 * 构建树形结构
	 *
	 * @param entities 实体集合
	 *              idFieldName id字段名称
	 *              parentIdFieldName parentId字段名称
	 *              childrenFieldName children字段名称
	 **/
	public static <T> List<T> buildEntityTree(List<T> entities, String idFieldName, String parentIdFieldName, String childrenFieldName) {
		if (entities == null || entities.isEmpty()) {
			return new ArrayList<>();
		}

		List<T> result = new ArrayList<>();

		try {
			Field idField = getField(entities.get(0).getClass(), idFieldName);
			Field parentIdField = getField(entities.get(0).getClass(), parentIdFieldName);
			Field childrenField = getField(entities.get(0).getClass(), childrenFieldName);

			if (idField == null || parentIdField == null) {
				throw new IllegalArgumentException("Invalid idFieldName or parentIdFieldName or childrenField");
			}

			Map<Object, T> entityMap = new HashMap<>();
			for (T entity : entities) {
				idField.setAccessible(true);
				Object id = idField.get(entity);
				entityMap.put(id, entity);
			}

			for (T entity : entities) {
				parentIdField.setAccessible(true);
				Object parentId = parentIdField.get(entity);
				if(parentId == null || parentId.equals("0") || parentId.equals("-1")){
					result.add(entity); // 根节点

				}else{
					T parentEntity = entityMap.get(parentId);
					if (parentEntity != null) {
						if (childrenField != null) {
							childrenField.setAccessible(true);
							List<T> children = (List<T>) childrenField.get(parentEntity);
							if (children == null) {
								children = new ArrayList<>();
							}
							children.add(entity);
							childrenField.set(parentEntity, children);
						}
					}
				}
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

		return result;
	}
	/**
	 * 构建树形结构
	 *
	 * @param entities 实体集合
	 *              idFieldName id字段名称
	 *              parentIdFieldName parentId字段名称
	 *              childrenFieldName children字段名称
	 *              rootId  根节点id
	 **/
	public static <T> List<T> buildEntityTree(List<T> entities, String idFieldName, String parentIdFieldName, String childrenFieldName, String rootId) {
		if (entities == null || entities.isEmpty()) {
			return new ArrayList<>();
		}

		List<T> result = new ArrayList<>();

		try {
			Field idField = getField(entities.get(0).getClass(), idFieldName);
			Field parentIdField = getField(entities.get(0).getClass(), parentIdFieldName);
			Field childrenField = getField(entities.get(0).getClass(), childrenFieldName);

			if (idField == null || parentIdField == null) {
				throw new IllegalArgumentException("Invalid idFieldName or parentIdFieldName or childrenField");
			}

			Map<Object, T> entityMap = new HashMap<>();
			for (T entity : entities) {
				idField.setAccessible(true);
				Object id = idField.get(entity);
				entityMap.put(id, entity);
			}

			for (T entity : entities) {
				parentIdField.setAccessible(true);
				Object parentId = parentIdField.get(entity);
				if(parentId == null || parentId.equals("0") || parentId.equals("-1")
						|| (!ObjectUtils.isEmpty(rootId) && parentId.equals(rootId))){
					result.add(entity); // 根节点

				}else{
					T parentEntity = entityMap.get(parentId);
					if (parentEntity != null) {
						if (childrenField != null) {
							childrenField.setAccessible(true);
							List<T> children = (List<T>) childrenField.get(parentEntity);
							if (children == null) {
								children = new ArrayList<>();
							}
							children.add(entity);
							childrenField.set(parentEntity, children);
						}
					}
				}
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

		return result;
	}


	private static Field getField(Class<?> clazz, String fieldName) {
		try {
			return clazz.getDeclaredField(fieldName);
		} catch (NoSuchFieldException e) {
			// 若当前类不存在指定字段，则尝试从父类中获取
			Class<?> superClass = clazz.getSuperclass();
			if (superClass != null && superClass != Object.class) {
				return getField(superClass, fieldName);
			}
		}
		return null;
	}

	/**
	 * 获取文件的后缀名
	 *
	 * @param fileName 文件名
	 * @return 文件后缀名，如果没有后缀名则返回空字符串
	 */
	public static String getFileExtension(String fileName) {
		if (fileName == null || fileName.isEmpty()) {
			return "";
		}

		int lastDotIndex = fileName.lastIndexOf('.');
		if (lastDotIndex == -1) {
			return ""; // 没有后缀名
		}

		return fileName.substring(lastDotIndex + 1).toLowerCase();
	}

	/**
	 * 比较两个版本号的大小
	 *
	 * @param version1 第一个版本号字符串，各部分由点（.）分隔
	 * @param version2 第二个版本号字符串，各部分由点（.）分隔
	 * @return 返回值为1表示version1大于version2，-1表示version1小于version2，0表示两者相等
	 */
	public static int compareVersion(String version1, String version2) {
		// 将版本号字符串按照点（.）分割成各个部分
		String[] versionParts1 = version1.split("\\.");
		String[] versionParts2 = version2.split("\\.");
		// 确定比较的长度，取两个版本号部分数的最大值
		int length = Math.max(versionParts1.length, versionParts2.length);
		// 遍历每个部分进行比较
		for (int i = 0; i < length; i++) {
			// 获取当前部分的版本号，如果超出数组长度则默认为0
			int part1 = i < versionParts1.length ? Integer.parseInt(versionParts1[i]) : 0;
			int part2 = i < versionParts2.length ? Integer.parseInt(versionParts2[i]) : 0;
			// 比较两个版本号的部分，如果不同则返回比较结果
			if (part1 < part2) {
				return -1;
			} else if (part1 > part2) {
				return 1;
			}
		}
		// 如果所有部分都相等，则返回0
		return 0;
	}

	public static String videoTimeMinFormat(Double videoTime) {
		int minutes = (int) (videoTime / 60);
		int remainingSeconds = (int) (videoTime % 60);
		StringBuffer sb = new StringBuffer();
		if (minutes < 10) {
			sb.append("0").append(minutes);
		} else {
			sb.append(minutes);
		}
		sb.append(":");
		if (remainingSeconds < 10) {
			sb.append("0").append(remainingSeconds);
		} else {
			sb.append(remainingSeconds);
		}
		return sb.toString();
	}

	public static void main(String[] args) {

		String aString = "	afjaisjfasjfasij	";
		String bString = "";
		bString= excelHandle(aString);
		System.out.println("bString:"+bString+".");
		System.out.println("aString:"+aString+".");
	}

}
