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

import BaseActivity
import DownLoadUtils
import DownloadCallback
import DownloadItem
import android.Manifest
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Notification
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.ConnectivityManager
import android.os.Build
import android.provider.Settings
import android.view.MotionEvent
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.addCallback
import androidx.appcompat.content.res.AppCompatResources
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.transition.Transition
import com.google.gson.reflect.TypeToken
import com.hjq.toast.Toaster
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import com.tbruyelle.rxpermissions2.RxPermissions
import com.xhkjedu.manageapp.R
import com.xhkjedu.manageapp.databinding.ActivityMainBinding
import com.xhly.corelib.Const
import com.xhly.corelib.bean.AppInfo
import com.xhly.corelib.eventbus.UIEvent
import com.xhly.corelib.utils.AppUtils
import com.xhly.corelib.utils.CustomOSUtils
import com.xhly.corelib.utils.FileUtils
import com.xhly.corelib.utils.GsonUtils
import com.xhly.corelib.utils.ImageUtils
import com.xhly.corelib.utils.LogShow
import com.xhly.corelib.utils.ModelNameUtils
import com.xhly.corelib.utils.NetworkUtils
import com.xhly.corelib.utils.SharedPreferencesUtils
import com.xhly.corelib.utils.SystemUtil
import com.xhly.manageapp.AppAdapter
import com.xhly.manageapp.ManageApplication
import com.xhly.manageapp.bean.EventLog
import com.xhly.manageapp.bean.PadLocationConst
import com.xhly.manageapp.bean.SocketMsgBean
import com.xhly.manageapp.bean.app.AppInstallBean
import com.xhly.manageapp.bean.app.AppModel
import com.xhly.manageapp.bean.log.LogPushBean
import com.xhly.manageapp.bean.log.LogdOperateBean
import com.xhly.manageapp.bean.log.UpdateBean
import com.xhly.manageapp.bean.scheme.AutoAppBean
import com.xhly.manageapp.bean.school.SchoolDeviceSetBean
import com.xhly.manageapp.bean.strategy.StrategyBean
import com.xhly.manageapp.bean.user.UserBean
import com.xhly.manageapp.broadcastreceiver.AppInstallReceiver
import com.xhly.manageapp.broadcastreceiver.NetConnectReceiver
import com.xhly.manageapp.broadcastreceiver.ScreenReceiver
import com.xhly.manageapp.service.ManageAccessibilityService
import com.xhly.manageapp.service.websocket.AppSocket
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.CurrentAppSharedPreferencesUtils
import com.xhly.manageapp.utils.CustomAppUtils
import com.xhly.manageapp.utils.InstallUtils
import com.xhly.manageapp.utils.PadInfoUtils
import com.xhly.manageapp.utils.StrategyUtils
import com.xhly.manageapp.workmanager.TimingWorker
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.util.Calendar
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.TimeUnit


class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>(),DownloadCallback {
    var adapter: AppAdapter? = null

    private var mMyInstallReceiver: AppInstallReceiver? = null
    private var netConnectReceiver:NetConnectReceiver?=null
    private var mScreenReceiver:ScreenReceiver?=null
    private var dataList: ArrayList<AppInfo> = arrayListOf()
    private var userBean: UserBean? = null
    private var timer: Timer? = null
    private val currentSpUtils by lazy { CurrentAppSharedPreferencesUtils.getInstance(this) }
    //标记锁屏时请求策略的时间,锁屏页面最快两分钟可以获得一次策略
    private var lastTimeLong=0L
    //标记是否请求了时间策略
    private var updateTimeFlag = false

    //标记是否请求了应用策略，都为真则提示
    private var updateStrategyFlag = false
    //标记当前是否锁定
    private var mainLockFlag=false
    private var autoAppFlag=true

    private var accountDialog:CustomDialog?=null

    //标记是否可以点击啊
    private var canClickFlag=false
    //百度定位
    private var locationClient:LocationClient?=null

    //上次提醒时长，用来设置是否重新设置提醒任务
    private var lastTipsTimeLong=0
    //判断是否从oncreat执行，防止时间策略多次执行
    private var isCreatFlag=false

    private var appStroeList:ArrayList<AppModel> = arrayListOf()


    override fun getBinding() = ActivityMainBinding.inflate(layoutInflater)

    @SuppressLint("CheckResult")
    override fun initData() {
        val json = spUtils.getFromJson(Const.USERINFO, UserBean().javaClass)
        if (json == null) {
            loginOut(false)
            return
        } else {
            userBean = json as UserBean
        }
        //自动同时一次时间
        viewModel.postSyncTime()
        viewModel.timeResultData.observe(this){
            ManageApplication.setSysTime(it)
        }
        lifecycleScope.launch {
            withContext(Dispatchers.IO) {
                val file = File(filesDir, "wallpaper.png")
                if (file.exists()) {
                    try {
                        val bitmap = ImageUtils().getBitmapFromFile(file.toString())
                        withContext(Dispatchers.Main) {
                            try {
                                mBinding.root.background = BitmapDrawable(resources, bitmap)
                            } catch (e: Exception) {
                                LogShow("图片设置失败")
                            }
                        }
                    } catch (e: Exception) {
                        LogShow("图片不存在")
                    }
                }
            }
        }
        DownLoadUtils.addCallback(this)
        adapter = AppAdapter(this, dataList)
        mBinding.rv.layoutManager = GridLayoutManager(this, 6, GridLayoutManager.VERTICAL, false)
        adapter?.changePwdListener = getChangeCodeListener()
        mBinding.rv.adapter = adapter
        updateAppRv()
        // checkAccessibility(this)
        registerAppInstallReceiver()
        registerNetConnectReceiver()
        registerScreenReceiver()
        /*
         使用情况权限
         val permissionIntent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
          startActivity(permissionIntent)*/
        // csdkManagerUtils.csdkManager.enableAccessibility("com.xhly.manageapp","com.xhly.manageapp.service.TestService",true)

        viewModel.pwdResultData.observe(this) {
            if (it) {
                unBindBlock()
            } else {
                Toast(getString(R.string.codeerror))
            }
        }

        viewModel.wallpaperData.observe(this) {
            if (!it.hpath.isNullOrBlank()) {
                Glide.with(this).load(Const.URL1 + it.hpath).placeholder(R.drawable.main_bg)
                    .error(R.drawable.main_bg)
                    .into(object : CustomViewTarget<LinearLayout, Drawable>(mBinding.root) {
                        override fun onLoadFailed(errorDrawable: Drawable?) {
                            errorDrawable?.let { drawble ->
                                mBinding.root.background = drawble
                            }
                        }

                        override fun onResourceCleared(placeholder: Drawable?) {
                            placeholder?.let { drawble ->
                                mBinding.root.background = drawble
                            }
                        }

                        override fun onResourceReady(
                            resource: Drawable,
                            transition: Transition<in Drawable>?
                        ) {
                            mBinding.root.background = resource
                            val imageUtil = ImageUtils()
                            imageUtil.saveBitmapToFile(
                                imageUtil.drawableToBitmap(resource),
                                File(filesDir, "wallpaper.png")
                            )
                        }
                    })
            }
        }


        viewModel.lockResultData.observe(this) {
            if (it) {
                spUtils.setParam(Const.DISABLEPAD, true)
                startIntentActivity(MainActivity().javaClass)
                val appList = AppUtils.GetAppList(this)
                StrategyUtils.clearMemory(this, appList)
            }
        }
        viewModel.resetlResultData.observe(this) {
            if (it) {
                ManageApplication.launchFactoryReset()
            }
        }

        viewModel.viewModelScope.launch {
            //在这里执行获得策略的操作，用来处理在后台时的数据处理。
            viewModel.listAppData.collect{ modelList ->
                modelList?.let {
                    appStroeList.clear()
                    appStroeList.addAll(it)
                    //存储商店应用包名到本地,并且存储商店应用列表数据到本地集合
                    val appNameList = arrayListOf<String>()
                    val whiteList = arrayListOf<String>()
                    modelList.forEach {
                        appNameList.add(it.appPackage)
                        if (it.whited == 1) {
                            whiteList.add(it.appPackage)
                        }
                    }
                    //添加到应用网络白名单
                    ManageApplication.addAppWhiteRule(whiteList)
                    //添加到安装应用白名单
                    ManageApplication.addInstallPackageWhiteList(appNameList)
                    spUtils.saveJson(Const.APPSTOREDATAKEY,modelList)
                    //获得应用集合，必装应用和推荐应用，再加上预装应用(预装应用直接隐藏)，其余应用需要静默卸载,必装应用需要进行静默下载和安装。安装应用从forceapp接口获取
                    val appList = AppUtils.GetAppList(this@MainActivity)
                    val firstAppList = arrayListOf<String>()
                    try {
                        //获得预装应用的包名
                        val currentList =
                            currentSpUtils.getFromJson(
                                Const.FIRSTAPPLIST,
                                ArrayList<String>().javaClass
                            ) as ArrayList<String>
                        firstAppList.addAll(currentList)
                    } catch (e: Exception) {
                        LogShow("冻结失败" + e.toString())
                    }
                    appList.forEach { app ->
                        val filter = modelList.filter { it.appPackage.equals(app.packageName) }
                        val appInfos = firstAppList.filter { app.packageName.equals(it) }
                        //接口列表以及初始化列表中不存在则将应用冻结或者卸载,目前是卸载
                        LogShow("${app.name},被冻结" + (filter.isEmpty() && appInfos.isEmpty()))
                        if (filter.isEmpty() && appInfos.isEmpty()) {
                            //ManageApplication.setPackageEnabled(app.packageName, (filter.isNotEmpty()))
                            ManageApplication.uninstallPackage(app.packageName)
                        }
                    }

                }
            }
        }

        viewModel.viewModelScope.launch {
            viewModel.forceListAppData.collect { modelList ->
               modelList?.let {
                   //获得必装应用，未安装或者版本较低则更新，先删除目录中的文件
                   val rxPermissions = RxPermissions(this@MainActivity)
                   rxPermissions.request(Manifest.permission.REQUEST_INSTALL_PACKAGES)
                       .subscribe { granted ->
                           if (granted || ModelNameUtils.IS_LianxX505f()||ModelNameUtils.IS_LianxX6e6f()) {
                               // 权限已授予，执行安装操作
                               val appList = AppUtils.GetAppList(this@MainActivity)
                               getExternalFilesDir(null)?.let {
                                   FileUtils.deleteCurrentFlie(it)
                               }
                               val file = getExternalFilesDir(null)
                               modelList.forEach { app ->
                                   try {
                                       //获得已安装的应用判断版本，未安装的则直接静默安装。
                                       val filter =
                                           appList.filter { it.packageName.equals(app.appPackage) }
                                       //列表中不存在,或者版本较低则更新
                                       val apkPath = app.apkPath
                                       val appName = app.appName
                                       if (filter.isNotEmpty()) {
                                           val currentApp = filter[0]
                                           if (app.versionNum > currentApp.versionNum) {
                                               //版本低则更新安装。
                                               //AppDownLoadUtils.addToDownloadQueue(apkPath, appName,app.appPackage)
                                               DownLoadUtils.addDownload(apkPath,app.appPackage,File(file.toString(), "$appName.apk").toString(),app.appPackage,appName)
                                           }
                                       } else {
                                           //不存在，直接下载安装。
                                           //AppDownLoadUtils.addToDownloadQueue(apkPath, appName,app.appPackage)
                                           DownLoadUtils.addDownload(apkPath,app.appPackage,File(file.toString(), "$appName.apk").toString(),app.appPackage,appName)
                                       }
                                   } catch (e: Exception) {
                                       LogShow("问题" + e.toString())
                                   }
                               }
                           } else {
                               // 用户拒绝了安装权限，处理相应逻辑
                               viewModel.getAppList()
                           }

                       }

               }
            }

        }

        viewModel.viewModelScope.launch {
            viewModel.strategyData.collect {
              it?.let {
                  spUtils.saveJson(Const.STRATEGYBEANKEY, it)
                  StrategyUtils.setStrategy(it)
                  useTimeStrategy()
                  updateStrategyFlag = true
                  if (updateTimeFlag) {
                      showSucessToast()
                  }

              }
            }
        }

        viewModel.viewModelScope.launch {
            viewModel.appStrategyData.collect {
                //存储app时间策略
               it?.let {
                   spUtils.saveJson(Const.APPSTRATEGYBEANKEY, it)
                   updateTimeFlag = true
                   if (updateStrategyFlag) {
                       showSucessToast()
                   }
               }
            }
        }

        viewModel.viewModelScope.launch {
            viewModel.padInfoData.collect {
                //存储信息上传时间
                it?.let {
                    if (it) {
                        spUtils.setParam(Const.PADINFOTIMEKEY, System.currentTimeMillis())
                    }
                }
            }
        }

        viewModel.viewModelScope.launch {
            viewModel.loginOutData.collect {
                it?.let {
                    if (it) {
                        loginOut()
                    } else {
                        Toast(getString(R.string.codeerror))
                    }
                }
            }
        }

        viewModel.viewModelScope.launch {
            viewModel.updateInfoData.collect {
                //成功则保存不在提交
                if (it!=null&&it) {
                    spUtils.setParam(Const.PADUPDATETIMEKEY, System.currentTimeMillis())
                }
            }
        }

        viewModel.viewModelScope.launch {
            viewModel.schoolSetData.collect {
                it?.let {
                    spUtils.saveJson(Const.SCHOOLSETDEVICE, it)
                    initSchoolSet(it)
                    mBinding.rv.visibility=View.VISIBLE
                    updateAppRv()
                }
            }
        }

        viewModel.viewModelScope.launch {

            viewModel.netWhiteListData.collect {
               it?.let {
                   StrategyUtils.setNetWhiteList(it)
               }
            }

        }


        viewModel.viewModelScope.launch {

            viewModel.logResultData.collect {
                it?.let {
                    if (it.enableFlag) {
                        when (it.pushType) {
                            2 -> {
                                spUtils.setParam(Const.DISABLEPAD, false)
                                useTimeStrategy()
                            }

                            3 -> {
                                val appList = AppUtils.GetAppList(this@MainActivity)
                                StrategyUtils.clearMemory(this@MainActivity, appList)
                                spUtils.setParam(Const.DISABLEPAD, true)
                                startIntentActivity(MainActivity().javaClass)
                            }

                            4 -> {
                                //请求接口更新策略
                                updateAllStrategy()
                            }

                            5 -> {
                                ManageApplication.rebootDevice()
                            }

                            6 -> {
                                loginOutSucess()
                                ManageApplication.launchFactoryReset()
                            }

                            7 -> {
                                currentSpUtils.setParam(Const.EXIT_CONTROL, true)
                                StrategyUtils.releaseControl(this@MainActivity)
                            }

                            8 -> {
                                loginOut()
                            }
                        }
                    }

                }
            }
        }

        viewModel.viewModelScope.launch {
            viewModel.logEventData.collect {
               it?.let {
                   when (it.logEventType) {
                       EventLog.ACCOUNTQUITEVENT -> {
                           loginOutSucess()
                       }
                   }
               }
            }
        }

        viewModel.viewModelScope.launch {
            viewModel.autoAppData.collect{
                it?.let {
                    //连接不为空，并且应用已安装则跳转应用
                      it.authUrl="com.xhkjedu.xh_control_browser.MainActivit111y"
                      it.appPackage="com.xhkjedu.xh_control_browser"
                    LogShow("锁定了吧"+mainLockFlag)
                    if (!mainLockFlag){
                        if (it.authUrl!=null&&AppUtils.isAppInstalled(this@MainActivity,it.appPackage)){
                            spUtils.saveJson(Const.AUTOAPPKEY,it)
                            startAutoApp(it)
                        }else{
                            try {
                                val autoAppBean = spUtils.getFromJson(Const.AUTOAPPKEY, AutoAppBean().javaClass) as AutoAppBean
                                if (autoAppBean.authUrl!=null&&AppUtils.isAppInstalled(this@MainActivity,autoAppBean.appPackage)&&!it.netSucessFlag){
                                    startAutoApp(autoAppBean)
                                }else{
                                    canClickFlag=true
                                }
                            }catch (e:Exception){
                                canClickFlag=true
                            }
                        }
                    }else{
                        canClickFlag=true
                        autoAppFlag=false
                        startIntentActivity(MainActivity().javaClass)
                    }

                }
             }
        }
        getLocation()
        startWorkManager()
        lastTimeLong=System.currentTimeMillis()
        isCreatFlag=true
        updateAllStrategy()
    }

    private fun startAutoApp(autoAppBean: AutoAppBean){
        try {
            val launchIntent = Intent()
            launchIntent.setComponent(
                ComponentName(
                    autoAppBean.appPackage!!,
                    autoAppBean.authUrl!!
                )
            )
            launchIntent.putExtra("authType",autoAppBean.authType)
            userBean?.let {
                when(autoAppBean.authType){
                    1->{
                        val userid = it.userid
                        launchIntent.putExtra("authData",userid.toString())
                    }
                    2->{
                        val studentno = it.studentno
                        launchIntent.putExtra("authData",studentno.toString())
                    }
                    3->{
                        val userphone = it.userphone
                        launchIntent.putExtra("authData",userphone.toString())
                    }
                    4->{
                        val cardid = it.cardid
                        launchIntent.putExtra("authData",cardid.toString())
                    }
                    else->{

                    }
                }
            }
            startActivity(launchIntent)
        }catch (e:Exception){
            canClickFlag=true
            LogShow("跳转问题是$e")
        }

    }
    private fun showSucessToast() {
        Toaster.show(R.string.updatetips)
        updateStrategyFlag = false
        updateTimeFlag = false
    }


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

    override fun initView() {
        userBean?.let {
            mBinding.usernameTv.text = it.username
        }

        mBinding.btn.setOnClickListener {
            startIntentActivity(ManageActivity().javaClass)
        }

        mBinding.lockLlayout.setOnClickListener {
            //限制最多1分钟请求一次策略,
            if (lastTimeLong+1*60*1000<System.currentTimeMillis()){
                lastTimeLong=System.currentTimeMillis()
                updateAllStrategy()
            }
        }
        mBinding.codeenterCv.setOnClickListener {
            //如果密码一致,则解锁
            val code = mBinding.lockEt.text.toString()
            if (code.isNullOrBlank()) {
                return@setOnClickListener
            }
            ManageApplication.getDeviceInfo()?.let {
                viewModel.postPwdDetail(code, it)
            }
        }
        mBinding.loginoutLlayout.setOnClickListener {
            val schoolDeviceSetBean = StrategyUtils.getSchoolDeviceSetBean(this@MainActivity)
            //禁用注销则需要输入密码才能注销，不限制则直接注销登录
            if (schoolDeviceSetBean != null && schoolDeviceSetBean.logout == 1) {
                //禁用注销
                showEditDialog()
            } else {
                try {
                    val userBean = spUtils.getFromJson(
                        Const.USERINFO, UserBean().javaClass
                    ) as UserBean
                    viewModel.loginOut(userBean.userid.toString(), "")
                } catch (e: Exception) {

                }
            }
        }
        mBinding.netsetLlayout.setOnClickListener {
            startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
        }
        onBackPressedDispatcher.addCallback {
            //屏蔽返回键
            Const.backNum++
            if (Const.backNum > Const.UPDATESTRATEGYNUM) {
                Const.backNum = 0
                updateAllStrategy()
            }
        }
    }

    //解锁屏幕
    private fun unBindBlock() {
        spUtils.setParam(Const.DISABLEPAD, false)
        useTimeStrategy()
        if (mBinding.mainLlayout.visibility == View.GONE) {
            Toast(getString(R.string.padtimestoptips))
        }
    }

    private fun getChangeCodeListener(): AppAdapter.ChangePwdListener {
        return object : AppAdapter.ChangePwdListener {
            override fun changeCode() {
                val deviceSetBean = StrategyUtils.getSchoolDeviceSetBean(this@MainActivity)
                var showFlag = true
                if (deviceSetBean != null && deviceSetBean.changePwd == 0) {
                    //学校设置是否禁止修改密码
                    showFlag = false
                }
                if (showFlag) {
                    showChangeCodeDialog()
                }
            }

        }
    }

    private fun showChangeCodeDialog() {
        CustomDialog.build()
            .setCustomView(object : OnBindView<CustomDialog>(R.layout.layout_changecode_dialog) {
                override fun onBind(dialog: CustomDialog, v: View) {
                    //TODO 修改密码接口没有
                    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)
                    val oldCodeEt = v.findViewById<EditText>(R.id.dialog_oldcode_et)
                    val newCodeEt = v.findViewById<EditText>(R.id.dialog_newcode_et)
                    enterTv.setOnClickListener {
                        val enterCode = editText.text.toString()
                        val oldCode = oldCodeEt.text.toString()
                        val newCode = newCodeEt.text.toString()
                        if (!getTextFlag(enterCode) || !getTextFlag(oldCode) || !getTextFlag(newCode)) {
                            Toast("密码不符合规则")
                            return@setOnClickListener
                        }
                        if (oldCode.equals(newCode)) {
                            Toast("新密码不能和旧密码一致")
                            return@setOnClickListener
                        }

                        if (!newCode.equals(enterCode)) {
                            Toast("两次输入的新密码不一致")
                            return@setOnClickListener
                        }

                        dialog.dismiss()
                        try {
                            val userBean = spUtils.getFromJson(
                                Const.USERINFO, UserBean().javaClass
                            ) as UserBean
                            viewModel.postEditPwd(userBean.userid, newCode, oldCode)
                        } catch (e: Exception) {

                        }
                    }
                    cancelTv.setOnClickListener {
                        dialog.dismiss()
                    }
                }
            }).setCancelable(false).setMaskColor(Color.parseColor("#66000000"))
            .setAlign(CustomDialog.ALIGN.CENTER).show()
    }

    private fun getTextFlag(code: String?): Boolean {
        try {
            return (!code.isNullOrBlank()) && code.length >= 6 && code.length <= 16
        } catch (e: Exception) {
            return false
        }
    }

    override fun onResume() {
        super.onResume()
        updateNetErrorAppRv()
        lifecycleScope.launch(Dispatchers.IO){
            try {
                val json = spUtils.getFromJson(Const.USERINFO, UserBean().javaClass)
                if (json == null) {
                    Toaster.show("用户信息为空")
                } else {
                    userBean = json as UserBean
                }
            }catch (e:Exception){

            }
        }
        Const.backNum++
        if (mainLockFlag&&lastTimeLong+5*60*1000<System.currentTimeMillis()){
            //如果时锁定状态进入这个页面则请求一次策略,限制为5分钟
            lastTimeLong=System.currentTimeMillis()
            updateAllStrategy()
        }else if (Const.backNum > Const.UPDATESTRATEGYNUM){
            //进入该页面20次或者点击返回键20次需要更新策略
            lastTimeLong=System.currentTimeMillis()
            Const.backNum = 0
            updateAllStrategy()
        }else{
            if (!isCreatFlag){
                useTimeStrategy()
            }
            isCreatFlag=false
        }
     /*   userBean?.let {
            viewModel.postAutoAppDetail(it.regionid)
        }*/
        updatePadInfo()
        updateMcApp()
        val appVersionCode = SystemUtil.getAppVersionCode(this, packageName)
        val appVersionName =SystemUtil.getAppVersionName(this,packageName)
        mBinding.versionTv.text="版本 v${appVersionName} (Build ${appVersionCode})"
        if (SystemUtil.isSuEnable()){
            //root了则调用接口
            val data = LogdOperateBean()
            ManageApplication.getDeviceInfo()?.let {
                data.sn = it
            }
            data.comm = "设备ROOT"
            data.doEvent = EventLog.ROOTEVENT
            viewModel.eventLog(data)
        }
    }

    private fun updateAllStrategy() {
        LogShow("请求策略锁定了吧")
        userBean?.let {
            Const.USERID = it.userid
            Const.USERNAME = it.username.toString()
            viewModel.postDevicesetDetail(it.schoolid)
            val name = StringBuffer()
            if (!it.schoolName.isNullOrBlank()) {
                name.append(it.schoolName)
            }
            if (!it.classname.isNullOrBlank()) {
                name.append(it.classname)
            }
            mBinding.userschoolTv.text = name.toString()
        }
        viewModel.postWallpaperPad()
        viewModel.updateStrategy()
        viewModel.uploadAppStrategy()
        viewModel.postAppNetWhiteList()
        updatePadInfo()
        updateAppInstallInfo()
    }

    private fun updateAppInstallInfo() {
        try {
            //获得已安装应用列表
            val appList = AppUtils.GetAppList(this)
            try {
                //获得预装应用的包名
                val currentList =
                    currentSpUtils.getFromJson(
                        Const.FIRSTAPPLIST,
                        ArrayList<String>().javaClass
                    ) as ArrayList<String>
                val removeList = arrayListOf<AppInfo>()
                currentList.forEach { pkg ->
                    //除了管控之类的我们的app之外的预装都不在统计范围
                    if (Const.CURRENTAPPPKG != pkg && Const.STOREAPPPKG != pkg) {
                        appList.filter { it.packageName == pkg }.forEach {
                            removeList.add(it)
                        }
                    }
                }
                //除了管控之类的我们的app之外的预装都不在统计范围,所以移除
                appList.removeAll(removeList)
            } catch (e: Exception) {

            }
            val userBean = spUtils.getFromJson(Const.USERINFO, UserBean().javaClass) as UserBean
            val appInstallList = arrayListOf<AppInstallBean>()
            appList.forEach {
                val appInstallBean = AppInstallBean()
                appInstallBean.userid = userBean.userid
                appInstallBean.appName = it.name
                appInstallBean.appVersion = it.versionName
                appInstallBean.appNum = it.versionNum
                appInstallBean.appPackage = it.packageName
                ManageApplication.getDeviceInfo()?.let { sn ->
                    appInstallBean.sn = sn
                }
                ManageApplication.getDeviceInfo(1)?.let { mac ->
                    appInstallBean.mac = mac
                }
                appInstallBean.schoolid = userBean.schoolid
                appInstallBean.regionid = userBean.regionid
                appInstallList.add(appInstallBean)
            }

            viewModel.updateAppInstallInfo(appInstallList)
        } catch (e: Exception) {

        }
    }


    @SuppressLint("CheckResult")
    private fun updatePadInfo() {
        try {
            //获得pad信息提交时间，如果为同一天则不在上传，不然继续上传
            val padTime = spUtils.getParam(Const.PADINFOTIMEKEY, 0L) as Long
            val instance = Calendar.getInstance()
            val currentYear = instance.get(Calendar.YEAR)
            val currentDay = instance.get(Calendar.DAY_OF_YEAR)
            instance.timeInMillis = padTime
            val year = instance.get(Calendar.YEAR)
            val day = instance.get(Calendar.DAY_OF_YEAR)
            val rxPermissions = RxPermissions(this)
            val request = rxPermissions.request(Manifest.permission.READ_PHONE_STATE)
            //权限通过不通过都要执行
            request.subscribe({ granted: Boolean ->
                var iccid = ""
                if (granted) {
                    iccid = SystemUtil.getICCID(this)
                }
                if (!(currentYear == year && currentDay == day)) {
                    viewModel.updatePadInfo(PadInfoUtils().getPadInfo(this, iccid))
                    updateAppInstallInfo()
                    if (lastTimeLong+10*60*1000<System.currentTimeMillis()){
                        //每日上传信息时获取策略，如果10分钟之内获取过则不再获取
                        lastTimeLong=System.currentTimeMillis()
                        updateAllStrategy()
                    }
                }
            }, {
                if (!(currentYear == year && currentDay == day)) {
                    viewModel.updatePadInfo(PadInfoUtils().getPadInfo(this, ""))
                }
            })
        } catch (e: Exception) {

        }
    }


    private fun updateMcApp() {
        //每天请求一次app更新接口，这个接口是用于提交管控自身的版本信息统计
        try {
            val userBean = spUtils.getFromJson(Const.USERINFO, UserBean().javaClass) as UserBean
            //存储pad更新请求时间，如果为同一天则不在上传，不然继续上传
            val padTime = spUtils.getParam(Const.PADUPDATETIMEKEY, 0L) as Long
            val instance = Calendar.getInstance()
            val currentYear = instance.get(Calendar.YEAR)
            val currentDay = instance.get(Calendar.DAY_OF_YEAR)
            instance.timeInMillis = padTime
            val year = instance.get(Calendar.YEAR)
            val day = instance.get(Calendar.DAY_OF_YEAR)
            if (!(currentYear == year && currentDay == day)) {
                val updateBean = UpdateBean()
                ManageApplication.getDeviceInfo()?.let {
                    updateBean.sn = it
                }
                val packageInfo =
                    packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA)
                updateBean.cversion = packageInfo.versionName
                updateBean.schoolid = userBean.schoolid
                updateBean.userid = userBean.userid
                updateBean.regionid = userBean.regionid
                viewModel.updateMcApp(updateBean)
            }
        } catch (e: Exception) {
          LogShow("用户信息不存在")
        }
    }

    @SuppressLint("CheckResult")
    private fun getLocation() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.request(
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
        ).subscribe({
            if (it) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    rxPermissions.request(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                        .subscribe {
                            //SystemUtil.getLocation(this)
                            baiduLocation()
                        }
                } else {
                    //SystemUtil.getLocation(this)
                    baiduLocation()
                }
            } else {
                baiduLocation()
                LogShow("没有权限")
            }
        }, {
            baiduLocation()
            LogShow("没有权限" + it.message)
        })
    }

    private fun baiduLocation(){
        LocationClient.setAgreePrivacy(true)
        locationClient = LocationClient(application)
        val option = LocationClientOption()
        option.locationMode=LocationClientOption.LocationMode.Hight_Accuracy
        option.setCoorType("bd09ll")
        option.setFirstLocType(LocationClientOption.FirstLocType.ACCURACY_IN_FIRST_LOC)
        option.setScanSpan(0)
        option.setOpenGnss(true)
        option.setLocationNotify(true)
        option.setEnableSimulateGnss(false)
        option.setNeedNewVersionRgc(true)
        option.setIsNeedAddress(true)
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        option.setOpenAutoNotifyMode();
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
        option.setOpenAutoNotifyMode(3000,1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
        locationClient?.locOption=option
        locationClient?.registerLocationListener(object :BDAbstractLocationListener(){
            override fun onReceiveLocation(bdLocation: BDLocation) {
                //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
                val latitude: Double = bdLocation.getLatitude() //获取纬度信息

                val longitude: Double = bdLocation.getLongitude() //获取经度信息
                val addrStr = bdLocation.addrStr
                val location = PadLocationConst.currentLocation
                location.lat=latitude
                location.lon=longitude
                location.address=addrStr
                try {
                    val lastLocation = PadLocationConst.lastLocation
                    if (location.lat!=null&&location.lon!=null&&(lastLocation.lon!=location.lon&&lastLocation.lat!=location.lat)){
                        lastLocation.lat=location.lat
                        lastLocation.lon=location.lon
                        ManageApplication.getDeviceInfo()?.let {
                            location.sn=it
                        }
                        userBean?.let {
                            location.userid=it.userid
                        }
                        viewModel.postPadLocation((location))
                        LogShow("真没有位置")
                    }else{
                        LogShow("没有位置")
                    }
                }catch (e:Exception){
                    LogShow("没有位置问题"+e.toString())
                }
                locationClient?.stop()
            }

        })
        locationClient?.start()
    }

    private fun useTimeStrategy() {
        //获得sputils中的平板锁定策略
        try {
            //如果存储的是锁定则锁定
            var block = false
            val strategyBean =
                spUtils.getFromJson(Const.STRATEGYBEANKEY, StrategyBean::class.java) as StrategyBean
            strategyBean?.let { bean ->
                //获得是否在使用时间范围
                block = StrategyUtils.getPadTimeStrategy(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
                //隐藏账号编辑弹窗
                accountDialog?.dismiss()
                mainLockFlag=true
                //锁定时可以点击
                canClickFlag=true
            } else {
                mainLockFlag=false
                autoAppFlag=true
                mBinding.mainLlayout.visibility = View.VISIBLE
                mBinding.lockLlayout.visibility = View.GONE
                hiddenSoft(mBinding.lockEt)
            }
            //如果同时锁定和平板不再可用时间，优先显示锁定提示，锁定接触后显示不再可用时间提示
            mBinding.locktipsTv.text=if (param){
                getString(R.string.locktips)
            }else if (block){
                getString(R.string.timelocktips)
            }else{
                getString(R.string.locktips)
            }
            mBinding.lockEt.setText("")
        } catch (e: Exception) {
            mainLockFlag=false
            //默认不锁定
            mBinding.mainLlayout.visibility = View.VISIBLE
            mBinding.lockLlayout.visibility = View.GONE
        }
        LogShow("锁定了吧"+mainLockFlag+"|||"+autoAppFlag)
        if (autoAppFlag){
            userBean?.let {
                viewModel.postAutoAppDetail(it.regionid)
            }
        }
    }

    private fun initSchoolSet(schoolDeviceSetBean: SchoolDeviceSetBean? = null) {
        schoolDeviceSetBean?.let { bean ->
            //是否启用截屏:1是0否
            ManageApplication.enableCaptureScreen(schoolDeviceSetBean.screenshots == 1)
            if (bean.schoolClass == 1) {
                mBinding.userschoolTv.visibility = View.VISIBLE
            } else {
                mBinding.userschoolTv.visibility = View.INVISIBLE
            }
            //设置护眼模式
            CustomOSUtils.openOrCloseNightMode(this, bean.protectedEyes == 1)
            startTimeTask(bean)
        }
    }

    private fun startTimeTask(bean: SchoolDeviceSetBean,fromBroadcast:Boolean=false) {
        //和上次时长不一致才使用，但是从广播调用时不用和上次时长对比
        if (bean.remindDuration == 1 && bean.duration > 0&&(lastTipsTimeLong!=bean.duration||fromBroadcast)) {
            //如果设置的有时间则执行任务
            try {
                timer?.cancel()
                timer = Timer()
            } catch (e: Exception) {

            }
            lastTipsTimeLong=bean.duration
            timer?.let {
                timer?.schedule(object : TimerTask() {
                    override fun run() {
                        Toast(getString(R.string.durationtips))
                    }
                }, bean.duration * 60 * 1000L, bean.duration* 60 * 1000L)
            }
        }
        //如果设置的有时间则取消所有任务
        if (bean.remindDuration != 1) {
            if (timer != null) {
                timer?.cancel()
                timer = null
            }
        }
    }


    override fun onUiEvent(uiEvent: UIEvent) {
        super.onUiEvent(uiEvent)
        when (uiEvent.getEvent()) {
            "update" -> {
                updateAppRv()
            }

            Const.CODE2001.toString() -> {
                val message = uiEvent.message
                showNoticeDialog(message)
            }

            Const.CODE2002.toString() -> {
                //杀掉其他app之保留自己
                postLogPush(3)
            }

            Const.CODE2003.toString() -> {
                postLogPush(2)
            }

            Const.CODE2004.toString() -> {
                postLogPush(4)
            }

            Const.CODE2005.toString() -> {
                postLogPush(5)
            }

            Const.CODE2006.toString() -> {
                postLogPush(6)
            }

            Const.CODE2007.toString() -> {
                postLogPush(7)
            }

            Const.CODE2008.toString() -> {
                postLogPush(8)
            }

            Const.LOGAPPSTART -> {
                val message = uiEvent.message
                if (Const.LASTPKGNAME == message) {
                    return
                }
                val filter = dataList.filter { it.packageName == message }
                if (filter.isNotEmpty()) {
                    Const.LASTPKGNAME = message
                    val data = LogdOperateBean()
                    ManageApplication.getDeviceInfo()?.let {
                        data.sn = it
                    }
                    data.appPackage = message
                    val packageInfo =
                        packageManager.getPackageInfo(message, PackageManager.GET_META_DATA)
                    val label =
                        packageManager.getApplicationLabel(packageInfo.applicationInfo)
                    data.comm =label.toString()
                    data.doEvent = EventLog.STARTAPPEVENT
                    viewModel.eventLog(data)
                }
            }

            Const.APPINSTALL -> {
                try {
                    val message = uiEvent.message
                    updateAppRv()
                    val data = LogdOperateBean()
                    ManageApplication.getDeviceInfo()?.let {
                        data.sn = it
                    }
                    try {
                        //优先从集合中取名字
                        getAppStoreList()
                        val filter = appStroeList.filter { it.appPackage == message }
                        val label =if (filter.isNotEmpty()){
                            filter[0].appName
                        }else{
                            ""
                        }
                        data.comm =label.toString()
                    }catch (e:Exception){

                    }finally {
                     if (data.comm.isNullOrBlank()){
                         val packageInfo =
                             packageManager.getPackageInfo(message, PackageManager.GET_META_DATA)
                         val label =
                             packageManager.getApplicationLabel(packageInfo.applicationInfo)
                         data.comm =label.toString()
                     }
                    }
                    data.appPackage = message
                    data.doEvent = EventLog.APPINSTALLEVENT
                    viewModel.eventLog(data)
                    updateAppInstallInfo()

                } catch (e: Exception) {

                }
            }

            Const.APPUNINSTALL -> {
                val message = uiEvent.message
                updateAppRv()
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                try {
                    //从存储集合中获得名字
                    getAppStoreList()
                    val filter = appStroeList.filter { it.appPackage == message }
                    val label =if (filter.isNotEmpty()){
                        filter[0].appName
                    }else{
                        ""
                    }
                    data.comm =label.toString()
                }catch (e:Exception){

                }
                data.appPackage = message
                data.doEvent = EventLog.APPUNINSTALLEVENT
                viewModel.eventLog(data)
            }

            Const.SDINSTALL -> {
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = EventLog.SDEMOUNTEDVENTSTRING
                data.doEvent = EventLog.SDEMOUNTEDVENT
                viewModel.eventLog(data)
            }

            Const.SDUNINSTALL -> {
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = EventLog.SDEJECTEVENTSTRING
                data.doEvent = EventLog.SDEJECTEVENT
                viewModel.eventLog(data)
            }

            Const.SIMINSTALL -> {
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = EventLog.SIMEVENTSTRING
                data.doEvent = EventLog.SIMEVENT
                viewModel.eventLog(data)
            }

            Const.BLUETOOTHOPEN -> {
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = EventLog.BLUETOOHEVENTSTRING
                data.doEvent = EventLog.BLUETOOHEVENT
                viewModel.eventLog(data)
            }

            Const.USB_CONNECTED -> {
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = EventLog.USBCONNECTEVENTSTRING
                data.doEvent = EventLog.USBCONNECTEVENT
                viewModel.eventLog(data)
            }

            Const.USB_NOCONNECTED -> {
                val data = LogdOperateBean()
                ManageApplication.getDeviceInfo()?.let {
                    data.sn = it
                }
                data.comm = EventLog.USBDISCONNECTEVENTSTRING
                data.doEvent = EventLog.USBDISCONNECTEVENT
                viewModel.eventLog(data)
            }

            Const.ACCOUNTLOGINOUT -> {
                loginOut()
            }

            Const.CODE3002.toString() -> {
                //执行这些操作优先跳回本页面，不然livedata会不刷新
                val deviceInfo = ManageApplication.getDeviceInfo()
                val sn = deviceInfo ?: ""
                viewModel.postExitLocked(sn)
                startIntentActivity(MainActivity().javaClass)
            }

            Const.CODE3006.toString() -> {
                //执行这些操作优先跳回本页面，不然livedata会不刷新
                val deviceInfo = ManageApplication.getDeviceInfo()
                val sn = deviceInfo ?: ""
                viewModel.postExitReseted(sn)
                startIntentActivity(MainActivity().javaClass)
            }
            Const.INSTALL_FORCEAPP->{
                ManageApplication.installPackage(uiEvent.message)
            }

            Const.STARTSOCKET -> {
                AppSocket.startSocket(this)
            }

            Const.ACTION_SCREEN_ON->{
                StrategyUtils.getSchoolDeviceSetBean(this)?.let {
                    startTimeTask(it,true)
                }
            }
            Const.ACTION_SCREEN_OFF->{
                //取消定时任务
                if (timer != null) {
                    timer?.cancel()
                    timer = null
                }
                LogShow("关闭任务")
            }
            Const.ACCOUNTLOGINOUTSUCESS->{
                loginOutSucess()
            }
            Const.STARTLOCATION->{
                getLocation()
            }
        }
    }

    private fun getAppStoreList(){
        try {
            if (appStroeList.size==0){
                val type = object : TypeToken<List<AppModel>>() {}.type
                val appModelList = spUtils.getFromJsonType(
                    Const.APPSTOREDATAKEY,
                    ArrayList<AppModel>().javaClass,
                    type
                ) as ArrayList<AppModel>
                appStroeList.addAll(appModelList)
            }
        }catch (e:Exception){

        }
    }

    private fun postLogPush(pushType: Int) {
        //执行这些操作优先跳回本页面，不然livedata会不刷新
        val pushBean = LogPushBean()
        pushBean.pushType = pushType
        ManageApplication.getDeviceInfo()?.let {
            pushBean.sn =it
        }
        viewModel.postLogPushAdd(pushBean)
        if (pushBean.pushType!=4){
            //更新策略不调回activity因为可能在其他应用中。
            startIntentActivity(MainActivity().javaClass)
        }
    }

    private fun updateAppRv() {
        try {
            //获得预装应用和商店应用，商店应用(隐藏图标的不显示)和预装重叠直接显示，其余预装直接隐藏
            var schoolDeviceSetBean: SchoolDeviceSetBean? = null
            schoolDeviceSetBean = StrategyUtils.getSchoolDeviceSetBean(this)
            val storeList = arrayListOf<String>()
            val storeRemoveList= arrayListOf<String>()
            //获得已安装app
            var appList = AppUtils.GetAppList(this)
            try {
                val type = object : TypeToken<List<AppModel>>() {}.type
                val appModelList = spUtils.getFromJsonType(
                    Const.APPSTOREDATAKEY,
                    ArrayList<AppModel>().javaClass,
                    type
                ) as ArrayList<AppModel>
                if (appModelList != null) {
                    appModelList.filter { it.showico==1}.forEach {
                        storeList.add(it.appPackage)
                    }
                    appModelList.filter { it.showico==0}.forEach {
                        storeRemoveList.add(it.appPackage)
                    }
                }
                appList.forEach {app->
                    appModelList.filter { it.appPackage==app.packageName }.forEach {
                        app.name=it.appName
                    }
                }
            } catch (e: Exception) {
                LogShow("商店应用为空"+e.toString())
            }
            dataList.clear()

            //获得预装应用直接隐藏
            val removeList = arrayListOf<AppInfo>()
            try {
                //获得预装应用的包名
                val currentList =
                    currentSpUtils.getFromJson(
                        Const.FIRSTAPPLIST,
                        ArrayList<String>().javaClass
                    ) as ArrayList<String>
                currentList.forEach { pkg ->
                    //获得预装，在学校控制和应用商店显示以外的app加入移除集合
                    if (!Const.schoolSetAppList.contains(pkg) && !storeList.contains(pkg)) {
                        appList.filter { it.packageName == pkg }.forEach {
                            removeList.add(it)
                        }
                    }
                }
            } catch (e: Exception) {

            }
            //如果包含应用商店也移除，因为会在自定义app中添加
            appList.filter { it.packageName == Const.STOREAPPPKG }.forEach {
                removeList.add(it)
            }
            //移除应用列表隐藏的应用
            storeRemoveList.forEach {pkg->
                appList.removeIf { it.packageName==pkg }
            }
            //移除学校控制之外预装应用
            appList.removeAll(removeList)

            appList.addAll(CustomAppUtils().getCustomAppList(this))
            //获得学校设置，设置应用显示（部分回合预装重合，由学校设置判断是否显示）
            if (schoolDeviceSetBean != null) {
                appList = StrategyUtils.setSchoolSetDevice(schoolDeviceSetBean, appList)
            }
            dataList.addAll(appList)
            if (adapter == null) {
                adapter = AppAdapter(this, dataList)
                adapter?.changePwdListener = getChangeCodeListener()
                mBinding.rv.adapter = adapter
            }
            adapter?.let {
                it.notifyDataSetChanged()
            }
        } catch (e: Exception) {

        }
    }
     //在网络无连接时显示数据
    private fun updateNetErrorAppRv(){
        if (!NetworkUtils.isAvailable(this)&&mBinding.rv.visibility==View.INVISIBLE){
            //未联网时，默认只显示更新策略图标
            dataList.clear()
            dataList.add(CustomAppUtils().getCusomAppBean(
                getString(R.string.updatestrategy),
                Const.UPDATESTRATEGYPKGNAME,
                AppCompatResources.getDrawable(this,R.drawable.icon_updatestrategy)!!
            ))
            mBinding.rv.visibility=View.VISIBLE
            if (adapter == null) {
                adapter = AppAdapter(this, dataList)
                adapter?.changePwdListener = getChangeCodeListener()
                mBinding.rv.adapter = adapter
            }
            adapter?.let {
                it.notifyDataSetChanged()
            }
        }
    }

    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 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 registerNetConnectReceiver(){
        netConnectReceiver = NetConnectReceiver()
        registerReceiver(netConnectReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
    }

    /**
     * 熄屏注册监听
     */
    private fun registerScreenReceiver() {
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_SCREEN_ON)
        filter.addAction(Intent.ACTION_SCREEN_OFF)
        mScreenReceiver = ScreenReceiver()
        registerReceiver(mScreenReceiver, filter)
    }

    private fun showEditDialog() {
        if (accountDialog==null){
            accountDialog = 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 {
                            val code = editText.text
                            if ((!code.isNullOrBlank()) && code.length >= 6 && code.length <= 16) {
                                dialog.dismiss()
                                try {
                                    val userBean = spUtils.getFromJson(
                                        Const.USERINFO, UserBean().javaClass
                                    ) as UserBean
                                    viewModel.loginOut(userBean.userid.toString(), code.toString())
                                } catch (e: Exception) {

                                }
                            }
                        }
                        cancelTv.setOnClickListener {
                            dialog.dismiss()
                        }
                    }
                }).setCancelable(false).setMaskColor(Color.parseColor("#66000000"))
                .setAlign(CustomDialog.ALIGN.CENTER).show()
        }else{
            accountDialog?.show()
        }
    }

    private fun showNoticeDialog(msg: String) {
        CustomDialog.build()
            .setCustomView(object : OnBindView<CustomDialog>(R.layout.layout_notice_dialog) {
                override fun onBind(dialog: CustomDialog, v: View) {
                    val closeBtn = v.findViewById<Button>(R.id.dialog_close_btn)
                    val titleTv = v.findViewById<TextView>(R.id.dialog_title_tv)
                    val contentTv = v.findViewById<TextView>(R.id.dialog_content_tv)
                    try {
                        val msgBean = GsonUtils.parseJsonWithGson(
                            msg, SocketMsgBean().javaClass
                        ) as SocketMsgBean
                        titleTv.text = msgBean.title
                        contentTv.text = msgBean.content
                    } catch (e: Exception) {
                        LogShow("解析失败" + e.toString())
                    }
                    closeBtn.setOnClickListener {
                        dialog.dismiss()
                    }
                }
            }).setCancelable(false).setMaskColor(Color.parseColor("#66000000"))
            .setAlign(CustomDialog.ALIGN.CENTER).show()
    }

    private fun loginOut(hasUser: Boolean = true) {
        //没有用户信息时，判断为初次调用，直接跳转登录页面
        if (hasUser) {
            //调用接口传递退出事件，成功则退出登录
            val data = LogdOperateBean()
            ManageApplication.getDeviceInfo()?.let {
                data.sn = it
            }
            data.comm =  EventLog.ACCOUNTQUITEVENTSTRING
            data.doEvent = EventLog.ACCOUNTQUITEVENT
            viewModel.eventLog(data)
        } else {
            loginOutSucess()
        }
    }

    private fun loginOutSucess() {
        spUtils.setParam(Const.DISABLEPAD,false)
        WorkManager.getInstance(this).cancelAllWork()
        deleteSharedPreferences(SharedPreferencesUtils.SP_FILE_NAME)
        Const.USERID = null
        Const.USERNAME = ""
        AppSocket.onDestroy()
        startIntentActivity(LoginActivity().javaClass)
        finish()
    }


    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer?.cancel()
            timer = null
        }
        locationClient?.stop()
        AppSocket.onDestroy()
        DownLoadUtils.removeCallback(this)
        mMyInstallReceiver?.let {
            unregisterReceiver(it)
        }
        netConnectReceiver?.let {
            unregisterReceiver(it)
        }
        mScreenReceiver?.let {
            unregisterReceiver(it)
        }
        LogShow("MainActivity被销毁")
    }


    private fun startWorkManager() {
        WorkManager.getInstance(this).cancelAllWork()
        // 周期性任务时间最少15分钟 所以除以实际周期的时间  看需要加入几个任务
        val taskList = arrayListOf(0, 5, 10)
        for (taskNo in taskList) {
            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)
        }
    }

    override fun onStart(downItem: DownloadItem) {

    }

    override fun onSuccess(downItem: DownloadItem) {
       /* ManageApplication.installPackage(downItem.savepath)*/
        InstallUtils.addInstall(downItem.savepath,downItem.pkgName,downItem.appName)
    }

    override fun onFailure(downItem: DownloadItem, errMsg: String) {

    }

    override fun onLoading(downItem: DownloadItem) {

    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        return if (canClickFlag||!NetworkUtils.isAvailable(this)){
            super.dispatchTouchEvent(ev)
        }else{
             true
        }
    }
}