package com.sjkj.appthreefloor_tsgz.utils;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.core.content.FileProvider;


import com.sjkj.appthreefloor_tsgz.BuildConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

/**
 * CREATE BY liyang
 * ON 2020-04-10
 * SUPPLY : Thanks for watching
 */
public class Method {



    /**
     * 获取当前的时间戳
     */
    public static String getTimeStamp() {
        long millis = System.currentTimeMillis();
        return millis + "";
    }

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /**
     * 时间戳转字符串
     */
    public static String getStrTime(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l));//单位秒
        return timeString;
    }

    /**
     * 时间戳转字符串
     */
    public static String getStrTime1(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l));//单位秒
        return timeString;
    }

    /**
     * 时间戳转字符串
     */
    public static String getStrTime2(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l));//单位秒
        return timeString;
    }

    /**
     * 时间戳转字符串
     */
    public static String getStrTime3(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l));//单位秒
        return timeString;
    }

    /**
     * 时间戳转字符串
     */
    public static String getStrTime4(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l));//单位秒
        return timeString;
    }

    /**
     * 时间戳转字符串
     */
    public static String getStrTime5(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l));//单位秒
        return timeString;
    }

    /**
     * 时间戳转字符串
     */
    public static String getStrTime6(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l));//单位秒
        return timeString;
    }

    /**
     * 时间戳转字符串
     */
    public static String getStrTime7(String timeStamp) {
        Calendar ca = Calendar.getInstance();
        int month = ca.get(Calendar.MONTH) + 1;
        return month + "";
    }

    /**
     * @param firstDate
     * @param lastDate
     * @return result＝0两个日期相等，result < 0表示firstDate 小与lastDate
     */
    public static int compareDate(String firstDate, String lastDate) {
        java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(df.parse(firstDate));
            c2.setTime(df.parse(lastDate));
        } catch (ParseException e) {
            System.err.println("格式不正确");
        }
        int result = c1.compareTo(c2);
        return result;
    }

    /**
     * @param firstDate
     * @param lastDate
     * @return result＝0两个日期相等，result < 0表示firstDate 小与lastDate
     */
    public static int compareDate2(String firstDate, String lastDate) {
        java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(df.parse(firstDate));
            c2.setTime(df.parse(lastDate));
        } catch (ParseException e) {
            System.err.println("格式不正确");
        }
        int result = c1.compareTo(c2);
        return result;
    }

    /**
     * 格式化日期时间 返回数据格式 12月27日 星期日
     */
    public static String formatDate2(String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("E");
        Date date_util = sdf.parse(date); // 转换为util.date
        String week = sdf2.format(date_util);
        String monthString = "";
        String dayString = "";
        if ("Sunday".equals(week)) {
            week = "日";
        } else if ("Monday".equals(week)) {
            week = "一";
        } else if ("Tuesday".equals(week)) {
            week = "二";
        } else if ("Wednesday".equals(week)) {
            week = "三";
        } else if ("Thursday".equals(week)) {
            week = "四";
        } else if ("Friday".equals(week)) {
            week = "五";
        } else if ("Saturday".equals(week)) {
            week = "六";
        }
        String showTimeString = "";
        int years = Integer.parseInt(date.substring(0, date.indexOf("-")));
        int month = Integer.parseInt(date.substring(date.indexOf("-") + 1, date.lastIndexOf("-")));
        int day = Integer.parseInt(date.substring(date.length() - 2, date.length()));
        monthString = month + "";
        dayString = day + "";
        if (month < 10) {
            monthString = "0" + month;
        }

        if (day < 10) {
            dayString = "0" + day;
        }
        showTimeString = years + "年" + monthString + "月" + dayString + "日 " + week;
        return showTimeString;

    }

    /**
     * 计算年月日
     *
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static String getStrDate(int year, int month, int day) {
        String date = null;
        if (month + 1 < 10) {
            if (day < 10) {
                date = new StringBuffer().append(year).append("-").append("0").
                        append(month + 1).append("-").append("0").append(day).toString();
            } else {
                date = new StringBuffer().append(year).append("-").append("0").
                        append(month + 1).append("-").append(day).toString();
            }

        } else {
            if (day < 10) {
                date = new StringBuffer().append(year).append("-").
                        append(month + 1).append("-").append("0").append(day).toString();
            } else {
                date = new StringBuffer().append(year).append("-").
                        append(month + 1).append("-").append(day).toString();
            }
        }
        return date;
    }

    public static String completionDate(int number) {
        String num = "";
        if (number < 10) {
            num = new StringBuffer().append("0").append(number).toString();
        } else {
            num = number + "";
        }
        return num;
    }

    public static String differDuration(String firstDate, String lastDate) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date first = null;
        Date last = null;
        try {
            first = simpleDateFormat.parse(firstDate);
            last = simpleDateFormat.parse(lastDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long fs = first.getTime();
        long lt = last.getTime();

        if ((lt - fs) / 1000 / 60 / 60 > 0)
            return (lt - fs) / 1000 / 60 / 60 + "小时";
        else
            return (lt - fs) / 1000 / 60 + "分钟";
    }

    /**
     * 创建文件
     */
    public static void createFile(String filePath) {
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * 循环文件夹文件
     *
     * @return list
     */
    public static LinkedList<File> folderFiles(String filePath) {
        LinkedList<File> list = new LinkedList<>();
        File docFile = new File(filePath);
        File[] fileArray = docFile.listFiles();
        for (File f : fileArray) {
            if (f.isFile()) {
                list.add(f);
            }
        }
        return list;
    }

    /**
     * 拷贝文件到新的地址
     */
    public static boolean copyFile(String path, String copyPath) {
        try {
            Method.createFile(copyPath);
            File oldfile = new File(path);
            File newFile = new File(copyPath + "/" + oldfile.getName());
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            try {
                //获得原文件流
                FileInputStream inputStream = new FileInputStream(oldfile);
                byte[] data = new byte[1024];
                //输出流
                FileOutputStream outputStream = new FileOutputStream(newFile);
                //开始处理流
                while (inputStream.read(data) != -1) {
                    outputStream.write(data);
                }
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 后缀判断当前文件是哪里类型，并且截取
     *
     * @param fileName
     * @return
     */
    public static String expandName(String fileName) {
        try {
            /* 依扩展名的类型决定MimeType */
            if (fileName.contains("m4a") || fileName.contains("mp3") || fileName.contains("mid") || fileName.contains("xmf")
                    || fileName.contains("ogg") || fileName.contains("wav") || fileName.contains("3gp") || fileName.contains("mp4")
                    || fileName.contains("jpg") || fileName.contains("gif") || fileName.contains("png") || fileName.contains("jpeg")
                    || fileName.contains("bmp") || fileName.contains("apk") || fileName.contains("ppt") || fileName.contains("xls")
                    || fileName.contains("xlsx") || fileName.contains("doc") || fileName.contains("docx") || fileName.contains("pdf") || fileName.contains("chm") || fileName.contains("txt")) {
                /* 截取后缀名字全城 */
                String end = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(Locale.getDefault());
                if (end.contains("(")) {
                    String expand = end.substring(0, end.indexOf("(")).toLowerCase(Locale.getDefault());
                    return fileName.substring(0, fileName.lastIndexOf(".") + 1) + expand;
                } else {
                    return fileName;
                }
            } else {
                return fileName;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return fileName;
        }
    }

    /**
     * 判断是否存在文件
     *
     * @param fileName
     * @return
     */

    public static boolean isExist(String fileName) {
        if (new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/" + fileName).exists())
            return true;
        else return false;
    }

    /**
     * 点击确定软键盘收回
     */
    public static void KeyboardBack(Activity activity) {
        View v = activity.getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 丰文
     *
     * @param content
     * @param start
     * @param end
     * @param color
     * @param textView
     */
    public static void isSpannable(String content, int start, int end, String color, TextView textView) {
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor(color));
        stringBuilder.setSpan(foregroundColorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(stringBuilder);
    }

    /**
     * 颜色标记
     *
     * @param year
     * @param month
     * @param day
     * @param color
     * @param text
     * @return
     */
    public static com.haibin.calendarview.Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        com.haibin.calendarview.Calendar calendar = new com.haibin.calendarview.Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }

    /**
     * @return
     */
    public static List<String> isWindDirection() {
        List<String> list = new ArrayList<>();
        list.add("东风");
        list.add("南风");
        list.add("西风");
        list.add("北风");
        list.add("东北风");
        list.add("西北风");
        list.add("东南风");
        list.add("西南风");
        return list;
    }

    /**
     * file --> uri
     *
     * @param context
     * @param file
     * @return
     */
    public static Uri getUriFromFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID+".fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }


    /**
     * 判断字符串是否为空
     */

    public static boolean isEmpty(String content) {
        if ("".equals(content) || "null".equals(content) || null == content) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 时间戳转字符串
     */
    public static String getDialogueTime(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l));//单位秒
        return timeString;
    }



    /**
     * 获取当前本地apk的版本
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0m";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1000) {
            fileSizeString = df.format((double) fileS) + "m";
        } else {
            fileSizeString = df.format((double) fileS / 1000) + "km";
        }
        return fileSizeString;
    }


    /**
     * 跳转拨打电话
     *
     * @param number
     */
    public static void getPhoneNumber(Context context,String number) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

}
