package com.reptileclient.jlifeapp.util;

import java.io.*;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ComonUtils {

    /**
     * 根据15位的身份证号码获得18位身份证号码
     *
     * @param fifteenIDCard 15位的身份证号码
     * @return 升级后的18位身份证号码
     * @throws Exception 如果不是15位的身份证号码，则抛出异常
     */
    public String getEighteenIDCard(String fifteenIDCard) throws Exception {
        if (fifteenIDCard != null && fifteenIDCard.length() == 15) {
            StringBuilder sb = new StringBuilder();
            sb.append(fifteenIDCard.substring(0, 6)).append("19").append(fifteenIDCard.substring(6));
            sb.append(getVerifyCode(sb.toString()));
            return sb.toString();
        } else {
            throw new Exception("不是15位的身份证");
        }
    }

    /**
     * 获取校验码
     *
     * @param idCardNumber 不带校验位的身份证号码（17位）
     * @return 校验码
     * @throws Exception 如果身份证没有加上19，则抛出异常
     */
    public static char getVerifyCode(String idCardNumber) throws Exception {
        if (idCardNumber == null || idCardNumber.length() < 17) {
            throw new Exception("不合法的身份证号码");
        }
        char[] Ai = idCardNumber.toCharArray();
        int[] Wi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] verifyCode = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int S = 0;
        int Y;
        for (int i = 0; i < Wi.length; i++) {
            S += (Ai[i] - '0') * Wi[i];
        }
        Y = S % 11;
        return verifyCode[Y];
    }

    /**
     * 校验18位的身份证号码的校验位是否正确
     *
     * @param idCardNumber 18位的身份证号码
     * @return
     * @throws Exception
     */
    public static boolean verify(String idCardNumber) throws Exception {
        if (idCardNumber == null || idCardNumber.length() != 18) {
            throw new Exception("不是18位的身份证号码");
        }
        return getVerifyCode(idCardNumber) == idCardNumber.charAt(idCardNumber.length() - 1);
    }

    public static int getAge(Date birthDate) {

        if (birthDate == null) {
            throw new RuntimeException("出生日期不能为null");
        }
        int age = 0;

        Date now = new Date();

        SimpleDateFormat format_y = new SimpleDateFormat("yyyy");
        SimpleDateFormat format_M = new SimpleDateFormat("MM");

        String birth_year = format_y.format(birthDate);
        String this_year = format_y.format(now);

        String birth_month = format_M.format(birthDate);
        String this_month = format_M.format(now);

        // 初步，估算
        age = Integer.parseInt(this_year) - Integer.parseInt(birth_year);

        // 如果未到出生月份，则age - 1
        if (this_month.compareTo(birth_month) < 0) {
            age -= 1;
        }
        if (age < 0) {
            age = 0;
        }
        return age;
    }

    public static Date format2Data(String strDate) {
        if (strDate == null || strDate.equals("")) {
            return null;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @throws FileNotFoundException
     */
    public static void copyFile(String oldPath, String newPath) throws FileNotFoundException {
        try {
            FileInputStream fis = new FileInputStream(oldPath);
            FileOutputStream fos = new FileOutputStream(newPath);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = fis.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("复制失败");
        }
    }

    /**
     * 创建单个文件
     *
     * @throws Exception
     */
    public static File createFile(String newPath, String newFileName) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddmmHHss");
        Date dd = new Date();
        File f = new File(newPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        File file = new File(f, newFileName);
        File file2 = null;
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            file2 = new File(f, dateFormat.format(dd) + newFileName);
            file2.createNewFile();
        }
        if (file2 == null) {
            return file;
        } else {
            return file2;
        }
    }

    /**
     * 根据指定的日期范围 获取连续月份
     *
     * @param minDate
     * @param maxDate
     * @return
     */
    public static List<String> getMonthBetween(String minDate, String maxDate) {
        ArrayList<String> result = new ArrayList<String>();
        // 格式化为年月
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        try {
            min.setTime(sdf.parse(minDate));
            max.setTime(sdf.parse(maxDate));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return result;
    }

    /**
     * 字符串转制定格式Date
     *
     * @param date
     * @param fmort
     * @return
     */
    public static Date getDate(String date, String fmort) {
        // yyyy-MM-dd HH:mm:ss
        Date date1 = null;
        SimpleDateFormat simdate1 = new SimpleDateFormat(fmort);

        try {
            date1 = simdate1.parse(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return date1;
    }

    /**
     * 制定格式Date转字符串
     *
     * @param date
     * @return
     */
    public static String getStrDate(Date date) {
        if (null != date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(date);
        }
        return null;
    }

    /**
     * 字符串分割
     *
     * @param str
     * @return
     */
    public static String[] getStrSplit(String str) {
        return str.split(" - ");
    }

    public static void main(String[] args) {
        Date s = ComonUtils.getDate("2018-12-12 12:22", "yyyy-MM-dd HH:mm");
        System.out.println(s);
    }

}
