package com.xinelu.common.utils;

import java.time.LocalDate;
import java.time.Period;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

/**
 * @description: 基本工具类
 * @author: mengkuiliang
 * @createDate: 2021-12-03 10:50
 */
public class BaseUtil {

    /**
     * @return java.lang.String
     * @Author mengkuiliang
     * @Description 根据身份证号计算年龄（周岁）
     * @Date 2021-12-03 11:03
     * @Param [identity]
     **/
    public static String calculateAgeByIdentity(String identity) {

        if (StringUtils.isBlank(identity)) {
            return "";
        }
        String age;
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DATE);
        int year = 0;
        int month = 0;
        int day = 0;
        if(identity.length() == 15) {
            year = 1900 + Integer.parseInt(identity.substring(6, 8));
            month = Integer.parseInt(identity.substring(8, 10));
            day = Integer.parseInt(identity.substring(10, 12));
        } else if(identity.length() == 18) {
            year = Integer.parseInt(identity.substring(6, 10));
            month = Integer.parseInt(identity.substring(10, 12));
            day = Integer.parseInt(identity.substring(12, 14));
        }


        if ((month < monthNow) || (month == monthNow && day <= dayNow)) {
            age = String.valueOf(yearNow - year);
        } else {
            age = String.valueOf(yearNow - year - 1);
        }
        return age;
    }

    /**
     * @return java.lang.String
     * @Author mengkuiliang
     * @Description 根据出生日期计算年龄（周岁）
     * @Date 2022-04-29 8:50
     * @Param [birthday]
     **/
    public static String calculateAgeByBirthdy(LocalDate birthday) {

        if (birthday == null) {
            return "";
        }
        String age;
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DATE);

        int year = birthday.getYear();
        int month = birthday.getMonthValue();
        int day = birthday.getDayOfMonth();

        if ((month < monthNow) || (month == monthNow && day <= dayNow)) {
            age = String.valueOf(yearNow - year);
        } else {
            age = String.valueOf(yearNow - year - 1);
        }
        return age;
    }

    /**
     * @return java.lang.String
     * @Author mengkuiliang
     * @Description 根据身份证号获取出生日期
     * @Date 2021-12-15 14:50
     * @Param [identity]
     **/
    public static LocalDate getBirthday(String identity) {
        if (StringUtils.isBlank(identity)) {
            return null;
        }
        String year = "";
        String month = "";
        String day = "";
        if(identity.length() == 15) {
            year = "19" + identity.substring(6, 8);
            month = identity.substring(8, 10);
            day = identity.substring(10, 12);
        } else if(identity.length() == 18) {
            year = identity.substring(6, 10);
            month = identity.substring(10, 12);
            day = identity.substring(12, 14);
        }
        return LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
    }

    /**
     * @return [1: 男 2：女]
     * @Author mengkuiliang
     * @Description 根据身份证号获取性别
     * @Date 2021-12-14 17:13
     * @Param
     **/
    public static String getGender(String identity) {
        if (StringUtils.isBlank(identity)) {
            return null;
        }
        Integer type = null;
        if(identity.length() == 15) {
            type = Integer.parseInt(identity.substring(14));
        } else if(identity.length() == 18) {
            type = Integer.parseInt(identity.substring(16, 17));
        }
        if(type == null) {
            return null;
        }
        if (type % 2 == 0) {
            return "FEMALE";
        } else {
            return "MALE";
        }
    }
	public static int getAge(LocalDate birthDate) {
		LocalDate currentDate = LocalDate.now();
		Period period = Period.between(birthDate, currentDate);
		return period.getYears();
	}

    /**
     * @return boolean
     * @Author mengkuiliang
     * @Description 是否包含汉字
     * @Date 2022-02-11 13:31
     * @Param [str]
     **/
    public static boolean bChineseCharacters(String str) {
        if (StringUtils.isBlank(str)) {
            return false;
        }
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * @return int
     * @Author mengkuiliang
     * @Description 获取指定字符串 在源字符串中 出现的次数
     * @Date 2022-03-09 15:56
     * @Param [source：源字符串, find：要查找的字符串]
     **/
    public static int appearNumber(String source, String find) {
        int count = 0;
        Pattern p = Pattern.compile(find);
        Matcher m = p.matcher(source);
        while (m.find()) {
            count++;
        }
        return count;
    }

    /**
     * @return int
     * @Author mengkuiliang
     * @Description 获取指定字符串 在源字符串中 第几次出现的位置
     * @Date 2022-03-09 15:56
     * @Param [source：源字符串, find：要查找的字符串, number：第几次]
     **/
    public static int appearNumberIndex(String source, String find, Integer number) {
        Matcher slashMatcher = Pattern.compile(find).matcher(source);
        int mIdx = 0;
        while (slashMatcher.find()) {
            mIdx++;
            if (mIdx == number) {
                break;
            }
        }
        return slashMatcher.start();
    }

    /**
     * @return java.lang.Boolean
     * @Author mengkuiliang
     * @Description 校验新版本是否大于最新版本
     * @Date 2022-03-10 8:39
     * @Param [lastVersion, newVersion]
     **/
    public static Boolean compareVersion(String lastVersion, String newVersion) {
        if (StringUtils.isBlank(lastVersion)) {
            return true;
        }
        if (StringUtils.isBlank(newVersion)) {
            return false;
        }
        String[] lastArray = lastVersion.split("\\.");
        String[] newArray = newVersion.split("\\.");
        // 获取最大长度
        int length = Math.max(lastArray.length, newArray.length);
        for (int i = 0; i < length; i++) {
            // 获取每个版本节点，挨个判断大小
            int lastV = i < lastArray.length ? Integer.parseInt(lastArray[i]) : 0;
            int newV = i < newArray.length ? Integer.parseInt(newArray[i]) : 0;
            if (lastV < newV) {
                return true;
            }
            if (lastV > newV) {
                return false;
            }
        }
        return false;
    }

    /**
     * 加密身份证号
     *
     * @param idNo 身份证号码
     *             <li>（1）把原字符串按字符循环获取 asc 码，并格式化为 3 位整数；</li>
     *             <li>（2）把数字字符串进行奇偶交换（第 1 位和第 2 位交换，第 3 位和第 4 位交换，
     *             依次类推，如果总长是奇数位，则最后一位不变），重新组合数字字符串</li>
     *             <li>例如：原字符串是“ab2”，第一步获取asc码转换为“097098050”，第二步转
     *             换就变成900789500</li>
     * @return {@link String}
     * @author gaoyu
     * @date 2022-05-18 14:28
     */
    public static String encryptIdNo(String idNo) {
        if (StringUtils.isEmpty(idNo)) {
            return "";
        }
        StringBuilder chars = new StringBuilder();
        for (int i = 0; i < idNo.length(); i++) {
            int asc_i = idNo.charAt(i);
            if (asc_i < 10) {
                chars.append("00").append(asc_i);
            } else if (asc_i < 100) {
                chars.append("0").append(asc_i);
            } else {
                chars.append(asc_i);
            }
        }
        String tempStr;
        String lastChar = "";
        if (chars.length() % 2 == 0) {
            tempStr = chars.toString();
        } else {
            tempStr = chars.substring(0, chars.length() - 1);
            lastChar = String.valueOf(chars.charAt(chars.length() - 1));
        }
        StringBuilder resultStr = new StringBuilder();
        for (int i = 0; i < tempStr.length(); i++) {
            if (i % 2 == 0) {
                resultStr.append(tempStr.charAt(i));
            } else {
                resultStr.insert(resultStr.length() - 1, tempStr.charAt(i));
            }
        }
        return resultStr.append(lastChar).toString();
    }

	/**
	 * @Author mengkuiliang
	 * @Description 判断是否为小数
	 * @Date 2023-03-13 15:20
	 * @Param [str]
	 * @return boolean
	 **/
	public static boolean isDecimal(String str){
		if(str != null) {
			Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
			Matcher isNum = pattern.matcher(str);
			if (!isNum.matches()) {
				return false;
			}
			return true;
		}
		return false;
	}

}
