package com.zkjc.common.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.usb.UsbManager;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.zkjc.common.R;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by cuiMarker on 2017/3/13.
 */

public class Utils {

    private static Utils instances;

    private Toast toast = null;

    private AlertDialog dialog = null;

    private TextView msg;

    public static Utils getInstances() {
        if (instances == null) {
            synchronized (Utils.class) {
                if (instances == null) {
                    instances = new Utils();
                }
            }
        }
        return instances;
    }

    @Deprecated
    public void showToast(Context context, String content) {
        showToast(context, content, Toast.LENGTH_SHORT);
    }

    @Deprecated
    public void showToast(Context context, String content, int duration) {
//        ToastUtils.show(content);
//        if(true) return;
        if (context instanceof Activity) {
            if (context == null || ((Activity) context).isFinishing()) {
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if (((Activity) context).isDestroyed()) {
                    return;
                }
            }
        }
        if (toast == null) {
            toast = Toast.makeText(context, content, duration);
        } else {
            toast.setText(content);
        }
        if (isOnMainThread()) {
            toast.show();
        } else {
            ((Activity) context).runOnUiThread(() -> toast.show());
        }
    }

    @Deprecated
    public void showToast(Activity context, String content) {
        showToast(context, content, Toast.LENGTH_SHORT);
    }

    public boolean isDate2Bigger(String str1, String str2) {
        boolean isBigger = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt1 = null;
        Date dt2 = null;
        try {
            dt1 = sdf.parse(str1);
            dt2 = sdf.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dt1.getTime() > dt2.getTime()) {
            isBigger = false;
        } else if (dt1.getTime() <= dt2.getTime()) {
            isBigger = true;
        }
        return isBigger;
    }
//    public void showToast(final Activity activity, final String message, final int duration) {
//        if (isOnMainThread()) {
//            Toast.makeText(activity, message, duration).show();
//        } else {
//            activity.runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    Toast.makeText(activity, message, duration).show();
//                }
//            });
//        }
//    }

    @Deprecated
    public void showToast(Context context, Handler handler, String content) {
        showToast(context, handler, content, Toast.LENGTH_SHORT);
    }

    @Deprecated
    public void showToast(final Context context, final Handler handler, final String message, final int duration) {
//        ToastUtils.show(message);
//        if(true) return;

        if (isOnMainThread()) {
            Toast.makeText(context, message, duration).show();
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, message, duration).show();
                }
            });
        }
    }

    public AlertDialog showDialog(Context context, String text) {
        if (dialog == null) {
            dialog = new AlertDialog.Builder(context,
                    R.style.MyDialogStyle).create();
            //对话框的类型设置为系统对话框
            dialog.getWindow().getAttributes().type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            dialog.setCanceledOnTouchOutside(false);//触摸外边时不取消对话框

        }

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
            }
        });//设置对话框取消监听
        dialog.show();//显示后才能添加内容
        dialog.getWindow().setContentView(R.layout.dialog_layout);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        msg = dialog.findViewById(R.id.id_tv_loadingmsg);
        msg.setText(text);

        if (!dialog.isShowing()) {//非显示中
            dialog.show();
        }

        return dialog;
    }


    public boolean isTime2Bigger(String str1, String str2, boolean containHour) {
        boolean isBigger = false;
        SimpleDateFormat sdf = null;
        if (containHour) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        } else {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        }
        Date dt1 = null;
        Date dt2 = null;
        try {
            dt1 = sdf.parse(str1);
            dt2 = sdf.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dt1.getTime() > dt2.getTime()) {
            isBigger = false;
        } else if (dt1.getTime() <= dt2.getTime()) {
            isBigger = true;
        }
        return isBigger;
    }

    public interface OnDialogListener {
        void complete();
    }

    private OnDialogListener dialogListener;

    public void setDialogListener(OnDialogListener dialogListener) {
        this.dialogListener = dialogListener;
    }

    public AlertDialog showDialog(Activity context, String text) {

        return showDialog(context, text, null);
    }

    public void showDialog(View view, Activity context, String text) {
        if (dialog == null || !context.equals(dialog.getOwnerActivity())) {
            dialog = new AlertDialog.Builder(context, R.style.MyDialogStyle).create();
            dialog.setCanceledOnTouchOutside(false);//触摸外边时不取消对话框
            dialog.setOwnerActivity(context);
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                }
            });//设置对话框取消监听
            dialog.show();//显示后才能添加内容
            dialog.getWindow().setContentView(R.layout.dialog_layout);
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            TextView msg = (TextView) dialog.findViewById(R.id.id_tv_loadingmsg);
            msg.setText(text);
        }

//        if(!dialog.isShowing() && !context.isFinishing()){//非显示中
//            dialog.show();
//        }

        if (dialog != null && !dialog.isShowing()) {
            Activity activity = dialog.getOwnerActivity();
            if (activity != null && !activity.isFinishing()) {
                if (null == view) {
                    dialog.show();
                } else {
                    view.post(new Runnable() {
                        @Override
                        public void run() {
                            dialog.show();
                        }
                    });
                }

            }
        }


    }

    public AlertDialog showDialog(Activity context, String text, OnDialogListener dialogListener) {
        if (dialog == null || !context.equals(dialog.getOwnerActivity())) {
            dialog = new AlertDialog.Builder(context, R.style.MyDialogStyle).create();
            dialog.setCanceledOnTouchOutside(false);//触摸外边时不取消对话框
            dialog.setOwnerActivity(context);
            dialog.setCancelable(true);
//            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
//                @Override
//                public void onCancel(DialogInterface dialogInterface) { }
//            });//设置对话框取消监听
            dialog.show();//显示后才能添加内容
            dialog.getWindow().setContentView(R.layout.dialog_layout);
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            msg = dialog.findViewById(R.id.id_tv_loadingmsg);
        }
        msg.setText(text);
        if (context != null)
            dialog.show();

        if (null != dialogListener)
            dialogListener.complete();

//        if ( dialog != null && !dialog.isShowing()) {
//            Activity activity = dialog.getOwnerActivity();
//            if ( activity != null && !activity.isFinishing() ) {
//                dialog.show();
//            }
//        }
        return dialog;
    }

    public void dismissDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    /**
     * 判断是否在当前主线程
     *
     * @return
     */
    public static boolean isOnMainThread() {
        return Thread.currentThread() == Looper.getMainLooper().getThread();
    }

    /**
     * 获取IMEI
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }

    public static byte[] str2Bcd(String asc) {
        int len = asc.length();
        int mod = len % 2;
        if (mod != 0) {
            asc = "0" + asc;
            len = asc.length();
        }
        byte abt[] = new byte[len];
        if (len >= 2) {
            len = len / 2;
        }
        byte bbt[] = new byte[len];
        abt = asc.getBytes();
        int j, k;
        for (int p = 0; p < asc.length() / 2; p++) {
            if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
                j = abt[2 * p] - '0';
            } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
                j = abt[2 * p] - 'a' + 0x0a;
            } else {
                j = abt[2 * p] - 'A' + 0x0a;
            }
            if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
                k = abt[2 * p + 1] - '0';
            } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
                k = abt[2 * p + 1] - 'a' + 0x0a;
            } else {
                k = abt[2 * p + 1] - 'A' + 0x0a;
            }
            int a = (j << 4) + k;
            byte b = (byte) a;
            bbt[p] = b;
            System.out.format("%02X\n", bbt[p]);
        }
        return bbt;
    }


    private static MediaRecorder mMediaRecorder;
    private static String soundName;

    public static String stopRecordSound(Context context) {
        mMediaRecorder.stop();
        return Utils.getStorageDirectory(context) + "/JingWuTong/" + soundName + ".amr";
    }

    /**
     * 开始录音
     */
    public static void startRecordSound(Context context) {
        //录制
        mMediaRecorder = new MediaRecorder();
        //设置录制声音来源
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//来自麦克风
        //设置录音格式
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);//默认格式
        //设置编码格式
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);//默认格式
        //设置保存文件的位置       路径/sdcard/a1.amr
        //Environment.getExternalStorageDirectory()==路径/sdcard
        soundName = System.currentTimeMillis() + "";

        File folderFile = new File(getStorageDirectory(context) + "/JingWuTong");
        if (!folderFile.exists()) {
            folderFile.mkdir();//比如：a://xxx/yyy只有xxx存在才能生成yyy。mkdirs()生成全部生成
        }

        File mSoundFile = new File(Utils.getStorageDirectory(context) + "/JingWuTong/" + soundName + ".amr");//获取外存目录
        //设定录制音频文件的保存位置
        mMediaRecorder.setOutputFile(mSoundFile.getAbsolutePath());//路径/sdcard/soundName.amr
        //
        try {
            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得根目录
     *
     * @param context:上下文
     * @return String
     * @throws null
     */
    public static String getStorageDirectory(Context context) {
        //判断是否有SDCard
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ?
                Environment.getExternalStorageDirectory().getPath() :
                context.getCacheDir().getPath();
    }

    /**
     * 判断文件是否存在
     */
    public static boolean isFileExists(String filePath) {
        try {
            File f = new File(filePath);
            if (!f.exists()) {
                f.mkdirs();
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 录音转化成Base64字符串
     */
    public static String voicetoString(String path) {
        String string = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileInputStream fis = new FileInputStream(new File(path));
            byte[] buf = new byte[1024];
            int n;
            while (-1 != (n = fis.read(buf))) {
                baos.write(buf, 0, n);
            }
            byte[] bytes = baos.toByteArray();
            string = Base64.encodeToString(bytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return string;
    }

    /**
     * 将base64转化成语音并存储到本地，返回  文件名：时长
     */
    public static String strToVoicePath(String voiceStr, Context context) {
        byte[] bytes;
        String path = "";
        try {
            bytes = Base64.decode(voiceStr, Base64.DEFAULT);
            File folderFile = new File(Utils.getStorageDirectory(context) + "/JingWuTong");
            if (!folderFile.exists()) {
                folderFile.mkdir();//比如：a://xxx/yyy只有xxx存在才能生成yyy。mkdirs()生成全部生成
            }
            path = Utils.getStorageDirectory(context) + "/JingWuTong/" + System.currentTimeMillis() + ".amr";
            FileOutputStream fos = new FileOutputStream(
                    new File(path));
            fos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    public static void gpio_control(int gpio, int mode) {
        try {
            String file_name = new String("/sys/class/gpio/gpio" + gpio + "/value");
            File file = new File(file_name);
            if (file.exists() == false) {
                file_name = new String("/sys/class/gpiocontrol/gpiocontrol/gpiocontrol" + gpio);
                file = new File(file_name);
            }

            FileWriter localFileWriter = new FileWriter(file);
            if (mode == 1)
                localFileWriter.write("1");
            else if (mode == 0)
                localFileWriter.write("0");
            localFileWriter.close();
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        }
    }

    public static boolean gpio_read(int paramInt) {
        try {
            File localFile = new File(new String("/sys/class/gpio/gpio" + paramInt + "/value"));
            if (!localFile.exists())
                localFile = new File(new String("/sys/class/gpiocontrol/gpiocontrol/gpiocontrol" + paramInt));
            FileReader localFileReader = new FileReader(localFile);
            char[] arrayOfChar = new char[1];
            localFileReader.read(arrayOfChar);
            localFileReader.close();
            int i = arrayOfChar[0];
            return i == 49;
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        }
        return false;
    }

    public static boolean isCarNO(String carNumber) {
                 /*
         车牌号格式：汉字 + A-Z + 5位A-Z或0-9
        （只包括了普通车牌号，教练车和部分部队车等车牌号不包括在内）
         */
        String carnumRegex = "[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}";
        if (TextUtils.isEmpty(carNumber)) return false;
        else return carNumber.matches(carnumRegex);
    }

    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }


    //人身损害
    public int whcdIds[] = {-1, 0, 1, 2, 3, 4, 9};
    public String whcdNames[] = {"请选择", "严重暴力", "特大", "重大", "一般", "轻微", "其它"};

    //案发原因
    public int zayyIds[] = {
            -1,
            206,
            207,
            208,
            209,
            210,
            211,
            212,
            213,
            214,
            215,
            216,
            217,
            218,
            219,
            220,
            221,
            222,
            223,
            224,
            225,
            226,
            227,
            228,
            229,
            230,
            231,
            232,
            233,
            234,
            235,
            236,
            237,
            238,
            239,
            240,
            241,
            242,
            243,
            244,
            245,
            246,
            247,
            248,
            249,
            250,
            251,
            252,
            253,
            254,
            255,
            256,
            257,
            258,
            259,
            260,
            261,
            262,
            263,
            264,
            265,
            266,
            267,
            268,
            269,
            270,
            271,
            272,
            273};
    public String zayyNames[] = {
            "请选择",
            "动机",
            "报复",
            "图财",
            "淫欲",
            "嫉妒",
            "厌世",
            "义愤",
            "虚荣",
            "义气",
            "好奇",
            "模仿",
            "逞强",
            "称霸",
            "激情",
            "反社会",
            "灭口",
            "畏罪潜逃",
            "政治投机",
            "猜疑",
            "嫌弃",
            "变态心理",
            "性变态",
            "泄私愤",
            "敌视社会",
            "对现实政策不满",
            "对领导人不满",
            "寻求刺激",
            "恶作剧",
            "其他",
            "因素",
            "心战宣传",
            "精神病",
            "罪迹败露",
            "隐私败露",
            "奸情败露",
            "婚恋纠纷",
            "家庭纠纷",
            "邻里纠纷",
            "经济纠纷",
            "土地纠纷",
            "水利纠纷",
            "资源纠纷",
            "劳资纠纷",
            "琐事口角",
            "名誉受损",
            "对职级奖惩不满",
            "对工作调整不满",
            "受人唆使",
            "受人雇佣",
            "淫物刺激",
            "酗酒",
            "吸毒",
            "过失",
            "赌博输款",
            "生意赔本",
            "欠款负债",
            "生活困难",
            "追求享乐",
            "灾害事故",
            "工资问题",
            "物价问题",
            "集资引发",
            "股票引发",
            "税收引发",
            "计生引发",
            "征地搬迁引发",
            "民族宗教引发",
            "其他"};

    /**
     * 验证no是否为正确的车牌号
     *
     * @param no
     * @return
     */
    public static boolean isPlateNo(String no) {
        if (no == null || no.equals("")) {
            return false;
        }
        String str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        String[] str1 = {"京", "津", "冀", "晋", "蒙", "辽", "吉", "黑", "沪", "苏",
                "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘", "粤", "桂", "琼", "渝",
                "川", "贵", "云", "藏", "陕", "甘", "青", "宁", "新", "农", "台", "中",
                "武", "WJ", "亥", "戌", "酉", "申", "未", "午", "巳", "辰", "卯", "寅",
                "丑", "子", "葵", "壬", "辛", "庚", "己", "戊", "丁", "丙", "乙", "甲",
                "河北", "山西", "北京", "北", "南", "兰", "沈", "济", "成", "广", "海", "空",
                "军", "京V", "使"};

        if (no.equals("新车")) {
            return true;
        }

        if (no.length() == 7) {
            int h = 0;
            for (int r = 0; r < no.length(); r++) {
                if (str.indexOf(no.charAt(r)) != -1) {
                    h++;
                }
            }
            if (h == 7) {
                return true;
            }
        }
        if (no.length() > 1) {

            String jq1 = no.substring(0, 1);
            String jq2 = no.substring(0, 2);

            for (int k = 0; k < str1.length; k++) {
                if (str1[k].equals(jq1)) {
                    if (no.length() <= 8) {
                        return true;
                    }
                }
                if (str1[k].equals(jq2)) {
                    if (no.length() <= 8) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    /**
     * 当前 时间戳
     *
     * @param time
     * @return
     */
    public String getDateTime(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE);
        sdf.applyPattern("yyyy_MM_dd_HH_mm_ss");// 文件名不能有:
        return sdf.format(time);
    }

    public boolean isUsbCamAttached(Context context) {

        // 检测是否 存在USB摄像头
        UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        if (null != manager.getDeviceList()) {
            HashMap<?, ?> deviceList = manager.getDeviceList();
            Iterator<?> it = deviceList.values().iterator();

            if (it.hasNext()) {
                return true;
            }
        }

        return false;
    }

    public String formatDuring(long s) {
        long days = s / (60 * 60 * 24);
        long hours = (s % (60 * 60 * 24)) / (60 * 60);
        long minutes = (s % (60 * 60)) / (60);
        long seconds = (s % (60));
        StringBuffer sb = new StringBuffer();
        if (days != 0) {
            sb.append(days + " d ");
        }
        if (hours != 0) {
            sb.append(hours + " h ");
        }
        if (minutes != 0) {
            sb.append(minutes + " m ");
        }
        sb.append(seconds + " s ");
        return sb.toString();
    }

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