package com.xhly.manageapp.utils

import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import androidx.work.WorkManager
import com.google.gson.reflect.TypeToken
import com.hjq.toast.Toaster
import com.xhly.corelib.Const
import com.xhly.corelib.bean.AppInfo
import com.xhly.corelib.utils.LogShow
import com.xhly.corelib.utils.ModelNameUtils
import com.xhly.corelib.utils.SharedPreferencesUtils
import com.xhly.corelib.utils.hourToCurrentDateLong
import com.xhly.manageapp.ManageApplication
import com.xhly.manageapp.bean.app.AppModel
import com.xhly.manageapp.bean.school.SchoolDeviceSetBean
import com.xhly.manageapp.bean.strategy.AppTimeManageBean
import com.xhly.manageapp.bean.strategy.StrategyBean
import com.xhly.manageapp.service.websocket.AppSocket
import java.util.Calendar
import kotlin.system.exitProcess

object StrategyUtils {
    public fun setStrategy(strategyBean: StrategyBean) {
        //是否启用白名单
        if (strategyBean.haswifi == 1) {
            ManageApplication.enableWifiWhiteList(true)
            strategyBean.padWifis?.let {
                val list = arrayListOf<String>()
                it.forEach { s ->
                    if (!s.isNullOrBlank()) {
                        list.add(s)
                    }
                }
                //先移除再添加
                val wifiWhiteList = ManageApplication.getWifiWhiteList()
                if (wifiWhiteList.isNotEmpty()){
                    ManageApplication.removeWifiWhiteList(wifiWhiteList)
                }
                ManageApplication.addWifiWhiteList(list)
            }
        } else {
            //不启用则清除所有wifi白名单
            val wifiWhiteList = ManageApplication.getWifiWhiteList()
            if (wifiWhiteList.isNotEmpty()){
                ManageApplication.removeWifiWhiteList(wifiWhiteList)
            }
            ManageApplication.enableWifiWhiteList(false)
        }
        //是否开启应用策略,不使用，通过app列表接口获取。
        /*      if (strategyBean.hasapp == 1) {
                  //TODO 应用策略可能需要应用下载安装以及卸载
                  //开启
                  strategyBean.padApps?.let { appArray ->
                      val list = arrayListOf<String>()
                      appArray.forEach {
                          list.add(it.appPackage)
                      }
                      ManageApplication.addInstallPackageWhiteList(list)
                  }
              } else {
                  //不开启应用策略
                  val installPackageWhiteList = ManageApplication.getInstallPackageWhiteList()
                  ManageApplication.removeInstallPackageWhiteList(installPackageWhiteList)
              }*/

        //是否开启时间策略，这个策略在生命周期中调用getPadTimeStrategy(strategyBean)


        //是否设备策略
        if (strategyBean.hasdevice == 1) {
            //开启
            deviceStrategy(strategyBean)
        } else {
            //不设置则默认全部打开
            deviceStrategy(strategyBean)
        }

        //违规处理,直接在事件触发时判断，不再这里处理
        /*if (strategyBean.hasviolate == 1) {

        }*/
    }

    private fun deviceStrategy(strategyBean: StrategyBean) {
        val padDevices = strategyBean.padDevices
        padDevices?.forEach {
            when (it.pdtype) {
                Const.DEVICETYPE1 -> {
                    ManageApplication.disableCamera(it.enabled != 1)
                }

                Const.DEVICETYPE2 -> {
                    ManageApplication.enableBluetooth(it.enabled == 1)
                }

                Const.DEVICETYPE3 -> {
                    ManageApplication.enableUsbDebugging(it.enabled == 1)
                }

                Const.DEVICETYPE4 -> {
                    //TODO 屏蔽对wifi的控制
                    //ManageApplication.enableWifi(it.enabled == 1)
                }

                Const.DEVICETYPE5 -> {
                    ManageApplication.setPackageEnabled(Const.ANDROIDPHONE,it.enabled==1)
                    ManageApplication.setPackageEnabled(Const.ANDROIDMMS,it.enabled==1)
                }

                Const.DEVICETYPE6 -> {
                    ManageApplication.enableData(it.enabled == 1)
                }

                Const.DEVICETYPE7 -> {
                    ManageApplication.enableLocation(it.enabled == 1)
                }

                Const.DEVICETYPE8 -> {
                    ManageApplication.disallowWifiAdvanceSettings(it.enabled != 1)
                }

                Const.DEVICETYPE9 -> {
                    ManageApplication.enableMassStorage(it.enabled == 1)
                }

                Const.DEVICETYPE10 -> {
                    ManageApplication.setCustomOTG(it.enabled == 1)
                }
            }
        }
    }

    /**
     * 时间策略处理，返回为真则锁定
     */
    public fun getPadTimeStrategy(strategyBean: StrategyBean): Boolean {
        //是否开启时间策略，返回为真则锁定
        var lockFlag = false
        val dayList = arrayListOf(2, 3, 4, 5, 6, 7, 1)
        val currentTimeMillis = System.currentTimeMillis()
        if (strategyBean.hastime == 1) {
            val calendar = Calendar.getInstance()
            //返回值 1 周日 2周一 3周二 4周三 5周四 6周五 7周六
            val dayWeek = calendar.get(Calendar.DAY_OF_WEEK)
            val padTimes = strategyBean.padTimes
            if (padTimes == null || padTimes.size == 0) {
                //开启策略，但不返回时间则表示锁定
                return true
            }
            padTimes?.forEach { padTimeManageBean ->
                val day = dayList[padTimeManageBean.week - 1]
                if (day == dayWeek) {
                    val starttime = padTimeManageBean.starttime
                    val stoptime = padTimeManageBean.stoptime
                    starttime?.let {
                        val start = starttime.hourToCurrentDateLong()
                        stoptime?.let {
                            val end = stoptime.hourToCurrentDateLong()
                            //只有有一个时段符合即为可用
                            if (currentTimeMillis > start && currentTimeMillis < end) {
                                //在使用范围不锁定
                                return false
                            } else {
                                lockFlag = true
                            }
                        }
                    }
                } else {
                    //不包含今天则锁定
                    lockFlag = true
                }
            }
            return lockFlag
        }
        return false
    }

    //处理app打开策略
    public fun getAppTimeStrategy(
        context: Context,
        pkgName: String
    ): Boolean {
        try {
            val spUtils by lazy { SharedPreferencesUtils.getInstance(context) }
            val type = object : TypeToken<List<AppTimeManageBean>>() {}.type
            val appTimeManageBeanList = spUtils.getFromJsonType(
                Const.APPSTRATEGYBEANKEY,
                ArrayList<AppTimeManageBean>().javaClass,
                type
            ) as ArrayList<AppTimeManageBean>
            //为真则可以使用，为false不可以使用,为黑名单机制，只有范围内的限制，不在范围内的不限制返回true
            var useFlag = true
            val dayList = arrayListOf(2, 3, 4, 5, 6, 7, 1)
            val currentTimeMillis = System.currentTimeMillis()
            val filter = appTimeManageBeanList.filter { it.appPackage.equals(pkgName) }
            if (filter.isNotEmpty()) {
                val calendar = Calendar.getInstance()
                //返回值 1 周日 2周一 3周二 4周三 5周四 6周五 7周六
                val dayWeek = calendar.get(Calendar.DAY_OF_WEEK)
                val appTimeManageBean = filter[0]
                val appTimes = appTimeManageBean.times
                if (appTimes == null || appTimes.size == 0) {
                    //开启策略，但不返回时间则表示锁定
                    return false
                }
                appTimes?.forEach { appTimeManageBean ->
                    val day = dayList[appTimeManageBean.week - 1]
                    if (day == dayWeek) {
                        val starttime = appTimeManageBean.starttime
                        val stoptime = appTimeManageBean.stoptime
                        starttime?.let {
                            val start = starttime.hourToCurrentDateLong()
                            stoptime?.let {
                                val end = stoptime.hourToCurrentDateLong()
                                //只有有一个时段符合即为可用
                                if (currentTimeMillis > start && currentTimeMillis < end) {
                                    //在使用范围则可用
                                    return true
                                } else {
                                    useFlag = false
                                }
                            }
                        }
                    } else {
                        //不包含今天则不可用
                        useFlag = false
                    }
                }
                return useFlag
            }
            return true
        } catch (e: Exception) {
            LogShow("问题是" + e.toString())
            return true
        }
    }

    /**
     * 处理学校设置的设备设置管理,设计隐藏的隐藏图标，
     */
    public fun setSchoolSetDevice(schoolDeviceSetBean: SchoolDeviceSetBean, appList: List<AppInfo>):ArrayList<AppInfo> {
        val dataList = arrayListOf<AppInfo>()
        appList.forEach { appinfo ->
            if (ModelNameUtils.IS_LianxX505f()||ModelNameUtils.IS_LianxX6e6f()){
                //启用电话短信:1是0否
                if (schoolDeviceSetBean.simcard == 0 && (appinfo.packageName.equals(Const.ANDROIDPHONE) || appinfo.packageName.equals(Const.ANDROIDMMS))) {
                    return@forEach
                }
                //是否隐藏日历:1是0否
                if (schoolDeviceSetBean.calendar == 1 && appinfo.packageName.equals(Const.ANDROIDCALENDAR)) {
                    return@forEach
                }
                //是否隐藏闹钟:1是0否
                if (schoolDeviceSetBean.alarmClock == 1 && appinfo.packageName.equals(Const.ANDROIDDESKCLOCK)) {
                    return@forEach
                }
                //是否隐藏相机:1是0否
                if (schoolDeviceSetBean.camera == 1 && appinfo.packageName.equals(Const.ANDROIDCAMERA)) {
                    return@forEach
                }
                //是否隐藏相册:1是0否(505f)
                if (schoolDeviceSetBean.gallery == 1 && appinfo.packageName.equals(Const.ANDROIDGALLERY)) {
                    return@forEach
                }
                //是否隐藏相册:1是0否(6e6f)
                if (schoolDeviceSetBean.gallery == 1 && appinfo.packageName.equals(Const.ANDROIDGALLERY6)) {
                    return@forEach
                }
            }
            //是否隐藏一键加速:1是0否
            if (schoolDeviceSetBean.accelerate==1&&appinfo.packageName.equals(Const.CUSTOMSPEEDAPP)){
                return@forEach
            }
            //是否隐藏清理缓存:1是0否
            if (schoolDeviceSetBean.cleanup==1&&appinfo.packageName.equals(Const.CUSTOMCLEARAPP)){
                return@forEach
            }
            //是否隐藏自动旋转:1是0否
            if (schoolDeviceSetBean.rotateSetting==1&&appinfo.packageName.equals(Const.CUSTOMROTATIONAPP)){
                return@forEach
            }
            //是否隐藏修改密码
            if (schoolDeviceSetBean.changePwd==0&&appinfo.packageName.equals(Const.CUSTOMCHANGEPSD)){
                return@forEach
            }
            dataList.add(appinfo)
        }
        return dataList
    }

    //获得存储的学校设备设置
    public fun getSchoolDeviceSetBean(context: Context):SchoolDeviceSetBean?{
        val spUtils = SharedPreferencesUtils.getInstance(context)
        var schoolDeviceSetBean: SchoolDeviceSetBean? = null
        try {
            val beanStr =
                spUtils.getFromJson(Const.SCHOOLSETDEVICE, SchoolDeviceSetBean().javaClass)
            if (beanStr != null) {
                schoolDeviceSetBean = beanStr as SchoolDeviceSetBean
            }
        } catch (e: Exception) {
            //为了不影响列表显示
        }
        return schoolDeviceSetBean
    }

    /**
     * 设置网络白名单
     */
    public fun setNetWhiteList(data:ArrayList<String>){
        ManageApplication.setUrlWhiteListWrite(data)
    }
    /**
     * 清理其他app进程
     */
    public fun clearMemory(context: Context,data: List<AppInfo>) {
        try {
            val service : ActivityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val runningAppProcesses = service.runningAppProcesses
            runningAppProcesses.forEach {process->
                LogShow("当前运行应用名称"+process.processName+"|||"+process?.importanceReasonComponent?.packageName)
                data.filter { it.packageName.equals(process.processName) }.forEach {
                    LogShow("当前运行应用名称,被清理的时"+it.packageName)
                    ManageApplication.killApplicationProcess(it.packageName)
                }
            }
        }catch (e:Exception){

        }
    }

    /**
     * 清理其他app缓存
     */
    public fun clearAppData(context: Context) {
        try {
            val spUtils by lazy { SharedPreferencesUtils.getInstance(context) }
            val type = object : TypeToken<List<AppModel>>() {}.type
            val appModelList = spUtils.getFromJsonType(
                Const.APPSTOREDATAKEY,
                ArrayList<AppModel>().javaClass,
                type
            ) as ArrayList<AppModel>

            val strings= arrayListOf<String>()
            appModelList.forEach {
                if (it.cached==1){
                    strings.add(it.appPackage)
                }
            }
            ManageApplication.clearAppData(strings)
        }catch (e:Exception){

        }
    }

    /**
     * 解除管控
     */
    public fun releaseControl(context: Context){
          try {
              //允许截屏
              ManageApplication.enableCaptureScreen(true)
              //解除状态栏管理
              ManageApplication.disableStatusBarPanel(false)
              //允许安装app
              ManageApplication.disableInstallation(false)
              //取消相机禁用
              ManageApplication.disableCamera(false)
              //显示底部虚拟键
              ManageApplication.hideHomeSoftKey(false)
              ManageApplication.hideMenuSoftKey(false)
              //允许截屏
              ManageApplication.enableCaptureScreen(true)
              //允许操作wifi
              ManageApplication.disallowWifi(false)
              ManageApplication.disallowWifiAdvanceSettings(false)
              //允许sd卡
              ManageApplication.enableMassStorage(true)
              //允许OTG
              ManageApplication.setCustomOTG(true)
              //关闭网络规则
              ManageApplication.ClearIpHostRules()
              //关闭App规则
              ManageApplication.clearAppWhiteRule()
              //关闭网络白名单
              ManageApplication.setUrlWhiteListEnable(false)

              //清除数据
              WorkManager.getInstance(context).cancelAllWork()
              context.deleteSharedPreferences(SharedPreferencesUtils.SP_FILE_NAME)
              Const.USERID = null
              Const.USERNAME = ""
              AppSocket.onDestroy()

              //设置默认启动器
              if (ModelNameUtils.IS_LianxX505f()||ModelNameUtils.IS_LianxX6e6f()){
                  //505f的桌面名称
                  ManageApplication.setCustomLauncher("com.tblenovo.launcher","com.android.iotlauncher.IotLauncher")
                  try {
                      val launchIntent = Intent()
                      launchIntent.setComponent(
                          ComponentName(
                              "com.tblenovo.launcher",
                              "com.android.iotlauncher.IotLauncher"
                          )
                      )
                      launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                      context.startActivity(launchIntent)
                      exitProcess(0)
                  }catch (e:Exception){
                      Toaster.showLong("失败原因"+e.toString())
                  }
              }
          }catch (e:Exception){

          }
    }

    //初始化管控的默认规则
    public fun initControlStrategy(){
        if (ModelNameUtils.IS_LianxX505f()||ModelNameUtils.IS_LianxX6e6f()) {
            //是505f则执行
            //启用白名单
            ManageApplication.setUrlWhiteListEnable(true)
            ManageApplication.addInstallPackageWhiteList(
                arrayListOf(
                    Const.CURRENTAPPPKG,
                    Const.STOREAPPPKG
                )
            )
            ManageApplication.setSleepTimeoutV3()
            //给自己加入网络白名单
            ManageApplication.addAppWhiteRule(arrayListOf(Const.CURRENTAPPPKG))
            //禁止状态栏下拉，屏蔽底部虚拟键。
            ManageApplication.disableStatusBarPanel(true)
            ManageApplication.hideHomeSoftKey(true)
            ManageApplication.hideMenuSoftKey(true)
            ManageApplication.enableAccessibility()
            ManageApplication.setCustomLauncher(
                Const.CURRENTAPPPKG,
                Const.CURRENTAPPPKG + ".ui.ManageActivity"
            )
            if (Const.isDebug){
                ManageApplication.setPackageEnabled("com.xhly.easystud", true)
                ManageApplication.setUrlWhiteListEnable(false)
                ManageApplication.disableStatusBarPanel(false)
                ManageApplication.hideHomeSoftKey(false)
                ManageApplication.hideMenuSoftKey(false)
            }
            ManageApplication.urlWhiteListRead().forEach {
                LogShow("白名单有$it")
            }
            ManageApplication.getWifiWhiteList().forEach {
                LogShow("wifi白名单有$it")
            }
        }
    }
}