package com.sjkj.base_lib.utils;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;

import androidx.appcompat.app.AlertDialog;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.sjkj.base_lib.R;
import com.sjkj.base_lib.app.AppManager;
import com.tencent.mmkv.MMKV;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

public class AppTools {
    public static final String TAG = "SJKJ";
    public static boolean LOCUS_OPEN = false;
    public static String LOCUS_SELECT_JIAOTONG = "";
    public static String LOCUS_SELECT_LINYE = "";
    public static String LOCUS_SELECT_SHUILI = "";
    public static String LOCUS_SELECT_HUANBAO = "";
    public static String LOCUS_SELECT_XIAOFANG = "";
    public static String LOCUS_SELECT_ZIYUAN = "";
    public static String LOCUS_SELECT_RECORD_JIAOTONG = "";
    public static String LOCUS_SELECT_RECORD_LINYE = "";
    public static String LOCUS_SELECT_RECORD_SHUILI = "";
    public static String LOCUS_SELECT_RECORD_HUANBAO = "";
    public static String LOCUS_SELECT_RECORD_XIAOFANG = "";
    public static String LOCUS_SELECT_RECORD_ZIYUAN = "";

//    public static Double LOCATION_SIPING_LAT = 43.166764;
//    public static Double LOCATION_SIPING_LNG = 124.350599;

    //    public static final double DEFAULT_LOCATION_LAT = 43.166764;
//    public static final double DEFAULT_LOCATION_LNG = 124.350599;
//    public static final int CODE_SUCCESS = 200;
//    public static final int ITEM_NUMBERS = 10;
//    /**
//     * 巡更条形码 请求值
//     */
//    public static final int SYSTEM_100 = 100;
//    public static final int SYSTEM_200 = 200;
//    public static final int SYSTEM_300 = 300;
//    private static Toast toast;
//    private static Handler mhandler = new Handler();
    private static MMKV mmkv = MMKV.defaultMMKV();
    //    public static String apkLocalPath = "";
//
    public static double userLat = 0.00;
    public static double userLog = 0.00;
    //    public static final String CAMERA_TEXT = "您的所有操作痕迹已被后台记录，请谨慎操作。部分摄像头处于敏感区域，已屏蔽操控权限，无法操控。";
    public static boolean isLeader = false;

//    public static void showToast(String info) {
//        if (!TextUtils.isEmpty(info) && info.contains("timeout")) {
//            info = "网络请求超时，请检查网络";
//        }
//        showToast(info, 3000);
//    }

//    public static void showToast(final String word, final long time) {
//        try {
//            AppManager.getAppManager().currentActivity().runOnUiThread(new Runnable() {
//                public void run() {
//                    final Toast toast = Toast.makeText(AppManager.getAppManager().currentActivity(), word, Toast.LENGTH_LONG);
//                    toast.show();
//                    Handler handler = new Handler();
//                    handler.postDelayed(new Runnable() {
//                        public void run() {
//                            toast.cancel();
//                        }
//                    }, time);
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    private static int cameraType = 0;
    private static String packageName = "";
    private static String packageNameProvider = "";
    public static final int CAMERA_TYPE_NONE = 0;
    /**
     * 四平/白山
     */
    public static final int CAMERA_TYPE_DH = 1;
    /**
     * 通榆
     */
    public static final int CAMERA_TYPE_HK = 2;
    public static final int CAMERA_TIME_INTERVAL = 0;


    public static void setCameraType(int cameraType) {
        AppTools.cameraType = cameraType;
    }

    public static void setPackageName(String packageName) {
        Log.e("AppTools.packageName",""+packageName);
        AppTools.packageName = packageName;
    }

    public static String getPackageNameProvider() {
        packageNameProvider = packageName + ".fileprovider";
        return packageNameProvider;
    }
    public static int getCameraType() {
        return AppTools.cameraType;
    }

    public static String getDeviceId(Context context) {
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        try {
            return toMD5(id);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return id;
        }
    }

    public static void initDefaultLatLng(double lat, double lng) {
        mmkv.encode("default_lat", lat);
        mmkv.encode("default_lng", lng);
    }

    public static double getDefaultLat() {
        return mmkv.decodeDouble("default_lat");
    }

    public static double getDefaultLng() {
        return mmkv.decodeDouble("default_lng");
    }

    private static String toMD5(String text) throws NoSuchAlgorithmException {
        //获取摘要器 MessageDigest
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        //通过摘要器对字符串的二进制字节数组进行hash计算
        byte[] digest = messageDigest.digest(text.getBytes());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digest.length; i++) {
            //循环每个字符 将计算结果转化为正整数;
            int digestInt = digest[i] & 0xff;
            //将10进制转化为较短的16进制
            String hexString = Integer.toHexString(digestInt);
            //转化结果如果是个位数会省略0,因此判断并补0
            if (hexString.length() < 2) {
                sb.append(0);
            }
            //将循环结果添加到缓冲区
            sb.append(hexString);
        }
        //返回整个结果
        return sb.toString();
    }

//    public static void showDialogLoginAuth() {
//        AlertDialog alertDialog = new AlertDialog.Builder(AppManager.getAppManager().currentActivity())
//                .setTitle("提示")
//                .setMessage("登录状态失效，或已在其他设备登录!")
//                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        AppTools.exitApp();
//                        dialogInterface.dismiss();
//                    }
//                })
////                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
////                    @Override
////                    public void onClick(DialogInterface dialogInterface, int i) {
////                     }
////                })
//                .setCancelable(false)
//                .create();
//
//        alertDialog.show();
//
//    }

//    public static void initLink(Activity activity) {
//        Uri uri = activity.getIntent().getData();
//        Log.e(TAG, "data = " + uri);
//        JMLinkAPI.getInstance().registerDefault(new MyRegisterCallback(activity));
//        if (uri != null) {
//            JMLinkAPI.getInstance().router(uri);
//        } else {
//            JMLinkAPI.getInstance().replay(new MyReplayCallback(activity));
//        }
//    }

//    static class MyRegisterCallback implements JMLinkCallback {
//        Context context;
//
//        MyRegisterCallback(Activity activity) {
//            context = activity.getApplicationContext();
//        }
//
//        @Override
//        public void execute(Map<String, String> map, Uri uri) {
//            Intent intent = new Intent();
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            try {
//                String scene = map.get("scene");
//                if (scene != null) {
//                    switch (scene) {
//                        case "1":
////                            intent.setClass(context, AKan.class);
////                            context.startActivity(intent);
//                            break;
//                        case "2":
////                            intent.setClass(context, Novel.class);
////                            context.startActivity(intent);
//                            break;
//                        case "3":
////                            intent.setClass(context, News.class);
////                            context.startActivity(intent);
//                            break;
//                        case "4":
////                            intent.setClass(context, Goods.class);
////                            context.startActivity(intent);
//                            break;
//                        case "5":
////                            intent.setClass(context, Spread.class);
////                            String uid = map.get("uid");
////                            intent.putExtra("uid", uid != null ? Long.valueOf(uid) : 0L);
////                            intent.putExtra("username", Uri.decode(Uri.decode(map.get("username"))));
////                            context.startActivity(intent);
//                            break;
//                        case "6":
////                            intent.setClass(context, Game.class);
////                            String roomId = map.get("room_id");
////                            intent.putExtra("room_id", roomId != null ? Long.valueOf(roomId) : 0L);
////                            intent.putExtra("username", Uri.decode(Uri.decode(map.get("username"))));
////                            context.startActivity(intent);
//                            break;
//                        case "7":
////                            intent.setClass(context, GroupShop.class);
////                            String groupId = map.get("group_id");
////                            intent.putExtra("group_id", groupId != null ? Long.valueOf(groupId) : 0L);
////                            intent.putExtra("username", Uri.decode(Uri.decode(map.get("username"))));
////                            context.startActivity(intent);
//                            break;
//                        default:
//                            break;
//                    }
//                }
//            } catch (Throwable t) {
//                t.printStackTrace();
//            }
//        }
//    }

//    static class MyReplayCallback implements ReplayCallback {
//        Context context;
//
//        MyReplayCallback(Activity activity) {
//            context = activity.getApplicationContext();
//            ;
//        }
//
//        @Override
//        public void onFailed() {
//            Log.d(TAG, "replay failed");
//        }
//
//        @Override
//        public void onSuccess() {
//            Log.d(TAG, "replay success");
//        }
//    }

//    public static void tokenBreak() {
//        try {
//            AppTools.setLogin(false);
//            AppTools.setToken("");
//            //停止、清除登录人推送信息
////            JPushInterface.stopPush(AppManager.getAppManager().currentActivity());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

//    public static void exitApp() {
//        try {
//            AppTools.menuList.clear();
//            AppTools.LOCUS_OPEN = false;
//            AppTools.setLogin(false);
//            AppTools.setToken("");
//            AppTools.setUserId("");
//            AppTools.setDeptId("");
//            AppTools.setDeptName("");
//            AppTools.setNickName("");
//            AppTools.setIsWangGe("");
//            //AppTools.setUserName("");
////            AppTools.setPassword("");
//            setAutoLogin(false);
//            //停止、清除登录人推送信息
//            pushStop();
//            //页面跳转登录页
//            Intent intent = new Intent(AppManager.getAppManager().currentActivity(), LoginActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            AppManager.getAppManager().currentActivity().startActivity(intent);
//            //关闭当前页面
//            AppManager.getAppManager().currentActivity().finish();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

//    public static String getRegistrationId() {
//        String registrationId = mmkv.decodeString("registrationId");
//        if (TextUtils.isEmpty(registrationId)) {
//            registrationId = JPushInterface.getRegistrationID(App.getInstance());
//            setRegistrationId(registrationId);
//        } else {
//            pushStop();
//        }
//        return registrationId;
//    }
//
//    public static void setRegistrationId(String registrationId) {
//        if (TextUtils.isEmpty(registrationId)) return;
//        mmkv.encode("registrationId", registrationId);
//        pushStop();
//    }

//    public static boolean isAutoLogin() {
//        return mmkv.decodeBool("isAutoLogin");
//    }
//
//    public static void setAutoLogin(boolean isFlag) {
//        mmkv.encode("isAutoLogin", isFlag);
//    }

//    public static void restartPushAndAlias() {
//        if (JPushInterface.isPushStopped(AppManager.getAppManager().currentActivity())) {
//            JPushInterface.resumePush(AppManager.getAppManager().currentActivity().getApplicationContext());
//        }
////        if (TextUtils.isEmpty(AppTools.getAliasName())){
////        JPushInterface.setAlias(AppManager.getAppManager().currentActivity().getApplicationContext(), 0, AppTools.getUserName());
////        }
//    }

    //
//    public static void pushRestart() {
//        if (JPushInterface.isPushStopped(App.getInstance())) {
//            JPushInterface.resumePush(App.getInstance());
//        }
//    }
//
//    public static void pushStop() {
//        if (!JPushInterface.isPushStopped(App.getInstance())) {
//            JPushInterface.stopPush(App.getInstance());
//        }
//    }
//
//    public static void pushInit() {
//        JPushInterface.setDebugMode(BuildConfig.DEBUG);
//        JPushInterface.init(App.getInstance());
//    }

//    public static void linkInit() {
//        JMLinkAPI.getInstance().setDebugMode(BuildConfig.DEBUG);
//        JMLinkAPI.getInstance().init(App.getInstance());
//    }

//    public static boolean pushIsStopped() {
//        return JPushInterface.isPushStopped(App.getInstance());
//    }

    public static final String ACCESS_TOKEN = "Authorization";

    public static void setLogin(boolean isLogin) {
        mmkv.encode("isLogin", isLogin);
    }

    public static boolean isLogin() {
        return mmkv.decodeBool("isLogin", false);
    }

    public static void setUserName(String username) {
        mmkv.encode("username", username);
    }

    public static String getUserName() {
        return mmkv.decodeString("username", "");
    }

    public static void setNickName(String username) {
        mmkv.encode("nickname", username);
    }

    public static String getNickName() {
        return mmkv.decodeString("nickname", "");
    }

    public static void setPassword(String password) {
        mmkv.encode("password", password);
    }

    public static String getPassword() {
        return mmkv.decodeString("password", "");
    }

    public static void setToken(String token) {
        mmkv.encode(ACCESS_TOKEN, "Bearer " + token);
    }

    public static String getToken() {
        return mmkv.decodeString(ACCESS_TOKEN, "");
    }


    public static void setIsWangGe(String isWangGe) {
        mmkv.encode("isWangGe", isWangGe);
    }

    public static String getIsWangGe() {
        return mmkv.decodeString("isWangGe", "");
    }

    public static void setDeptId(String deptId) {
        mmkv.encode("deptId", deptId);
    }

    public static String getDeptId() {
        return mmkv.decodeString("deptId", "");
    }

    public static void setDeptName(String deptName) {
        mmkv.encode("deptName", deptName);
    }


    public static String getDeptName() {
        return mmkv.decodeString("deptName", "");
    }


    public static void setUserId(String userId) {
        mmkv.encode("userId", userId);
    }

    public static String getUserId() {
        return mmkv.decodeString("userId", "");
    }

    public static void setCameraStreamType(int type) {
        mmkv.encode("cameraStreamType", type);
    }

    public static int getCameraStreamType() {
        return mmkv.decodeInt("cameraStreamType", 0);
    }


    public static void setBaseUrl(String baseUrl) {
        mmkv.encode("baseUrl", baseUrl);
    }

    public static String getBaseUrl() {
      // return mmkv.decodeString("baseUrl", "http://192.168.4.82:8080/api/");
        return mmkv.decodeString("baseUrl", "http://192.168.4.16:8080/api/");
    }

//    public static final String GATEWAY_URL = "sooka-mobile";
//    public static final String GATEWAY_URL_SYSTEM = "system";


//    public static void setAliasName(String alias) {
//        mmkv.encode("alias", alias);
//    }
//
//    public static String getAliasName() {
//        return mmkv.decodeString("alias", "");
//    }


//    public static void setRegistrationId(String registrationId) {
//        mmkv.encode("registrationId", registrationId);
//    }


//    /**
//     * 通知权限申请
//     *
//     * @param context
//     */
//    public static void requestNotify(Context context) {
//        /**
//         * 跳到通知栏设置界面
//         * @param context
//         */
//        Intent localIntent = new Intent();
//        ///< 直接跳转到应用通知设置的代码
//        if (android.os.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 (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
//                android.os.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 (android.os.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);
//    }


    private static AlertDialog alertDialog;

    public static void showLoading() {
        if (alertDialog == null) {
            alertDialog = new AlertDialog.Builder(AppManager.getAppManager().currentActivity()).create();
        } else {
            if (alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
        }
        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
        alertDialog.setCancelable(true);
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH || keyCode == KeyEvent.KEYCODE_BACK)
                    return true;
                return false;
            }
        });
        alertDialog.show();
        alertDialog.setContentView(R.layout.loading_alert);
        alertDialog.setCanceledOnTouchOutside(false);
    }

    public static void hideLoading() {
        if (null != alertDialog && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
    }


    public static void chooseImage() {
//        XXPermissions.with(AppManager.getAppManager().currentActivity())
//                .permission(Permission.READ_EXTERNAL_STORAGE)
//                .permission(Permission.WRITE_EXTERNAL_STORAGE)
////                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
//                .permission(Permission.CAMERA)
//                .request(new OnPermissionCallback() {
//                    @Override
//                    public void onGranted(List<String> permissions, boolean all) {
//                        if (all) {
                            Matisse.from(AppManager.getAppManager().currentActivity())
                                    .choose(MimeType.ofImage())//图片类型
                                    .countable(true)//true:选中后显示数字;false:选中后显示对号
                                    .maxSelectable(1)//可选的最大数
                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(false, AppTools.getPackageNameProvider()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .imageEngine(new GlideEngine())//图片加载引擎
                                    .forResult(100);
//                        } else {
//                            ToastUtils.show("获取部分权限成功，但部分权限未正常授予");
//                        }
//                    }
//
//                    @Override
//                    public void onDenied(List<String> permissions, boolean never) {
//                        if (never) {
//                            ToastUtils.show("被永久拒绝授权，请手动授予权限");
//                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
//                            XXPermissions.startPermissionActivity(AppManager.getAppManager().currentActivity(), permissions);
//                        } else {
//                            ToastUtils.show("获取权限失败");
//                        }
//                    }
//                });

    }

    public static List<Uri> chooseImageResult(Intent data) {
        List<Uri> result = Matisse.obtainResult(data);
        return result;
    }

//    /**
//     * 时间格式化工具
//     *
//     * @param pattern    格式
//     * @param timeMillis 毫秒
//     */
//    private static SimpleDateFormat sDateYMDFormat;
//
//    public static String dataFormat(String pattern, long timeMillis) {//这个传多了一个参数,pattern模型,就是自己规定格式
//        if (sDateYMDFormat == null) {
//            sDateYMDFormat = new SimpleDateFormat(pattern, Locale.getDefault());//跟上面差不多的
//        }
//        try {
//            return sDateYMDFormat.format(timeMillis);//跟上面差不多的
//        } catch (Exception e) {
//            return "2022-01-01";//跟上面差不多的
//        }
//    }

    public static void initLog() {
        Logger.addLogAdapter(new AndroidLogAdapter());
    }


//    public static void showLogE(String content) {
//        if (TextUtils.isEmpty(content)) {
//            Log.e(TAG, "value is null");
//            return;
//        }
//        Log.e(TAG, content);
//    }
//
//    public static void showLogD(String content) {
//        if (TextUtils.isEmpty(content)) {
//            Log.d(TAG, "value is null");
//            return;
//        }
//        Log.d(TAG, content);
//    }

    public static void restartApp() {
        Intent intent = AppManager.getAppManager().currentActivity().getBaseContext().getPackageManager().getLaunchIntentForPackage(AppManager.getAppManager().currentActivity().getBaseContext().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //与正常页面跳转一样可传递序列化数据, 在Launch页面内获得
        intent.putExtra("REBOOT", "reboot");
        AppManager.getAppManager().currentActivity().startActivity(intent);
    }

    public static int ceil(int totla) {
        double dou = (double) totla / Constants.ITEM_NUMBERS;
        return (int) Math.ceil(dou);
    }

    public static void setGhb(boolean isghb) {
        mmkv.encode("isGhb", isghb);
    }

    public static boolean isGhb() {
        return mmkv.decodeBool("isGhb", false);
    }
}
