package com.xhly.manageapp.ui.main.activity

import BaseActivity
import android.Manifest
import android.annotation.SuppressLint
import android.app.ActivityManager
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.recyclerview.widget.GridLayoutManager
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import com.tbruyelle.rxpermissions2.RxPermissions
import com.xhly.corelib.Const
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.CustomOSUtils
import com.xhly.corelib.utils.LogShow
import com.xhly.corelib.utils.PhoneInfoUtils
import com.xhly.manageapp.AppAdapter
import com.xhly.manageapp.ManageApplication
import com.xhly.manageapp.R
import com.xhly.manageapp.bean.EventLog
import com.xhly.manageapp.bean.log.LogdOperateBean
import com.xhly.manageapp.bean.strategy.StrategyBean
import com.xhly.manageapp.broadcastreceiver.AppInstallReceiver
import com.xhly.manageapp.broadcastreceiver.SDReceiver
import com.xhly.manageapp.databinding.ActivityMainBinding
import com.xhly.manageapp.network.log.LogService
import com.xhly.manageapp.service.ManageAccessibilityService
import com.xhly.manageapp.service.websocket.AppSocketService
import com.xhly.manageapp.ui.ManageActivity
import com.xhly.manageapp.ui.login.activity.LoginActivity
import com.xhly.manageapp.ui.main.viewmodel.MainViewModel
import com.xhly.manageapp.utils.StrategyUtils
import com.xhly.manageapp.workmanager.TimingWorker
import java.util.concurrent.TimeUnit


class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {
    lateinit var adapter: AppAdapter

    /*private var csdkManager = CSDKManager(this)*/
    private var mMyInstallReceiver: AppInstallReceiver? = null
    private var mySDReceiver: SDReceiver? = 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()
       // registerSDReceiver()
        /*
         使用情况权限
         val permissionIntent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
          startActivity(permissionIntent)*/
        // csdkManagerUtils.csdkManager.enableAccessibility("com.xhly.manageapp","com.xhly.manageapp.service.TestService",true)
        viewModel.getAppList()
        viewModel.listAppData.observe(this) {
            //获得应用集合，必装应用和推荐应用，再加上预装应用，其余应用需要静默卸载,必装应用需要进行静默下载和安装。
            var appList = AppUtils.GetAppList(this)

        }
        viewModel.strategyData.observe(this) {
            spUtils.saveJson(Const.STRATEGYBEANKEY, it)
            StrategyUtils.setStrategy(it)
        }
        startWorkManager()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
    }

    override fun initView() {
        mBinding.loginoutIv.setOnClickListener {
            showEditDialog()
        }
        mBinding.codeenterCv.setOnClickListener {
            //如果密码一致,则解锁
            spUtils.setParam(Const.DISABLEPAD, false)
            useStrategy()
            if (mBinding.mainLlayout.visibility == View.GONE) {
                Toast("当前不在可用时间。")
            }
        }
        onBackPressedDispatcher.addCallback {
            //屏蔽返回

        }
    }


    override fun onResume() {
        super.onResume()
        AppSocketService.lastPkgName = ""/*getAppInfo()*/
        viewModel.updateStrategy()
        useStrategy()
        try {
            var s =
                "厂商" + CustomOSUtils.getSystemBrand() + "，型号" + CustomOSUtils.getSystemDevice() + "，系统版本" + CustomOSUtils.getSystemDisplay()
        } catch (e: Exception) {
            LogShow("没有数据")
        }
        requestPermissionAndShotView()
    }

    private fun useStrategy() {
        //获得sputils中的数据设置状态,以及策略
        try {
            //如果存储的是锁定则锁定
            var block = false
            val strategyBean =
                spUtils.getFromJson(Const.STRATEGYBEANKEY, StrategyBean::class.java) as StrategyBean
            strategyBean?.let { bean ->
                //获得是否在使用时间范围
                block = StrategyUtils.getAppTimeStrategy(bean)
            }
            if (Const.isDebug) {
                //测试状态不锁定
                block = false
            }
            val param = spUtils.getParam(Const.DISABLEPAD, false) as Boolean
            if (param || block) {
                mBinding.mainLlayout.visibility = View.GONE
                mBinding.lockLlayout.visibility = View.VISIBLE
            } else {
                mBinding.mainLlayout.visibility = View.VISIBLE
                mBinding.lockLlayout.visibility = View.GONE
            }
            changeWhiteList()
        } catch (e: Exception) {
            val param = spUtils.getParam(Const.DISABLEPAD, false) as Boolean
            if (param) {
                mBinding.mainLlayout.visibility = View.GONE
                mBinding.lockLlayout.visibility = View.VISIBLE
            } else {
                mBinding.mainLlayout.visibility = View.VISIBLE
                mBinding.lockLlayout.visibility = View.GONE
            }
        }
    }

    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)
                }
            }

            Const.APPINSTALL -> {
                try {
                    dataList.clear()
                    val getAppList1 = AppUtils.GetAppList(this)
                    dataList.addAll(getAppList1)
                    adapter.notifyDataSetChanged()
                } catch (e: Exception) {

                }
            }
            Const.SDINSTALL -> {
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = "SD卡插入"
                data.doEvent = EventLog.SDEMOUNTEDVENT
               viewModel.eventLog(data)
            }
            Const.SDUNINSTALL->{
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = "SD卡拔出"
                data.doEvent = EventLog.SDEJECTEVENT
                viewModel.eventLog(data)
            }
            Const.SIMINSTALL->{
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = "SIM卡安装"
                data.doEvent = EventLog.SIMEVENT
                viewModel.eventLog(data)
            }
            Const.BLUETOOTHOPEN->{
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = "蓝牙打开"
                data.doEvent = EventLog.BLUETOOHEVENT
                viewModel.eventLog(data)
            }
            "策略更新" -> {

            }
        }
    }

    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 registerSDReceiver() {
        val intentFilter = IntentFilter();
        intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED)
        intentFilter.addAction(Intent.ACTION_MEDIA_EJECT)
        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED)
        intentFilter.addDataScheme("file")
        intentFilter.priority=1000
        mySDReceiver = SDReceiver()
        registerReceiver(mySDReceiver, 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)
        }
        mySDReceiver?.let {
            unregisterReceiver(it)
        }
        LogShow("MainActivity被销毁")
    }

    /**
     * 请求运行时权限
     */
    @SuppressLint("CheckResult")
    private fun requestPermissionAndShotView() {
        val phoneInfoUtils = PhoneInfoUtils(this)

        var iccid = ""
        val rxPermissions = RxPermissions(this)
        var request = rxPermissions.request(Manifest.permission.READ_PHONE_STATE)
        request.subscribe({ granted: Boolean ->
            if (granted) {
                iccid = phoneInfoUtils.iccid
                LogShow("手机信息" + iccid + "||" + iccid)
            }
        }, {
            LogShow("手机信息失败了" + it.message)
        })
    }


    private fun startWorkManager() {
        WorkManager.getInstance(this).cancelAllWork()
        // 周期性任务时间最少15分钟 所以除以实际周期的时间  看需要加入几个任务
        val taskList = arrayListOf(5, 10)
        for (taskNo in 1..10) {
            val request = PeriodicWorkRequest
                // 最少15分钟 PeriodicWorkRequest
                .Builder(TimingWorker::class.java, 15, TimeUnit.MINUTES)
                // WorkRequest 根据实际周期以及任务的编号 延迟初始化 0，5，10 分别周期行执行
                .setInitialDelay(taskNo.toLong(), TimeUnit.MINUTES).build()
            WorkManager.getInstance(this).enqueue(request)
        }
    }
}