package com.changfa.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 时间格式转换工具类
 */
public class TimeUtil {
    private static final String timeFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String dateFormat = "yyyy-MM-dd";

    static String[] units = { "", "十", "百", "千", "万", "十万", "百万", "千万", "亿",
            "十亿", "百亿", "千亿", "万亿" };
    static char[] numArray = { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' };


    /**
     * 时间日期格式
     *
     * @param time
     * @return
     * @throws ParseException
     */
    public static Date getTime(String time) throws ParseException {
        SimpleDateFormat ft = new SimpleDateFormat(timeFormat);
        return ft.parse(time);
    }

    /**
     * 时间日期格式
     *
     * @param time
     * @return
     */
    public static String getTime(Date time) {
        SimpleDateFormat ft = new SimpleDateFormat(timeFormat);
        return ft.format(time);
    }

    /**
     * 日期格式
     *
     * @param date
     * @return
     * @throws ParseException
     */
    public static Date getDate(String date) throws ParseException {
        SimpleDateFormat ft = new SimpleDateFormat(dateFormat);
        return ft.parse(date);
    }

    /**
     * 日期格式
     *
     * @param date
     * @return
     * @throws ParseException
     */
    public static String getDateStr(String date) throws ParseException {
        SimpleDateFormat ft = new SimpleDateFormat(dateFormat);
        return ft.format(ft.parse(date));
    }

    public static List<String> GetCurrentWeekAllDate(){

        // 获取当天的毫秒时间
        long currentTimeMillis = System.currentTimeMillis();

        List<String> list = getAllWeekDayDateByMillis(currentTimeMillis);
        return list;
    }

    private static List<String> getAllWeekDayDateByMillis(long timeMills){
        List<String> list = new ArrayList<String>();

        // 得到指定时间是周几
        String week = getWhatDaySomeday(timeMills);

        // 记录与周一的间隔天数
        int dayFromMonday=getHowManyDayFromMonday(week);

        // 获取这周第一天毫秒值
        long dayMillis = 24*60*60*1000;
        // 获取这周第一天的日子
        long firstOfWeekMillis = timeMills - dayFromMonday * dayMillis;

        // 使用 for 循环得到当前一周的日子（7天的日子）
        for(long i = firstOfWeekMillis;i<firstOfWeekMillis+ 7 *dayMillis;i+=dayMillis) {
            Date targetDate = new Date(i);

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String targetDay = format.format(targetDate);
            list.add(targetDay);
        }
        return list;
    }

    private static String getWhatDaySomeday(long timeMillis) {

        Date toDayDate = new Date(timeMillis);
        SimpleDateFormat formatE = new SimpleDateFormat("E");
        String week =null;
        try {
            week = formatE.format(toDayDate);
            System.out.println(week);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return week;
    }

    private static int getHowManyDayFromMonday(String someDay) {
        int day = 0;
        switch(someDay) {
            case "星期一":
                day=0;
                break;
            case "星期二":
                day=1;
                break;
            case "星期三":
                day=2;
                break;
            case "星期四":
                day=3;
                break;
            case "星期五":
                day=4;
                break;
            case "星期六":
                day=5;
                break;
            case "星期日":
                day=6;
                break;
            default:
                System.out.println("不存在这样的星期几 : "+ someDay);
                break;
        }

        return day;
    }

    /**
     * 日期格式
     *
     * @param date
     * @return
     */
    public static String getDate(Date date) {
        SimpleDateFormat ft = new SimpleDateFormat(dateFormat);
        return ft.format(date);
    }

    /**
     * 将日期转化成毫秒
     *
     * @param date
     * @return
     */
    public static Long getTimeMill(Date date) {
        return date.getTime();
    }

    /**
     * 将毫秒转化为日期
     *
     * @param time
     * @return
     */
    public static Date getTimeMill(Long time) {
        Date date = new Date();
        date.setTime(time);
        return date;
    }

    /**
     * 两个时间相差的分钟数
     *
     * @param time1
     * @param time2
     * @return
     * @Description:
     */
    public static Integer getDistanceMinutes(Date time1, Date time2) {
        try {
            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            String fromDate = simpleFormat.format(time1);
            String toDate = simpleFormat.format(time2);
            long from = simpleFormat.parse(fromDate).getTime();
            long to = simpleFormat.parse(toDate).getTime();
            int minutes = (int) ((to - from) / (1000 * 60));
            return minutes;
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }

    }


    public static  String getDay(Date date){
        String week = "";
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int weekday = calendar.get(Calendar.DAY_OF_WEEK);
        if (weekday == 1) {
            week = "星期日";
        } else if (weekday == 2) {
            week = "星期一";
        } else if (weekday == 3) {
            week = "星期二";
        } else if (weekday == 4) {
            week = "星期三";
        } else if (weekday == 5) {
            week = "星期四";
        } else if (weekday == 6) {
            week = "星期五";
        } else if (weekday == 7) {
            week = "星期六";
        }
        return week;
    }


    /**
     *
     * 字符串的日期格式的计算两个日期之间相差的天数
     * @param smdate
     * @param bdate
     * @author lingxin
     * @date 2021/12/20 10:02 AM
     * @return int
     */
    public static int daysBetween(String smdate,String bdate) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days=((time2-time1)/(1000*3600*24))+1;
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     *
     * 字符串的日期格式的计算两个日期之间相差的月数
     * @param smdate
     * @param bdate
     * @author lingxin
     * @date 2021/12/20 10:02 AM
     * @return int
     */
    public static int monthsBetween(String smdate,String bdate) throws ParseException{
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(getDate(smdate));
        c2.setTime(getDate(bdate));
        int year1 = c1.get(Calendar.YEAR);
        int year2 = c2.get(Calendar.YEAR);
        int month1 = c1.get(Calendar.MONTH);
        int month2 = c2.get(Calendar.MONTH);
        int day1 = c1.get(Calendar.DAY_OF_MONTH);
        int day2 = c2.get(Calendar.DAY_OF_MONTH);
        // 获取年的差值
        int yearInterval = year1 - year2;
        // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
        if (month1 < month2 || month1 == month2 && day1 < day2) {
            yearInterval--;
        }
        // 获取月数差值
        int monthInterval = (month1 + 12) - month2;
        if (day1 < day2) {
            monthInterval--;
        }
        monthInterval %= 12;
        int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
        return monthsDiff;
    }
    /**
     *
     * 字符串的日期格式的计算两个日期之间相差的年数
     * @param smdate
     * @param bdate
     * @author lingxin
     * @date 2021/12/22 4:49 PM 
     * @return int
     */
    public static int yearsBetween(String smdate,String bdate) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(sdf.parse(smdate));
        aft.setTime(sdf.parse(bdate));
        int surplus = aft.get(Calendar.DATE) - bef.get(Calendar.DATE);
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int year = aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR);
        System.out.println(result);
        if(result < 0){
            result = 1;
        }else if(result == 0){
            result = surplus <= 0 ? 0 : 1;
        }else{
            result = 0;
        }
        return Math.abs(year + result)+1;
    }

    /**
     *
     * 获取月份第一天
     * @param month
     * @author lingxin
     * @date 2021/12/22 4:01 PM
     * @return java.lang.String
     */
    public static String getFirstForMonth(String month) throws ParseException {
        String[] s = month.split("-");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(getFirstDay(Integer.valueOf(s[0]), Integer.valueOf(s[1])));
    }

    /**
     *
     * 获取月份最后一天
     * @param month
     * @author lingxin
     * @date 2021/12/22 4:01 PM
     * @return java.lang.String
     */
    public static String getLastForMonth(String month){
        String[] s = month.split("-");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return getLastDayOfMonth(Integer.valueOf(s[0]), Integer.valueOf(s[1]));
    }

    public static Date getFirstDay(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month - 1);
        c.set(Calendar.DAY_OF_MONTH, 1);
        return c.getTime();
    }
    public static String getfisrtdayofmonth(int year,int month)
    {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstday = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstday);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        String firstdayofmonth = sdf.format(cal.getTime());
        return firstdayofmonth;
    }

    public static Date getLastDay(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month - 1);
        int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        c.set(Calendar.DAY_OF_MONTH, lastDay);
        return c.getTime();
    }


    /**
     * 获取某月的最后一天
     *
     */
    public static String getLastDayOfMonth(String day)
    {
        String[] days = day.split("-");
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,Integer.valueOf(days[0]));
        //设置月份
        cal.set(Calendar.MONTH, Integer.valueOf(days[1])-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }

    /**
     * 月份加一
     * @param date
     * @return
     */
    public static String monthAddFrist(String date){
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Calendar ct=Calendar.getInstance();
            ct.setTime(df.parse(date));
            ct.add(Calendar.MONTH, +1);
            return df.format(ct.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 年份加一
     * @param date
     * @return
     */
    public static String yearAddFrist(String date){
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Calendar ct=Calendar.getInstance();
            ct.setTime(df.parse(date));
            ct.add(Calendar.YEAR, +1);
            return df.format(ct.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return "";
    }

    //数字转阿拉伯数字
    public static String foematInteger(int num) {
        char[] val = String.valueOf(num).toCharArray();
        int len = val.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            String m = val[i] + "";
            int n = Integer.valueOf(m);
            boolean isZero = n == 0;
            String unit = units[(len - 1) - i];
            if (isZero) {
                if ('0' == val[i - 1]) {
                    continue;
                } else {
                    sb.append(numArray[n]);
                }
            } else {
                sb.append(numArray[n]);
                sb.append(unit);
            }
        }
        return sb.toString();
    }

    /**
     * 获取某年第一天日期
     * @param year 年份
     * @return Date
     */
    public static String getYearFirst(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        String date = getDate(currYearFirst);
        return date;
    }

    /**
     * 获取某年最后一天日期
     * @param year 年份
     * @return Date
     */
    public static String getYearLast(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        String date = getDate(currYearLast);
        return date;
    }

    public static int daysBetweenformoney(Date date1,Date date2){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        long time1 = cal.getTimeInMillis();
        cal.setTime(date2);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 获取指定月份的前几个月
     * @param strDate 传入的字符串时间
     * @param num 想获取前几个月 就传几
     * @return
     */

    public static String getStrDate(String strDate,int num ){
        String stringDate="";
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");//格式化为2017-10
            Date month=formatter.parse(strDate);
            Calendar calendar = Calendar.getInstance();//得到Calendar实例
            calendar.setTime(month);
            calendar.add(Calendar.MONTH, -num);//把月份减三个月
            Date starDate = calendar.getTime();//得到时间赋给Data
            stringDate = formatter.format(starDate);//使用格式化Data
            return stringDate;
        }catch (Exception e){
            e.printStackTrace();
            return stringDate;
        }
    }

    public static String getLastDayOfMonth(int year,int month)
    {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }
}
