package com.cooleshow.base.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.TextAppearanceSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;

import com.cooleshow.base.widgets.span.QMUIAlignMiddleImageSpan;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Description:
 * Copyright  : Copyright (c) 2019
 * Company    : 大雅乐盟
 * Author     : r
 * Date       : 2019/8/22 15:08
 */
public class UiUtils {
    private final static Handler mainHand = new Handler(Looper.getMainLooper());

    public static void postDelayed(Runnable r, long delay) {
        mainHand.postDelayed(r, delay);
    }

    public static void setMargins(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

    public static SpannableString matcherSearchText(Context context, String text, int keyword, int color) {
        String key = keyword + "";
        SpannableString ss = new SpannableString(text);
        Pattern pattern = Pattern.compile(key);
        Matcher matcher = pattern.matcher(ss);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            ss.setSpan(new TextAppearanceSpan(context, color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//new ForegroundColorSpan(color)
        }
        return ss;
    }

    public static String formateTime(String dateString, String format) {
        if (TextUtils.isEmpty(dateString)) return "";
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateString);
            String ds = new SimpleDateFormat(format).format(date);
            return ds;
        } catch (ParseException e) {
            return "";
        }

    }

    public static String formateHourTime(String dateString, String format) {
        if (TextUtils.isEmpty(dateString)) return "";
        try {
            Date date = new SimpleDateFormat("HH:mm:ss").parse(dateString);
            String ds = new SimpleDateFormat(format).format(date);
            return ds;
        } catch (ParseException e) {
            return "";
        }

    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) < MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    public static int getMaxHeightAtRatio16_9(Context context) {
        float ratio = 16 / 9f;
        return getMaxHeightAtAspectRatio(context, ratio);
    }

    public static int getHeightAtRatio16_9(Context context, float width) {
        float ratio = 16 / 9f;
        return (int) (width / ratio);
    }

    public static int getMaxHeightAtAspectRatio(Context context, float ratio) {
        DisplayMetrics deviceSize = DeviceUtil.getDeviceSize(context);
        if (deviceSize != null) {
            int width = deviceSize.widthPixels;
            return (int) (width / ratio);
        }
        return 0;
    }

    public static SpannableString diffColorString(String bigSizeStr, String centerStr, String lastStr, int firstColor, int centerColor) {
        String tmpStr = bigSizeStr + centerStr + lastStr;
        SpannableString result = new SpannableString(tmpStr);
        try {
            result.setSpan(new ForegroundColorSpan(firstColor), 0, bigSizeStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            result.setSpan(new ForegroundColorSpan(centerColor), bigSizeStr.length(), bigSizeStr.length() + centerStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            result.setSpan(new ForegroundColorSpan(firstColor), bigSizeStr.length() + centerStr.length(), tmpStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static SpannableString diffColorString(String bigSizeStr, String lastStr, int firstColor, int lastColor) {
        String tmpStr = bigSizeStr + lastStr;
        SpannableString result = new SpannableString(tmpStr);
        try {
            result.setSpan(new ForegroundColorSpan(firstColor), 0, bigSizeStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            result.setSpan(new ForegroundColorSpan(lastColor), bigSizeStr.length(), tmpStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static SpannableString diffColorString(String bigSizeStr, String lastStr, int firstColor, int lastColor, Drawable iconDrawable) {
        String tmpStr = bigSizeStr + lastStr;
        try {
            String icon = "[icon]";
            SpannableString result = new SpannableString("[icon]" + tmpStr);

            if (iconDrawable != null) {
                iconDrawable.setBounds(0, 0, iconDrawable.getIntrinsicWidth(), iconDrawable.getIntrinsicHeight());
            }
            ImageSpan alignMiddleImageSpan = new QMUIAlignMiddleImageSpan(iconDrawable, QMUIAlignMiddleImageSpan.ALIGN_MIDDLE, 4);
            result.setSpan(alignMiddleImageSpan, 0, icon.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            result.setSpan(new ForegroundColorSpan(firstColor), icon.length(), icon.length() + bigSizeStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            result.setSpan(new ForegroundColorSpan(lastColor), icon.length() + bigSizeStr.length(), result.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            SpannableString spannableString = new SpannableString(tmpStr);
            return spannableString;

        }
    }

    public static String[] splitSubjectName(String subjectName) {
        if (TextUtils.isEmpty(subjectName)) {
            return null;
        }
        String[] split = subjectName.split(",");
        return split;
    }


    /**
     * 保留2位小数
     *
     * @param targetValue
     * @return
     */
    public static String convertDouble(double targetValue) {
        BigDecimal bd = new BigDecimal(targetValue);
        double result = bd.setScale(2, BigDecimal.ROUND_DOWN).doubleValue(); // 保留两位小数，不四舍五入(可选舍入模式)
        return String.valueOf(result);
    }

    public static String getCourseTimeString(String start, String end) {
        if (TextUtils.isEmpty(start) || TextUtils.isEmpty(end)) {
            return "";
        }
        if (TextUtils.isEmpty(start) && !TextUtils.isEmpty(end)) {
            return TimeUtils.date2String(TimeUtils.getDate(start), "yyyy-MM-dd HH:mm");
        }
        if (!TextUtils.isEmpty(start) && TextUtils.isEmpty(end)) {
            return TimeUtils.date2String(TimeUtils.getDate(end), "yyyy-MM-dd HH:mm");
        }
        String time = "";
        String startTime = TimeUtils.date2String(TimeUtils.getDate(start), "yyyy-MM-dd");
        String endTime = TimeUtils.date2String(TimeUtils.getDate(end), "yyyy-MM-dd");
        String startTimeText = TimeUtils.date2String(TimeUtils.getDate(start), "HH:mm");
        String endTimeText = TimeUtils.date2String(TimeUtils.getDate(end), "HH:mm");
        if (TextUtils.equals(startTime, endTime)) {
            time = startTime + " " + startTimeText + "-" + endTimeText;
        } else {
            time = startTime + " " + startTimeText + "-" + endTime + " " + endTimeText;
        }
        return time;
    }

    public static String getPianoCourseName(String courseTitle, int classNum) {
        if (classNum != 0) {
            return courseTitle + "第" + classNum + "课";
        } else {
            return courseTitle;
        }
    }
}
