package com.sjkj.base_lib.utils;

import static java.util.regex.Pattern.matches;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.sjkj.base_lib.app.BaseApp;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class CommonUtils {
    public static void copyToClipboard(Context context, String text) {
        ClipboardManager clip = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        //clip.getText(); // 粘贴
        clip.setText(text); // 复制
    }

    public static String stringNotEmpty(String content) {
        return TextUtils.isEmpty(content) ? "" : content;
    }

    public static String stringNotEmpty(int content) {
        return TextUtils.isEmpty(content + "") ? "" : content + "";
    }

    public static String stringNotEmptyDefault(String content) {
        return TextUtils.isEmpty(content) ? "不详" : content;
    }

    public static boolean isMobileNO(String mobileNums) {
        /**
         * 判断字符串是否符合手机号码格式
         * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
         * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
         * 电信号段: 133,149,153,170,173,177,180,181,189
         * @param str
         * @return 待检测的字符串
         */
        String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表下一位为数字可以是几，"[0-9]"代表可以为0-9中的一个，"[5,7,9]"表示可以是5,7,9中的任意一位,[^4]表示除4以外的任何一个,\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }

    public static String getDeviceId() {
        return DeviceUuidFactory.getDeviceUuid(BaseApp.getInstance());
    }

    /**
     * 检查网络是否连通
     *
     * @return boolean
     * @since V1.0
     */
    public static boolean isNetworkAvailable(Context context) {
        // 创建并初始化连接对象
        ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // 判断初始化是否成功并作出相应处理
        if (connMan != null) {
            // 调用getActiveNetworkInfo方法创建对象,如果不为空则表明网络连通，否则没连通
            NetworkInfo info = connMan.getActiveNetworkInfo();
            if (info != null) {
                return info.isAvailable();
            }
        }
        return false;
    }

    public static int getDisplayHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    public static int getDisplayWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    private static long lastClickTime = 0;

    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 1000) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static boolean checkLongitudeLatitude(String longitude, String latitude) {
//        String latPattern = "^[-+]?([0-8]\\d{1}([.]\\d{1,8})?|90([.]0{1,8})?)$";
//        String logPattern = "^[-+]?((1[0-7]\\d{1}([.]\\d{1,8})?)|(180([.]0{1,8})?))$";
//        return longitude.matches(logPattern) == true ? latitude.matches(latPattern) : false;
        if (!TextUtils.isEmpty(longitude) && !TextUtils.isEmpty(latitude)) {
            double lng = Double.parseDouble(longitude);
            double lat = Double.parseDouble(latitude);
            if (lng <= 180 && lng >= -180 && lat <= 180 && lat >= -180) {
                return true;
            }
        }
        return false;
    }

    /**
     * dp转px
     *
     * @param dp
     * @return
     */
    public static int dp2px(int dp) {
        float density = BaseApp.getInstance().getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5);
    }

    /**
     * px转换dip
     */
    public static int px2dp(int px) {
        final float scale = BaseApp.getInstance().getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * px转换sp
     */
    public static int px2sp(int pxValue) {
        final float fontScale = BaseApp.getInstance().getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * sp转换px
     */
    public static int sp2px(int spValue) {
        final float fontScale = BaseApp.getInstance().getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    public static String formatRMBPrice(double dPrice) {
        DecimalFormat decimalFormat = null;
        String sPrice = "";
        try {
            if (dPrice <= 0) {
                return "￥00.00";
            } else if (dPrice > 0 && dPrice < 1) {
                return "￥" + dPrice;
            } else {
                decimalFormat = new DecimalFormat("￥###,###.00");
                sPrice = decimalFormat.format(dPrice);
            }

        } catch (NumberFormatException e) {
//            e.printStackTrace();
        }
        return sPrice;
    }

    public static String formatPrice(double dPrice) {

        String str = "";
        try {
            DecimalFormat decimalFormat;
            if (dPrice <= 0) {
                return "00.00";
            } else if (dPrice > 0 && dPrice < 1) {
                return dPrice + "";
            } else {
                decimalFormat = new DecimalFormat("###,###.00");
                str = decimalFormat.format(dPrice);
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return str;
    }

    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    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;
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVersionName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    public static String transformNumBaiFenBi(double num) {
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);
        return nf.format(num);
    }

    public static String percentagePrint(double num1, double num2) {
        if (Double.compare(num2, 0) == 0) throw new RuntimeException("输入有误");
        double ratio = num1 / num2;
        NumberFormat format = NumberFormat.getPercentInstance();
        format.setMaximumFractionDigits(2);//设置保留几位小数
//        System.out.println("百分比为：" + format.format(ratio));
        return format.format(ratio);
    }

    public interface CallBack {
        void onError(String msg);

        void onSuccess(String paht);


    }

    /*** 验证电话号码
     * @return 如果是符合格式的字符串, 返回 <b>true </b>,否则为 <b>false </b>
     */
    //座机
    public static boolean ISTel(String str) {
        String regex = "^(0\\d{2,3}-){0,1}\\d{7,8}$";//座机
        return matches(regex, str);
    }

    //手机号
    public static boolean ISPhone(String str) {
        String mobile = "^1(3|4|5|6|7|8|9)\\d{9}$";//电话号
        return matches(mobile, str);
    }

    public static boolean IsTelephone(String str) {
        String regex = "^(0\\d{2,3}-){0,1}\\d{7,8}$";//座机
        String mobile = "^1(3|4|5|6|7|8|9)\\d{9}$";//电话号
        if (str.charAt(0) == '0') {
            return matches(regex, str);
        } else {
            return matches(mobile, str);
        }

    }

    public static boolean isMobilePhone(String str) {
//        String regex = "^(0\\d{2,3}-){0,1}\\d{7,8}$";//座机
        String mobile = "^1(3|4|5|6|7|8|9)\\d{9}$";//电话号
//        if (str.charAt(0) == '0') {
//            return matches(regex, str);
//        } else {
        return matches(mobile, str);
//        }

    }


}
