package com.mjsheng.myappstore.utils;

import android.annotation.SuppressLint;
import android.app.admin.DevicePolicyManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresPermission;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.base.MyApplication;
import com.mjsheng.myappstore.comm.CommonDatas;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static android.Manifest.permission.READ_PHONE_STATE;

public class Utils {


    public static final String PACKAGE = "appstore";
    public static final String DOWNLOAD_STARTALL_ACTION = PACKAGE + "_startall"; // 开始所有任务
    public static final String DOWNLOAD_DELETE_UPDATE_ACTION = PACKAGE + "_download_update_delete"; // 删除应用更新文件
    public static final String DOWNLOAD_DELETEALL_ACTION = PACKAGE + "_deleteall_alltask"; // 删除所有任务
    public static final String DOWNLOAD_ALLTASK_ACTION = PACKAGE + "_download_alltask"; // 获取所有任务
    public static final String DOWNLOAD_START_ACTION = PACKAGE + "_download_start"; // 下载标识
    public static final String DOWNLOAD_STOP_ACTION = PACKAGE + "_download_stop"; // 暂停标识
    public static final String DOWNLOAD_DELETE_PACKAGENAME_ACTION = PACKAGE + "_download_packagename_delete"; // 删除标识 根据包名
    public static final String DOWNLOAD_DELETE_URL_ACTION = PACKAGE + "_download_url_delete"; // 删除标识 根据下载地址
    public static final String DOWNLOAD_INITIALIZE_ACTION = PACKAGE + "_download_initialize"; // item初始化状态
    public static final String DOWNLOAD_PACKAGENAME_ACTION = PACKAGE + "_download_packagename"; // item初始化状态 包名
    public static final String DOWNLOAD_SERVICE_ACTION = PACKAGE + "_download_service";  // 下载状态回调服务

    public static final String DOWNLOAD_ALLSERVICE_ACTION = PACKAGE + "_download_allservice"; // 返回所有下载任务
    public static final String DOWNLOAD_NEWSERVICE_ACTION = PACKAGE + "_download_newservice"; // 一个新的下载任务

    // JPush   推送消息
    public static final String MESSAGE_RECEIVED_ACTION = "com.appstore.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title"; // 消息标题
    public static final String KEY_MESSAGE = "message"; // 消息内容
    public static final String KEY_EXTRAS = "extras"; // 消息内容类型
    public static final String KEY_TYPE = "type"; // 消息内容类型


    public static final String ACTION_PACKAGE_REPLACED = PACKAGE + "PACKAGE_REPLACED"; // 替换应用
    public static final String ACTION_PACKAGE_REMOVED = PACKAGE + "PACKAGE_REMOVED"; // 卸载应用
    public static final String ACTION_PACKAGE_ADDED = PACKAGE + "PACKAGE_ADDED"; // 安装应用

    public static int[] babyImage = {R.drawable.language, R.drawable.habit, R.drawable.knowledge, R.drawable.security, R.drawable.promotion};
    public static int[] childImage = {R.drawable.yuwen, R.drawable.shuxue, R.drawable.yingyu, R.drawable.qingshang, R.drawable.yishu, R.drawable.promotion};
    public static int[] youngImage = {R.drawable.yuwen, R.drawable.shuxue, R.drawable.yingyu, R.drawable.promotion};
    // 学习日志上传标识
    public static final String APP_LRARNLOG = "com.colorflykids.alarm";
    // 学习日志下载标识
    public static final String APP_DOWNLOADLEARNLOG = "com.colorflykids.downloadlearnlog";
    // 账号注销标识
    public static final String APP_USERLOGOUT = "com.colorflykids.userlogout";


    public static final String UPDATE_SYSTEMUI = "cn.colorflykids.UPDATE_SYSTEMUI";
    public static final int COUNT_ONE_PAGE = 8;
    public static final int COUNT_ONE_PAGE2 = 10;
    public static final String YOUNGSYSTEM_APP_TONGBU = "com.school.app.syn"; // 小学系统 同步教材app
    /**
     */
    public static final String number[] = {
            "1", "2", "3", "4", "5", "6", "7",
            "8", "9", "10", "0", "11"};
    public static final String STORE = "store";
    public static final String CATEGORY_THREE = "3";
    public static final String CATEGORY_SIX = "6";
    public static final String CATEGORY_UPSIX = "10";
    public static final String CLOSE_REST_WINDOW = "colse_rest_window";
    public static final String STOP_LOOPING_TIMER = "stop_looping_timer";
    public static final String START_LOOPING_TIMER = "start_looping_timer";
    public static String DOWNLOADAPP_CALLBACK = "com.colorflykids.downloadapp"; //  子界面下载回调 提示更新UI
    public static String MENU_YOUYOU = "youyou";
    public static String MENU_LANGUAGE = "语言启蒙";
    public static String MENU_HABIT = "行为习惯";
    public static String MENU_KNOWLEDGE = "生活认知";
    public static String MENU_SECURITY = "安全自理";
    public static String MENU_PROMOTION = "入园-综合提升";
    public static String MENU_LY = "优优乐园";
    public static String MENU_YW = "语文知识";
    public static String MENU_SX = "数理逻辑";
    public static String MENU_YY = "英语启蒙";
    public static String MENU_QS = "情商培养";
    public static String MENU_YS = "艺术提升";
    public static String MENU_ZH = "学前-综合提升";
    public static String MENU_TONGBUJIAOCAI = "同步教材";
    public static String MENU_YUWEN = "语文";
    public static String MENU_SHUXUE = "数学";
    public static String MENU_YINGYU = "英语";
    public static String MENU_ZONGHETISHEGN = "小学-综合提升";
    public static String[] babySystem = {MENU_LANGUAGE, MENU_HABIT, MENU_KNOWLEDGE, MENU_SECURITY, MENU_PROMOTION};
    public static String[] childSystem = {MENU_LY, MENU_YW, MENU_SX, MENU_YY, MENU_QS, MENU_YS, MENU_ZH};
    public static String[] youngSystem = {MENU_YUWEN, MENU_SHUXUE, MENU_YINGYU, MENU_ZONGHETISHEGN};


    public static String[] sonSystem = {MENU_HABIT, MENU_SECURITY, MENU_LANGUAGE, MENU_KNOWLEDGE, MENU_PROMOTION,
            MENU_LY, MENU_YW, MENU_SX, MENU_YY, MENU_QS, MENU_YS, MENU_ZH,
            MENU_TONGBUJIAOCAI, MENU_YUWEN, MENU_SHUXUE, MENU_YINGYU, MENU_YINGYU, MENU_ZONGHETISHEGN};
    public static String[][] tagList = {babySystem, childSystem, youngSystem};
    public static String subcategories[][] = {babySystem, childSystem, youngSystem};
    public static String system[] = {"入园系统", "学前系统", "小学系统"};
    public static String systemandno[] = {"入园系统", "学前系统", "小学系统", "未分配"};
    protected static Toast toast = null;
    private static String oldMsg;
    private static long oneTime = 0;
    private static long twoTime = 0;


    //   积分记录 达人标准次数记录



    // MD5 设备地址标识
    public static String getMAC(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // 如果当前设备系统大于等于6.0 使用下面的方法
            return getMac();
        } else {
            try {
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                // 获取MAC地址
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String mac = wifiInfo.getMacAddress();
                if (null == mac) {
                    // 未获取到
                    mac = "";
                }
                return mac;
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }
    }

    /**
     * 获取手机的MAC地址
     *
     * @return
     */
    public static String getMac() {
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();
                macSerial = getAndroid7MAC();
            }
        }
        return macSerial;
    }

    /**
     * 兼容7.0获取不到的问题
     *
     * @return
     */
    public static String getAndroid7MAC() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0"))
                    continue;
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
        }
        return "";
    }

    public static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }

    public static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }


    // MD5 设备地址标识
    public static String getMD5(Context context) {
        String WLANMAC = getMAC(context);
        // compute md5
        MessageDigest m = null;
        try {
            m = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (WLANMAC != null && !WLANMAC.equals("")) {
            m.update(WLANMAC.getBytes(), 0, WLANMAC.length());
        } else if (getSimSerialNumber(context) != null && !getSimSerialNumber(context).equals("")) {
            m.update(getSimSerialNumber(context).getBytes(), 0, getSimSerialNumber(context).length());
        } else {
            m.update(getPesudoUniqueID().getBytes(), 0, getPesudoUniqueID().length());
        }
        // get md5 bytes
        byte p_md5Data[] = m.digest();
        // create a hex string
        String m_szUniqueID = new String();
        for (int i = 0; i < p_md5Data.length; i++) {
            int b = (0xFF & p_md5Data[i]);
            // if it is a single digit, make sure it have 0 in front (proper padding)
            if (b <= 0xF)
                m_szUniqueID += "0";
            // add number to string
            m_szUniqueID += Integer.toHexString(b);
        }   // hex string to uppercase
        m_szUniqueID = m_szUniqueID.toUpperCase();
        return m_szUniqueID;
    }

    private static String getSimSerialNumber(Context context) {

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        @SuppressLint("MissingPermission") String simSerialNumber = tm.getSimSerialNumber();
        return simSerialNumber;
    }


    private static String getPesudoUniqueID() {
        String m_szDevIDShort = "35" + //we make this look like a valid IMEI
                Build.BOARD.length() % 10 +
                Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 +
                Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 +
                Build.HOST.length() % 10 +
                Build.ID.length() % 10 +
                Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 +
                Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 +
                Build.TYPE.length() % 10 +
                Build.USER.length() % 10;
        return m_szDevIDShort;
    }


    // 防止连续点击
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    //  5分钟 = 1 转换成时间
    public static String getRangeTime(int range) {
        StringBuffer sBuffer = new StringBuffer();
        String hour;
        String minute;
        if ((range / 12) >= 10) {
            hour = range / 12 + "";
        } else {
            hour = "0" + range / 12 + "";
        }
        if ((range % 12) > 0) {
            minute = ":" + range % 12 / 2 + "0";
        } else {
            minute = ":00";
        }
        sBuffer.append(hour.trim());
        sBuffer.append(minute.trim());
        return sBuffer.toString();
    }


    // 根据日期取得星期几
    public static String getWeek(Date date) {
        String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return weeks[week_index];
    }


    // 非空判断
    public static boolean isEmpty(String s) {
        if (null == s)
            return true;
        if (s.length() == 0)
            return true;
        if (s.trim().length() == 0)
            return true;
        return false;
    }

    // 手动隐藏键盘
    public static void CloseKeyBoard(Context context) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        System.out.println("isActive:" + imm.isActive());
        if (imm.isActive()) {
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    // 接受软键盘输入
    public static void hideKeyboard(Context context, View view) {
        if (context == null || view == null) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    // 卸载app
    public static void unInstallAPP(Context context, String packageName) {
        if (!TextUtils.isEmpty(packageName) && !AppsManagerUtils.isSystemApp(context, packageName)) {
            if (AppsManagerUtils.isSystemApp(context, packageName)) {
                Toast.makeText(MyApplication.getAppContext(), R.string.system_unistall_error, Toast.LENGTH_SHORT).show();
            } else {
                Uri packageURI = Uri.parse("package:" + packageName);
                Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
                context.startActivity(intent);
            }
        } else {
            Toast.makeText(MyApplication.getAppContext(), R.string.unistall_error, Toast.LENGTH_SHORT).show();
        }
    }

    // 打开app
    public static void startApp(Context context, String packageName,
                                String activityName) {

        if (TextUtils.isEmpty(packageName))
            return;

        try {
            Intent intent = null;
            if (TextUtils.isEmpty(activityName)) {
                intent = context.getPackageManager().getLaunchIntentForPackage(
                        packageName);
            } else {
                intent = new Intent();
                intent.setComponent(new ComponentName(packageName, activityName));
            }
            if (intent == null) {
                intent = getLaunchIntentForNoCategory(context, packageName);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Intent getLaunchIntentForNoCategory(Context context,
                                                      String packageName) {
        Intent intent = null;

        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageinfo = null;
        try {
            packageinfo = packageManager.getPackageInfo(packageName, 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return null;
        }
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.setPackage(packageinfo.packageName);
        List<ResolveInfo> resolveinfoList = packageManager
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            String className = resolveinfo.activityInfo.name;
            intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            ComponentName cn = new ComponentName(packageName, className);
            intent.setComponent(cn);
        }
        return intent;
    }

    // 设置系统亮度模式
    public static void systemBrightness(Context context) {
        try {
            SharedPreferences mPrefs = context.getSharedPreferences("colorflykids", 0);
            boolean initSetting = mPrefs.getBoolean("init_setting", true);
            if (initSetting) {
                mPrefs.edit().putBoolean("init_setting", false).commit();
            }
            Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
            mPrefs.edit().putBoolean("first_init", false).commit();

        } catch (Exception err) {
            err.printStackTrace();
        }
    }

    // 更新 版本比较
    public static boolean isUpdate(String oldVersion, String newVersion) {
        if (TextUtils.isEmpty(oldVersion) || TextUtils.isEmpty(newVersion) || oldVersion.equals(newVersion)) {
            return false;
        }
        String[] oldVersionSp = oldVersion.replaceAll("[^.\\d]", "").trim().split("\\.");
        String[] newVsersionSp = newVersion.replaceAll("[^.\\d]", "").trim().split("\\.");
        int index = 0;
        int minLen = Math.min(oldVersionSp.length, newVsersionSp.length);
        int diff = 0;
        while (index < minLen && (diff = Integer.parseInt(newVsersionSp[index]) - Integer.parseInt(oldVersionSp[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            for (int i = index; i < oldVersionSp.length; i++) {
                if (Integer.parseInt(oldVersionSp[i]) > 0) {
                    return false;
                }
            }
            for (int i = index; i < newVsersionSp.length; i++) {
                if (Integer.parseInt(newVsersionSp[i]) > 0) {
                    return true;
                }
            }
        } else {
            return diff > 0 ? true : false;
        }
        return false;
    }

    /***
     * 半角转换为全角
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    public static void showToast(Context context, String s) {
        if (toast == null) {
            toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
            toast.show();
            oneTime = System.currentTimeMillis();
        } else {
            twoTime = System.currentTimeMillis();
            if (s.equals(oldMsg)) {
                if (twoTime - oneTime > Toast.LENGTH_SHORT) {
                    toast.show();
                }
            } else {
                oldMsg = s;
                toast.setText(s);
                toast.show();
            }
        }
        oneTime = twoTime;
    }

    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 boolean isIntent(Context context) {

        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }
        // 检查网络连接，如果无网络可用，就不需要进行连网操作等
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();

        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }
        return true;
    }

    public static String getTime(int time) {
        int min = time / 60;
        int sec = time % 60;
        if (sec > 0) {
            return String.valueOf(min + 1);
        } else {
            return String.valueOf(min);
        }
    }

    public static String getTimeClick(int time) {
        StringBuffer timeClick = new StringBuffer();
        int min = time / 60;
        int sec = time % 60;
        timeClick.append(min >= 10 ? (int) Math.ceil(min / 10) : 0)
                .append(min % 10)
                .append(":")
                .append(sec >= 10 ? (int) Math.ceil(sec / 10) : 0)
                .append(sec % 10);
        return timeClick.toString();
    }


    public static String getVersionName(Context context) {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            String version = packInfo.versionName.replaceAll("[a-zA-Z]", "").trim();
            ;
            return version;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public static float dp2px(Resources resources, float dp) {
        final float scale = resources.getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }

    public static float sp2px(Resources resources, float sp) {
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    public static String getTime() {
        long time = System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = new Date(time);
        String t1 = format.format(d1);
        return t1;
    }


    private static void getAdmin(Context context, ComponentName componentName) {
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "宏云萌书院OS");
        context.startActivity(intent);
    }

    /**
     * 获取设备序列号
     *
     * @return
     */
    public static String getSerial() {
        return Build.SERIAL;
//        return "QNS3AI000111";
//        return "QNW8WJ900002";

    }

    public static final long A_GB = 1073741824;
    public static final long A_MB = 1048576;
    public static final int A_KB = 1024;

    public static String fmtSpace(long space) {
        if (space <= 0) {
            return "0";
        }
        double gbValue = (double) space / A_GB;
        if (gbValue >= 1) {
            return String.format("%.2fGB", gbValue);
        } else {
            double mbValue = (double) space / A_MB;
            //            Log.e("GB", "gbvalue=" + mbValue);
            if (mbValue >= 1) {
                return String.format("%.2fMB", mbValue);
            } else {
                final double kbValue = space / A_KB;
                return String.format("%.2fKB", kbValue);
            }
        }
    }


    public static String transferLongToDate(Long millSec){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date= new Date(millSec);

        return sdf.format(date);

    }
    //判断是否为系统应用
    public static boolean isSystemApp(Context context, String pkgName) {
        boolean isSystemApp = false;
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(pkgName, 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            Log.e("isSystemApp", e.getMessage(), e);

        }

        // 是系统中已安装的应用
        if (pi != null) {
            boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
            boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
            isSystemApp = isSysApp || isSysUpd;
        }
        return isSystemApp;
    }
}