package com.ym.modulecommon.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.ym.modulecommon.AppliContext;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


/**
 * Created by gaoleichao on 2019/4/17
 */
public class Utils {
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public static int dip2px(float dipValue) {
        final float scale = AppliContext.get().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    public static int dip2px(int dipValue) {
        final float scale = AppliContext.get().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    public static int dip2px(Context context, int dipValue) {
        final float scale = AppliContext.get().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    public static int px2dip(float pxValue) {
        final float scale = AppliContext.get().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2sp(float pxValue) {
        final float fontScale = AppliContext.get().getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public static int sp2px(float spValue) {
        final float fontScale = AppliContext.get().getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static String getSystemProperty(String propName) {
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
        return line;
    }

    private static String oldMsg;
    protected static Toast toast = null;
    private static long oneTime = 0;
    private static long twoTime = 0;
    public static void destory(View view) {
        toDestory(view);
    }

    private static void toDestory(Object obj) {
        if (obj == null)
            return;
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            try {
                field.set(obj, null);
            } catch (Exception e) {
            }
        }
    }
    public static void onExit(Activity context) {
        context.finish();
        android.os.Process.killProcess(android.os.Process.myPid());
    }


    public static String obj2Str(Object obj) {
        if (obj == null) {
            return "";
        }
        return new Gson().toJson(obj);
    }

    public static Object str2Obj(String json, Class beanClass) {
        Gson gson = new Gson();
        Object res = gson.fromJson(json, beanClass);
        return res;
    }


    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * map拼接url
     *
     * @param url
     * @param params
     * @return
     */
    public static String getUrlWithQueryString(String url, Map<String, String> params) {
        if (params != null) {
            //			String paramString = params.getParamString();
            if (url != null)
                if (params.size() > 0) {

                    //迭代Map拼接请求参数
                    StringBuilder sb = new StringBuilder();
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        sb.append(entry.getKey()).append('=')
                                .append(entry.getValue()).append('&');
                    }
                    sb.deleteCharAt(sb.length() - 1);//删除最后一个"&"

                    if (!url.contains("?")) {
                        url += "?" + sb;
                    }

                }
        }
        return url;
    }

    // 判断是否缺少权限
    public static boolean needsPermission(String permission) {
        return ContextCompat.checkSelfPermission(AppliContext.get(), permission) != PackageManager.PERMISSION_GRANTED;
    }

    // 判断权限集合
    public static boolean needPermissions(String... permissions) {
        boolean isNeed;
        for (String permission : permissions) {
            isNeed = needsPermission(permission);
            if (isNeed) {
                return true;
            }
        }
        return false;
    }

    public static List<String> noPermissions(String... permissions) {
        List<String> list = new ArrayList<>();
        for (String permission : permissions) {
            if (needPermissions(permission)) {
                list.add(permission);
            }
        }
        return list;
    }


    public static AlertDialog.Builder createAlertDialog(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setIconAttribute(android.R.attr.alertDialogIcon);
        return builder;
    }

    public static String getNowDate() {
        Date date = new Date();//获取时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//转换格式
        return sdf.format(date);
    }


    /**
     * 判断当前是否是主进程
     *
     * @param context 上下文对象，用于获取包名
     * @return 如果取不到进程名或进程名与包名相同，则返回true
     */
    private static String sProcessName;
    private static boolean sIsMainProcess;

    public static boolean isMainProcess(Context context) {
        if (sProcessName == null) { // 如果上一次没获取到进程名，才重复获取
            // 获取当前进程名
            sProcessName = getProcessNameByAm(context);
            if (sProcessName == null) {
                sProcessName = getProcessNameFromFile(android.os.Process.myPid());
            }
            // 获取当前包名
            String packageName = context.getPackageName();
            sIsMainProcess = sProcessName == null || sProcessName.equals(packageName);
            LogUtils.d("Process", "主进程判断结果 = " + sIsMainProcess);
        }
        return sIsMainProcess;
    }

    /**
     * 通过ActivityManager获取当前进程名称
     *
     * @param context
     * @return 如果没获取到，则返回null
     */
    private static String getProcessNameByAm(Context context) {
        android.app.ActivityManager am = ((android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        List<android.app.ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        if (processInfos != null) {
            int myPid = android.os.Process.myPid();
            for (android.app.ActivityManager.RunningAppProcessInfo info : processInfos) {
                if (info.pid == myPid) {
                    LogUtils.d("Process", "通过AM获取到进程 " + myPid + " 为 " + info.processName);
                    return info.processName;
                }
            }
        }
        LogUtils.d("Process", "没有通过AM获取到进程名");
        return null;
    }

    /**
     * 从proc下的文件里面获取进程号对应的进程名<br/>
     * 参考自https://bugly.qq.com/docs/user-guide/instruction-manual-android/?v=20161219153020
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessNameFromFile(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
                LogUtils.d("Process", "通过File获取到进程 " + pid + " 为 " + processName);
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            LogUtils.d("Process", "判断进程失败", throwable);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
                LogUtils.d("Process", "判断进程关闭文件失败", exception);
            }
        }
        return null;
    }

    public static int getStatusBarHeight() {
        try {
            int result = 0;
            int resourceId = AppliContext.get().getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = AppliContext.get().getResources().getDimensionPixelSize(resourceId);
            }
            System.out.println("getStatusBarHeight:" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static float getStatusBarHeightFloat() {
        float result = 0;
        int resourceId = AppliContext.get().getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = AppliContext.get().getResources().getDimensionPixelOffset(resourceId);
        }
        return result;
    }

    public static <E> String list2String(List<E> list) {

        return new Gson().toJson(list);
    }

    public static <T> List<T> str2listObj(String json, Class clazz) {
        try {
            Type type = new ParameterizedTypeImpl(clazz);
            List<T> list = new Gson().fromJson(json, type);
            return list;
        } catch (Exception e) {
            return null;
        }
    }

    public static void play(int i) {

        AssetManager assetManager;
        MediaPlayer player = null;
        player = new MediaPlayer();
        assetManager = AppliContext.get().getResources().getAssets();
        try {
            AssetFileDescriptor fileDescriptor = assetManager.openFd("aigei_com.wav");
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getStartOffset());
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static class ParameterizedTypeImpl implements ParameterizedType {
        Class clazz;

        public ParameterizedTypeImpl(Class clz) {
            clazz = clz;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        @Override
        public Type getRawType() {
            return List.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }

    public static String getBase64(byte[] str) {
        String result = "";
        if (str != null) {
            try {
                result = new String(Base64.encode(str, Base64.NO_WRAP), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param bitmap
     * @param roundPx 一般设成14
     * @return
     * @Description: 获得圆角图片的方法
     * @author
     * @date 2014-4-2
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        if (bitmap == null) {
            return null;
        }
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final int color = 0xff424242;// 颜色值（0xff---alpha）
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            final RectF rectF = new RectF(rect);// Rect是使用int类型作为数值，RectF是使用float类型作为数值
            // --------抗锯齿-------//
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, null, rect, paint);
            return output;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    //判断app是否安装
    public static boolean isInstall(Intent intent) {
        return AppliContext.get().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
    }

    /**
     * 获取application中指定的meta-data 调用方法时key就是UMENG_CHANNEL
     *
     * @return 如果没有获取成功(没有对应值 ， 或者异常)，则返回值为空
     */
    public static String getChannel(Context ctx) {
        if (ctx == null || TextUtils.isEmpty("UMENG_CHANNEL")) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString("UMENG_CHANNEL");
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData;
    }

    /**
     * 清空剪贴板内容
     */
    public static void clearClipboard(Context context) {
        ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (manager != null) {
            try {
                manager.setPrimaryClip(manager.getPrimaryClip());
                manager.setText(null);
            } catch (Exception e) {

            }
        }
    }

    /**
     * 获取系统剪贴板内容
     */
    public static String getClipContent(Context context) {
        ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (manager != null) {
            if (manager.hasPrimaryClip() && manager.getPrimaryClip().getItemCount() > 0) {
                CharSequence addedText = manager.getPrimaryClip().getItemAt(0).getText();
                String addedTextString = String.valueOf(addedText);
                if (!TextUtils.isEmpty(addedTextString)) {
                    return addedTextString;
                }
            }
        }
        return "";
    }

    /**
     * 实现文本复制功能
     *
     * @param content 复制的文本
     */
    public static void copy(String content, Context context) {
        if (!TextUtils.isEmpty(content)) {
            // 得到剪贴板管理器
            ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(content.trim());
            // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
            ClipData clipData = ClipData.newPlainText(null, content);
            // 把数据集设置（复制）到剪贴板
            cmb.setPrimaryClip(clipData);
        }
    }

    public static void handleSSLHandshake() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }};

            SSLContext sc = SSLContext.getInstance("TLS");
            // trustAllCerts信任所有的证书
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception ignored) {
        }
    }

    public static boolean isYesterday(long time) {
        if (time == 0) {
            return true;
        }
        boolean isYesterday = false;
        Date date;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            date = sdf.parse(sdf.format(new Date()));
            if (time < date.getTime() && time > (date.getTime() - 24 * 60 * 60 * 1000)) {
                isYesterday = true;
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return isYesterday;
    }



    public static String replaceAll(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        return str.replaceAll("[^a-z^A-Z]", "");
    }

    private static String mActivityJumpTag;        //activity跳转tag
    private static long mClickTime;                //activity跳转时间

    /**
     * 检查是否重复，不需要则重写方法并返回true
     */
    public static boolean checkDoubleClick(Intent intent) {

        // 默认检查通过
        boolean result = true;
        // 标记对象
        String tag;
        if (intent.getComponent() != null) { // 显式跳转
            tag = intent.getComponent().getClassName();
        } else if (intent.getAction() != null) { // 隐式跳转
            tag = intent.getAction();
        } else {
            return true;
        }

        if (tag.equals(mActivityJumpTag) && mClickTime >= SystemClock.uptimeMillis() - 500) {
            // 检查不通过
            result = false;
        }

        // 记录启动标记和时间
        mActivityJumpTag = tag;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }

    public static void setTime(long time, TextView text) {
        if (text == null) {
            return;
        }
        long totalSeconds = time / 1000;
        long seconds = totalSeconds % 60;
        long minutes = totalSeconds / 60 % 60;
//        val hours = totalSeconds / 3600
        String minutesStr = minutes < 10 ? "0" + minutes : minutes + "";
        String secondsStr = seconds < 10 ? "0" + seconds : seconds + "";

        text.setText(minutesStr + ":" + secondsStr);
    }

    /**
     * 获取手机内部可用存储空间
     *
     * @param context
     * @return 以M, G为单位的容量
     */
    public static Long getAvailableInternalMemorySize(Context context) {
        File file = Environment.getDataDirectory();
        StatFs statFs = new StatFs(file.getPath());
        long availableBlocksLong = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            availableBlocksLong = statFs.getAvailableBlocksLong();
        }
        long blockSizeLong = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            blockSizeLong = statFs.getBlockSizeLong();
        }
        return (availableBlocksLong * blockSizeLong);
    }

    /**
     * byte(字节)根据长度转成kb(千字节)和mb(兆字节)
     *
     * @param bytes
     * @return
     */
    public static float bytes2Mb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        return returnValue;
    }

    /**
     * 生成一个startNum 到 endNum之间的随机数(不包含endNum的随机数)
     *
     * @param startNum
     * @param endNum
     * @return
     */
    public static int getNum(int startNum, int endNum) {
        if (endNum > startNum) {
            Random random = new Random();
            return random.nextInt(endNum - startNum) + startNum;
        }
        return 0;
    }

    /**
     * Get Mobile Type
     *
     * @return
     */
    public static String getMobileType() {
        return Build.MANUFACTURER;
    }

    /**
     * 通知权限申请
     *
     * @param context
     */
    public static void requestNotify(Context context) {
        /**
         * 跳到通知栏设置界面
         * @param context
         */
        Intent localIntent = new Intent();
        ///< 直接跳转到应用通知设置的代码
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            localIntent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            localIntent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
                Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            localIntent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            localIntent.putExtra("app_package", context.getPackageName());
            localIntent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            localIntent.addCategory(Intent.CATEGORY_DEFAULT);
            localIntent.setData(Uri.parse("package:" + context.getPackageName()));
        } else {
            ///< 4.4以下没有从app跳转到应用通知设置页面的Action，可考虑跳转到应用详情页面,
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            }
        }
        context.startActivity(localIntent);
    }

    public static void joinQQ(String qq) {
        String qqUrl = "mqqwpa://im/chat?chat_type=wpa&version=1&uin=" + qq;//uin是发送过去的qq号码
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(qqUrl));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        AppliContext.get().startActivity(intent);
    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime 设置的需要判断的时间  //格式如2012-09-08
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */

//  String pTime = "2012-03-12";
    public static String getWeek(String pTime) {
        String Week = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(format.parse(pTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            Week += "天";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 2) {
            Week += "一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 3) {
            Week += "二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 4) {
            Week += "三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 5) {
            Week += "四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 6) {
            Week += "五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 7) {
            Week += "六";
        }
        return Week;
    }

    public static boolean isNight() {
        long time = System.currentTimeMillis();

        Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(time);
        int mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
        if (mHour >= 18 || mHour <= 5) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 普通字符转换成16进制字符串
     *
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        byte[] bytes = str.getBytes();
        // 如果不是宽类型的可以用Integer
        BigInteger bigInteger = new BigInteger(1, bytes);
        return bigInteger.toString(16);
    }


    public static boolean isLogin() {
        String token = AdPreference.getToken();
        if (TextUtils.isEmpty(token)) {
            return false;
        }
        return true;
    }

    public static void drawableLeft(TextView textview, int rid) {

        Drawable drawableLeft = textview.getResources().getDrawable(rid);

        textview.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
                null, null, null);
    }

    public static void drawableRight(TextView textview, int rid) {

        Drawable drawableLeft = textview.getResources().getDrawable(rid);

        textview.setCompoundDrawablesWithIntrinsicBounds(null,
                null, drawableLeft, null);
    }

    /**
     * 手机号中间数字加密
     *
     * @param mobile
     * @return
     */
    public static String getStarMobile(String mobile) {

        if (!TextUtils.isEmpty(mobile)) {

            if (mobile.length() >= 11)

                return mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());

        } else {

            return "";

        }

        return mobile;

    }

    public static String SHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String formatDuring(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return days + "-" + hours + "-" + minutes + "-"
                + seconds + "";
    }

    public static String ts2Day(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);

        return days + "";
    }

    public static String ts2Hh(long mss) {
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);

        return hours + "";
    }

    public static String ts2Mm(long mss) {
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);

        return minutes + "";
    }

    public static String ts2Ss(long mss) {
        long seconds = (mss % (1000 * 60)) / 1000;

        return seconds + "";
    }



    public static void showToast(Context context, final String str) {
        MainLooper.Companion.get().post(new Runnable() {
            @Override
            public void run() {
                String msg = str;
                if (msg == null || TextUtils.isEmpty(msg))
                    return;

                if (msg.contains("failed to connect to") || msg.contains("502") || msg.contains("404") || msg.contains("failed to connect to"))
                    msg = "网络不给力，请重新尝试";

                if (toast == null) {
                    toast = Toast.makeText(AppliContext.get(), msg, Toast.LENGTH_SHORT);
                    toast.show();
                    oneTime = System.currentTimeMillis();
                } else {
                    twoTime = System.currentTimeMillis();
                    if (msg.equals(oldMsg)) {
                        if (twoTime - oneTime > Toast.LENGTH_SHORT) {
                            toast.show();
                        }
                    } else {
                        oldMsg = msg;
                        toast.setText(msg);
                        toast.show();
                    }
                }
                oneTime = twoTime;
            }
        });
    }

    /**
     * 获取随机数
     * @param len
     * @return
     */
    public static String getRandom(int len) {
        int digit = (int) Math.pow(10, len - 1);
        int rs = new Random().nextInt(digit * 10);
        if (rs < digit) {
            rs += digit;
        }
        return String.valueOf(rs);
    }

}
