package com.sd.cavphmi.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.*
import android.content.pm.PackageManager
import android.content.res.Resources
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.telephony.PhoneStateListener
import android.telephony.SignalStrength
import android.telephony.TelephonyCallback
import android.telephony.TelephonyManager
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.RequiresPermission
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import java.io.File


object SystemUtils {

    fun getScreenWidth(): Int {
        val dm = Resources.getSystem().displayMetrics
        return dm.widthPixels
    }

    fun getScreenHeight(): Int {
        val dm = Resources.getSystem().displayMetrics
        return dm.heightPixels
    }

    /**
     * 调用系统打电话
     *
     * @param phone
     */
    fun callSystemTell(context: Context, phone: String) {
        if (!phone.isNullOrEmpty()) {
            try {
//                var intent = Intent(Intent.ACTION_DIAL, phone.toUri())
                var intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phone"))
                context.startActivity(intent)
            } catch (e: ActivityNotFoundException) {

            }
        }
    }

    /**
     * 获取当前应用程序的版本号
     */
    fun getAppVersionCode(context: Context): Int {
        var version = 0
        try {
            version = context.packageManager.getPackageInfo(context.packageName, 0).versionCode
        } catch (e: PackageManager.NameNotFoundException) {
            throw RuntimeException(context.javaClass.simpleName + "the application not found")
        }
        return version
    }

    /**
     * 获取当前应用程序的版本号
     */
    fun getAppVersionName(context: Context): String {
        var version = "0"
        try {
            version =
                context.packageManager.getPackageInfo(context.packageName, 0).versionName.toString()
        } catch (e: PackageManager.NameNotFoundException) {
            throw RuntimeException("the application not found")
        }
        return version
    }


    /**
     * 关闭软键盘
     */
    fun closeKeyboard(view: View, context: Context) {
        val imm = ContextCompat.getSystemService(context, InputMethodManager::class.java)
        imm?.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    /**
     * 打卡软键盘
     */
    fun showKeyboard(view: View, context: Context) {
        view.isFocusable = true
        view.requestFocus()
        val imm = ContextCompat.getSystemService(context, InputMethodManager::class.java)
        imm?.showSoftInput(view, 0)
    }

    /**
     * 适配华为安全键盘
     */
    fun etHuaWeiKeybroad(et: EditText) {
        if (MobileUtils.isEMUI() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            with(et) {
                inputType =
                    android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_NORMAL
                transformationMethod =
                    android.text.method.PasswordTransformationMethod.getInstance()
            }
        }
    }


    fun setStatusBarColor(activity: Activity, colorId: Int) {
        val window = activity.window
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = ContextCompat.getColor(activity, colorId)
    }

    /**
     * 通过上下文找到activity
     */
    fun findActivity(context: Context): Activity? {
        if (context is Activity) {
            return context
        }
        return if (context is ContextWrapper) {
            val wrapper = context as ContextWrapper
            findActivity(wrapper.baseContext)
        } else {
            null
        }
    }


    @RequiresPermission("android.permission.READ_PRIVILEGED_PHONE_STATE")
    fun getPhoneIMEI(context: Context): String? {
        val tm = ContextCompat.getSystemService(context, TelephonyManager::class.java)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            return tm?.deviceId
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            return tm?.getImei(0)
        } else {
            return Settings.System.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
        }
    }

    /**
     * 复制文字到剪切板
     */
    fun copyTextClip(context: Context, text: String) {
        // 得到剪贴板管理器
        val cmb = ContextCompat.getSystemService(context, ClipboardManager::class.java)
        var clipData = ClipData.newPlainText("", text)
        cmb?.setPrimaryClip(clipData)
    }

    fun exitApp(context: Context) {
//        val activityManager =   getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val activityManager = ContextCompat.getSystemService(context, ActivityManager::class.java)
        val appTaskList = activityManager?.appTasks
        if (appTaskList != null) {
            for (appTask in appTaskList) {
                appTask.finishAndRemoveTask()
            }
        }
    }

    fun openThridUrl(url: String, context: Context) {
        var myurl = url
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            myurl = "http://$url"
        }
        try {
            val uri = Uri.parse(myurl)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            context.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
//            LogUtil.e("--------", "没找到Activity url=$url")
        }
    }

    //android获取一个用于打开HTML文件的intent
    fun openHtmlFileIntent(urlParam: String, context: Context) {
        val intent = Intent("android.intent.action.VIEW")
        intent.addCategory("android.intent.category.DEFAULT")
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//        val uri = Uri.fromFile(File(urlParam))

        var file = File(urlParam)
        var uri: Uri?
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            uri = FileProvider.getUriForFile(context, "com.zhaolaobao.fileProvider", file)
        } else {
            uri = Uri.fromFile(file)
        }

        var type = ""
        /* 取得扩展名 */
        var suffix = urlParam.substringAfterLast(".").toLowerCase()
        println("----url 后缀 = ${suffix}")
        when (suffix) {
            "pdf" -> type = "application/pdf"
            "ppt", "pptx" -> type = "application/vnd.ms-powerpoint"
//            "pptx" -> type =
//                "application/vnd.openxmlformats-officedocument.presentationml.presentation"
            "doc" -> type = "application/msword"
            "docx" -> type =
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document"

            "xls", "xlsx" -> type = "application/vnd.ms-excel"
            "txt" -> type = "text/plain"
            else -> type = "*/*"
        }
        intent.setDataAndType(uri, type)

        try {
            context.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            ToastHelper.showShort(context, "不支持打开")
        }
    }

    /**
     *跳转到应用外部打开
     */
    fun openFile(file: File, context: Context) {
        var intent = Intent(Intent.ACTION_VIEW)
        intent.addCategory("android.intent.category.DEFAULT")
        var uri: Uri?
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            uri = FileProvider.getUriForFile(context, "com.zhaolaobao.fileProvider", file)
        } else {
            uri = Uri.fromFile(file)
        }
        var type = ""
        /* 取得扩展名 */
        var end = file.name.substringAfterLast(".").toLowerCase()
        when (end) {
            "pdf" -> type = "application/pdf"
            "ppt" -> type = "application/vnd.ms-powerpoint"
            "pptx" -> type =
                "application/vnd.openxmlformats-officedocument.presentationml.presentation"

            "doc" -> type = "application/msword"
            "docx" -> type =
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document"

            "xls" -> type = "application/vnd.ms-excel"
            "xlsx" -> type = "application/vnd.ms-excel"
            "txt" -> type = "text/plain"
            else -> type = "*/*"
        }
        intent.setDataAndType(uri, type)
        try {
            context.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
//            context.toast("不支持打开")
        }
    }

    /**
     * 登录超时
     */
    fun timeOutLoginActivity(context: Context) {
        context.startActivity(Intent().apply {
//            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            action = "goLoginActivity"
            putExtra("is_login_timeout", true)
        })
    }

    /**
     * 账户禁用
     */
    fun accountDisLoginActivity(context: Context) {
        context.startActivity(Intent().apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            action = "goLoginActivity"
            putExtra("is_login_timeout", false)
        })
    }

    /**
     * 应用是否在电池白名单里
     */
    fun isIgnoringBatteryOptimizations(context: Context): Boolean {
        var isIgnoring = false
        val powerManager = ContextCompat.getSystemService(context, PowerManager::class.java)
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(context.packageName)
        }
        return isIgnoring
    }


    fun getMobileNetworkSignal(context: Context) :Int{
        var telephonyManager =
            context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        var signalStrength  = telephonyManager.signalStrength
        var list =signalStrength?.cellSignalStrengths
        return 1
    }


}