package com.xhly.manageapp.ui

import BaseActivity
import android.app.ActivityManager
import android.app.usage.UsageEvents
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.provider.Settings
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import com.xhly.corelib.Const
import com.xhly.corelib.base.viewmodel.CommonBaseViewModel
import com.xhly.corelib.bean.AppInfo
import com.xhly.corelib.eventbus.UIEvent
import com.xhly.corelib.network.RetrofitService
import com.xhly.corelib.utils.AppUtils
import com.xhly.corelib.utils.LogShow
import com.xhly.manageapp.AppAdapter
import com.xhly.manageapp.R
import com.xhly.manageapp.broadcastreceiver.AppInstallReceiver
import com.xhly.manageapp.databinding.ActivityMainBinding
import com.xhly.manageapp.network.LogService
import com.xhly.manageapp.service.ManageAccessibilityService
import com.xhly.manageapp.service.websocket.AppSocketService
import com.xhly.manageapp.ui.login.activity.LoginActivity
import kotlinx.coroutines.launch
import java.util.Calendar


class MainActivity : BaseActivity<CommonBaseViewModel, ActivityMainBinding>() {
    lateinit var adapter: AppAdapter
    /*private var csdkManager = CSDKManager(this)*/
    private var mMyInstallReceiver: AppInstallReceiver? = null
    private var dataList: ArrayList<AppInfo> = arrayListOf()
    override fun getBinding() = ActivityMainBinding.inflate(layoutInflater)

    override fun initData() {
        var user = spUtils.get("user")
        if (user.isNullOrBlank()) {
            startIntentActivity(LoginActivity().javaClass)
        }
        val getAppList1 = AppUtils.GetAppList(this)
        dataList.addAll(getAppList1)
        adapter = AppAdapter(this, dataList)
        mBinding.rv.layoutManager = GridLayoutManager(this, 6, GridLayoutManager.VERTICAL, false)
        mBinding.rv.adapter = adapter
        // checkAccessibility(this)
        mBinding.btn.setOnClickListener {
            startIntentActivity(ManageActivity().javaClass)
        }
        mBinding.resetbtn.setOnClickListener {
            UIEvent("2005").post()
        }
        registerAppInstallReceiver()
        /*
         使用情况权限
         val permissionIntent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
          startActivity(permissionIntent)*/
        // csdkManagerUtils.csdkManager.enableAccessibility("com.xhly.manageapp","com.xhly.manageapp.service.TestService",true)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
    }
    override fun initView() {
        mBinding.loginoutIv.setOnClickListener {
            showEditDialog()
        }
        mBinding.stoptv.setOnClickListener {
            spUtils.setParam(Const.DISABLEAPP, false)
        }
        onBackPressedDispatcher.addCallback {
          lifecycleScope.launch {

          }
            //屏蔽返回
        }
    }


    override fun onResume() {
        super.onResume()
        AppSocketService.lastPkgName=""
        getAppInfo()
        useStrategy()
        if (!isServiceON(this,AppSocketService::class.java.name)){
            AppSocketService.openWebSocket(this)
        }
        /*      lifecycleScope.launch(Dispatchers.IO) {
                  delay(20000)
                  withContext(Dispatchers.Main) {
                      Toast("冻结应用")
                      *//*csdkManager.setPackageEnabled("com.android.calendar", true)*//*
                *//* ManageApplication.killApplicationProcess("com.android.calendar")*//*
            }
        }*/
    }

    private fun useStrategy() {
        //获得sputils中的数据设置状态,以及策略
        try {
            var param = spUtils.getParam(Const.DISABLEAPP, false)
            if (param as Boolean) {
                mBinding.stoptv.visibility = View.VISIBLE
            } else {
                mBinding.stoptv.visibility = View.GONE
            }
            changeWhiteList()
        } catch (e: Exception) {

        }
    }

    private fun changeWhiteList() {
/*        //获得当前白名单
        val packageWhiteList = csdkManager.installPackageWhiteList
        LogShow("当前白名单$packageWhiteList")
        //获得从网络获取的白名单
        val jsonArray = spUtils.getFromJson(Const.WHITELISTAPP, ArrayList<String>().javaClass)
        val removeList = arrayListOf<String>()
        //移除白名单外的应用，并设置新的白名单
        if (jsonArray != null) {
            val whiteList = jsonArray as ArrayList<String>
            packageWhiteList.forEach { pkg ->
                val filter = whiteList.filter { it == pkg }
                if (filter.isEmpty()) {
                    removeList.add(pkg)
                }
            }
            ManageApplication.addInstallPackageWhiteList(whiteList)
        }
        ManageApplication.removeInstallPackageWhiteList(removeList)*/
    }

    override fun onUiEvent(uiEvent: UIEvent) {
        super.onUiEvent(uiEvent)
        when (uiEvent.getEvent()) {
            "update" -> {
                dataList.clear()
                val getAppList1 = AppUtils.GetAppList(this)
                dataList.addAll(getAppList1)
                adapter.notifyDataSetChanged()
                dataList.forEach {
                    LogShow("app包名" + it.packageName)
                }
            }

            "策略更新" -> {

            }
        }
    }

    private fun getAppInfo() {
        //统计使用时长
        var instance = Calendar.getInstance()
        instance.set(Calendar.HOUR_OF_DAY, 0)
        instance.set(Calendar.MINUTE, 0)
        instance.set(Calendar.SECOND, 1)
        var timeInMillis = instance.timeInMillis
        val usageManager = getSystemService(USAGE_STATS_SERVICE) as UsageStatsManager
        if (usageManager != null) {
            val intervalType = UsageStatsManager.INTERVAL_DAILY
            val endTime = System.currentTimeMillis()
            val startTime = timeInMillis
            //queryUsageStats查询使用时长，时间范围设置后，返回的数据时间范围不一定和设置的时间范围一致。
            /*   val applicationList = usageManager.queryUsageStats(intervalType, startTime, endTime)
               for (usageStats in applicationList) {
                   dataList.filter { it.packageName.equals(usageStats.packageName) }.forEach {
                       LogShow("应用时长统计"+it.name+"使用时间"+millisecondsToHMS(usageStats.totalTimeInForeground))
                   }
                   if (usageStats.packageName.equals("com.xhly.manageapp")){
                       LogShow("应用时长统计XhlyManageApp"+"使用时间"+millisecondsToHMS(usageStats.totalTimeInForeground))
                   }
               }*/

            //queryEvents查询使用时长，时间范围设置后，返回的数据时间范围和设置的一致，但需要自己判断时长
            var queryEvents = usageManager.queryEvents(startTime, endTime)
            var event = UsageEvents.Event()

            var totalTime = 0L
            var totalStartTime = 0L
            while (queryEvents.hasNextEvent()) {
                queryEvents.getNextEvent(event)
                when (event.eventType) {
                    UsageEvents.Event.ACTIVITY_RESUMED -> {
                        var first =
                            dataList.firstOrNull { event.packageName.equals(it.packageName) }
                        first?.let {
                            it.startTime = event.timeStamp
                        }
                        if (event.packageName.equals("com.xhly.manageapp")) {
                            totalStartTime = event.timeStamp
                        }
                    }

                    UsageEvents.Event.ACTIVITY_PAUSED -> {
                        var first =
                            dataList.firstOrNull { event.packageName.equals(it.packageName) }
                        first?.let {
                            if (it.startTime == 0L) {
                                it.startTime = instance.timeInMillis
                            }
                            it.foregroundTime += (event.timeStamp - it.startTime)
                        }
                        if (event.packageName.equals("com.xhly.manageapp")) {
                            totalTime += (event.timeStamp - totalStartTime)
                        }
                    }
                }
            }

            dataList.filter { it.foregroundTime > 0L }.forEach {
                LogShow("events应用时长统计" + it.name + "使用时间" + millisecondsToHMS(it.foregroundTime))
            }
            if (totalTime > 0L) {
                LogShow("events应用时长统计com.xhly.manageapp使用时间" + millisecondsToHMS(totalTime))
            } else {
                LogShow("events应用时长统计com.xhly.manageapp使用时间无法获取")
            }
        }
    }

    fun checkAccessibility(context: Context): Boolean {
        // 判断辅助功能是否开启
        if (!isServiceON(this, ManageAccessibilityService::class.java.name)) {
            // 引导至辅助功能设置页面
            context.startActivity(
                Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            )
            Toast.makeText(context, "请先开启 \"Activity 栈\" 的辅助功能", Toast.LENGTH_LONG).show()
            return false
        }
        return true
    }

    fun millisecondsToHMS(milliseconds: Long): String {
        val seconds = milliseconds / 1000
        val hours = seconds / 3600
        val minutes = (seconds % 3600) / 60
        val remainingSeconds = seconds % 60

        return String.format("%02d:%02d:%02d", hours, minutes, remainingSeconds)
    }


    fun isServiceON(context: Context, className: String?): Boolean {
        val activityManager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val runningServices = activityManager.getRunningServices(100)
        if (runningServices.size < 0) {
            return false
        }
        for (i in runningServices.indices) {
            val service = runningServices[i].service
            if (service.className.contains(className!!)) {
                return true
            }
        }
        return false
    }


    private fun registerAppInstallReceiver() {
        val intentFilter = IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED)
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED)
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED)
        intentFilter.addDataScheme("package")
        mMyInstallReceiver = AppInstallReceiver()
        registerReceiver(mMyInstallReceiver, intentFilter);
    }


    private fun showEditDialog() {
        CustomDialog
            .build()
            .setCustomView(object : OnBindView<CustomDialog>(R.layout.layout_edit_dialog) {
                override fun onBind(dialog: CustomDialog, v: View) {
                    var titleTv = v.findViewById<TextView>(R.id.dialog_title_tv)
                    val enterTv = v.findViewById<TextView>(R.id.dialog_enter_tv)
                    val cancelTv = v.findViewById<TextView>(R.id.dialog_cancel_tv)
                    val editText = v.findViewById<EditText>(R.id.dialog_et)
                    editText.hint = getString(R.string.inputcode)
                    titleTv.text = getString(R.string.exit)
                    enterTv.setOnClickListener {
                        dialog.dismiss()
                        loginOut()
                    }
                    cancelTv.setOnClickListener {
                        dialog.dismiss()
                        showNoticeDialog()
                    }
                }
            }).setCancelable(false).setMaskColor(Color.parseColor("#66000000"))
            .setAlign(CustomDialog.ALIGN.CENTER).show()
    }

    private fun showNoticeDialog(){
        CustomDialog
            .build()
            .setCustomView(object : OnBindView<CustomDialog>(R.layout.layout_notice_dialog) {
                override fun onBind(dialog: CustomDialog, v: View) {
                    var closeBtn = v.findViewById<Button>(R.id.dialog_close_btn)
                    closeBtn.setOnClickListener {
                        dialog.dismiss()

                    }
                }
            }).setCancelable(false).setMaskColor(Color.parseColor("#66000000"))
            .setAlign(CustomDialog.ALIGN.CENTER).show()
    }

    private fun loginOut() {
        startIntentActivity(LoginActivity().javaClass)
        finish()
    }


    override fun onDestroy() {
        super.onDestroy()
        mMyInstallReceiver?.let {
            unregisterReceiver(it)
        }

    }
}