package com.xhly.manageapp.ui.login.activity

import BaseActivity
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.provider.Settings
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import com.kongzue.dialogx.DialogX
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnBindView
import com.tbruyelle.rxpermissions2.RxPermissions
import com.xhkjedu.manageapp.R
import com.xhkjedu.manageapp.databinding.ActivityLoginBinding
import com.xhly.corelib.Const
import com.xhly.corelib.eventbus.UIEvent
import com.xhly.corelib.utils.AppUtils
import com.xhly.corelib.utils.GsonUtils
import com.xhly.corelib.utils.LogShow
import com.xhly.corelib.utils.SystemUtil
import com.xhly.manageapp.ManageApplication
import com.xhly.manageapp.bean.EventLog
import com.xhly.manageapp.bean.login.LoginBean
import com.xhly.manageapp.bean.SocketMsgBean
import com.xhly.manageapp.bean.log.LogPushBean
import com.xhly.manageapp.bean.log.LogdOperateBean
import com.xhly.manageapp.bean.user.UserBean
import com.xhly.manageapp.contentprovider.ZSpProvider
import com.xhly.manageapp.service.websocket.AppSocket
import com.xhly.manageapp.ui.ManageActivity
import com.xhly.manageapp.ui.login.viewmodel.LoginViewModel
import com.xhly.manageapp.ui.main.activity.MainActivity
import com.xhly.manageapp.utils.CurrentAppSharedPreferencesUtils
import com.xhly.manageapp.utils.StrategyUtils
import com.xhly.manageapp.workmanager.TimingWorker
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit

class LoginActivity : BaseActivity<LoginViewModel, ActivityLoginBinding>() {
    //单独创建sharedpreference用来存储初始化的应用
    private val currentSpUtils by lazy { CurrentAppSharedPreferencesUtils.getInstance(this) }
    private var regioncode = ""
    //如果次数大于10则可以打开设置页面
    private var showSettingNum=0
    private var waitDialog:WaitDialog?=null
    override fun getBinding() = ActivityLoginBinding.inflate(layoutInflater)

    override fun initData() {
       viewModel.loginData.observe(this){
           waitDialog?.doDismiss()
           if (it.xhlyLoginSucess){
               loginSucess(it)
           }else{
               it.xhlyLoginMessage?.let {
                   Toast(it)
               }
           }
       }
        viewModel.pwdResultData.observe(this){
            if (it){
                unBindBlock()
            }else{
                Toast(getString(R.string.codeerror))
            }
        }
        viewModel.timeResultData.observe(this){
            ManageApplication.setSysTime(it)
            Toast(getString(R.string.syncsucess))
        }
        viewModel.controlResultData.observe(this){
            //为真则可以进入管理页面
            if (it){
                startIntentActivity(ManageActivity().javaClass)
            }else{
                Toast(getString(R.string.codeerror))
            }
        }
        viewModel.regionCodeData.observe(this){
           if (!it){
               regioncode=""
           }else{
               if (regioncode.isNotBlank()){
                   currentSpUtils.setParam(Const.REGIONCODEKEY,regioncode)
               }
           }
        }
        //自动同时一次时间
        viewModel.postSyncTime()
      /*  val exitControlFlag = currentSpUtils.getParam(Const.EXIT_CONTROL, false) as Boolean
        //如果解除管控为真，则不在执行以下代码
        if (!exitControlFlag){
            //登陆页面不在执行定时任务
            //startWorkManager()
        }*/
    }

    @SuppressLint("CheckResult")
    override fun initView() {
        initFirstUse()
        setSoftInput(mBinding.root)
        mBinding.loginBtn.setOnClickListener {
            val rxPermissions = RxPermissions(this)
            //有无权限都要登录
            val request = rxPermissions.request(Manifest.permission.READ_PHONE_STATE)
            request.subscribe({
                login()
            },{
                login()
            })
        }
        mBinding.codeLoginIv.setOnClickListener {
            showEditDialog()
        }
        mBinding.codeenterCv.setOnClickListener {
            //如果密码一致,则解锁
            val code = mBinding.lockEt.text.toString()
            if (code.isNullOrBlank()){
                return@setOnClickListener
            }
            ManageApplication.getDeviceInfo()?.let {
                viewModel.postPwdDetail(code,it)
            }
        }

        mBinding.loginClayout.setOnClickListener {
            hiddenSoft(mBinding.accountEt)
        }
        mBinding.netsetLlayout.setOnClickListener {
            startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
        }
        mBinding.synctimeLlayout.setOnClickListener {
               viewModel.postSyncTime()
        }
        mBinding.logoIv.setOnClickListener {
            if (showSettingNum>10){
                showSettingNum=0
                showSettingDialog()
            }
        }
        lifecycleScope.launch {
            viewModel.logResultData.collect{
                it?.let {
                    if (it.enableFlag){
                        when(it.pushType){
                            2->{
                                spUtils.setParam(Const.DISABLEPAD, false)
                                useTimeStrategy()
                            }
                            3->{
                                spUtils.setParam(Const.DISABLEPAD, true)
                                useTimeStrategy()
                            }
                            5->{
                                ManageApplication.rebootDevice()
                            }
                            6->{
                                ManageApplication.launchFactoryReset()
                            }
                            7->{
                                currentSpUtils.setParam(Const.EXIT_CONTROL,true)
                                StrategyUtils.releaseControl(this@LoginActivity)
                            }
                        }
                    }
                }
            }
        }
        onBackPressedDispatcher.addCallback {
            //屏蔽返回
        }
    }

    private fun initFirstUse() {
        val firstFlag = currentSpUtils.getParam(Const.FIRSTFLAG, true) as Boolean
        if (firstFlag){
            //如果第一次使用则提交登录事件，并且保存初始app
            val data = LogdOperateBean()
            ManageApplication.getDeviceInfo()?.let {
                data.sn = it
            }
            data.comm = EventLog.FIRSTEVENTSTRING
            data.doEvent = EventLog.FIRSTEVENT
            viewModel.eventLog(data)
            currentSpUtils.setParam(Const.FIRSTFLAG,false)
            val firstAppList = AppUtils.GetAppList(this)
            //保存初始应用，只保留包名，因为drawble数据存储时有问题
            val pkgNameList= arrayListOf<String>()
            firstAppList.forEach {
                pkgNameList.add(it.packageName)
            }
            currentSpUtils.saveJson(Const.FIRSTAPPLIST,pkgNameList)
        }
    }

    private fun login() {
        val account = mBinding.accountEt.text.toString()
        val code = mBinding.codeEt.text.toString()
        LogShow("sn=="+ ManageApplication.getDeviceInfo())
        if (account.isNullOrBlank()) {
            Toast(getString(R.string.accountnoempty))
            return
        }
        if (code.isNullOrBlank()) {
            Toast(getString(R.string.codenoempty))
            return
        }
        val loginBean= LoginBean()
        loginBean.loginname=account
        loginBean.loginpwd=code
        loginBean.device= Build.BRAND
        loginBean.deviceModel=Build.MODEL
        loginBean.romVersion=Build.DISPLAY
        ManageApplication.getDeviceInfo(1)?.let{mac->
            loginBean.deviceMac=mac
        }
        loginBean.regionCode=regioncode
        loginBean.clientVersion=SystemUtil.getAppVersionName(this,packageName)
        ManageApplication.getDeviceInfo()?.let {
            loginBean.sn=it
        }
         waitDialog = WaitDialog.setMessage("正在登陆").show()
        viewModel.login(loginBean)
    }

    private fun loginSucess(userBean: UserBean){
        //登录成功则打开管控
        val exitControlFlag = currentSpUtils.getParam(Const.EXIT_CONTROL, false) as Boolean
        if (exitControlFlag){
            //如果解除了管控，登录成功则重新添加管控
            currentSpUtils.setParam(Const.EXIT_CONTROL,false)
            StrategyUtils.initControlStrategy()
        }
        //提交登录事件
        val data = LogdOperateBean()
        ManageApplication.getDeviceInfo()?.let {
            data.sn = it
        }
        data.doEvent = EventLog.ACCOUNTLOGINEVENT
        data.comm=EventLog.ACCOUNTLOGINEVENTSTRING
        viewModel.eventLog(data)
        Const.USERID=userBean.userid
        Const.USERNAME=userBean.username.toString()
        Const.SCHOOLID=userBean.schoolid
        Const.CLASSID=userBean.classid
        spUtils.saveJson(Const.USERINFO,userBean)
        val parseClassToJson = GsonUtils.parseClassToJson(userBean)
        ZSpProvider.save(this,Const.USERINFO,parseClassToJson)
        AppSocket.onDestroy()
        AppSocket.startSocket(ManageApplication.instance)
        startIntentActivity(MainActivity().javaClass)
        finish()
    }

    private fun unBindBlock() {
        spUtils.setParam(Const.DISABLEPAD, false)
        useTimeStrategy()
        if (mBinding.loginMainLlayout.visibility == View.GONE) {
            Toast(getString(R.string.padtimestoptips))
        }
    }

    override fun onResume() {
        super.onResume()
        useTimeStrategy()
    }

    private fun showEditDialog() {
        CustomDialog
            .build()
            .setCustomView(object : OnBindView<CustomDialog>(R.layout.layout_edit_dialog) {
                override fun onBind(dialog: CustomDialog, v: View) {
                    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 titleTv=v.findViewById<TextView>(R.id.dialog_title_tv)
                    regioncode = currentSpUtils.getParam(Const.REGIONCODEKEY, regioncode) as String
                    editText.setText(regioncode)
                    enterTv.setOnClickListener {
                        dialog.dismiss()
                        val text = editText.text
                        val list= arrayListOf("com.xhly.manageapp")
                        spUtils.saveJson(Const.WHITELISTAPP,list)
                        regioncode = if (text != null && text.isNotEmpty()) {
                            text.toString()
                        } else {
                            ""
                        }
                        if (regioncode.isNotEmpty()){
                            viewModel.postRegionCheckCode(regioncode)
                        }
                    }
                    cancelTv.setOnClickListener {
                        dialog.dismiss()
                    }
                    titleTv.setOnClickListener {
                        showSettingNum++
                    }
                }
            }).setCancelable(false).setMaskColor(Color.parseColor("#66000000"))
            .setAlign(CustomDialog.ALIGN.CENTER).show()
    }

    override fun onUiEvent(uiEvent: UIEvent) {
        super.onUiEvent(uiEvent)
        when (uiEvent.getEvent()) {

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

            Const.CODE2002.toString() -> {
                postLogPush(3)
            }

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


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

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

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

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

    }

    private fun postLogPush(pushType:Int){
        val pushBean=LogPushBean()
        pushBean.pushType=pushType
        pushBean.sn=ManageApplication.getDeviceInfo()?:""
        viewModel.postLogPushAdd(pushBean)
    }

    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()
    }
    //弹出调用设置页面的dialog
    private fun showSettingDialog() {
        CustomDialog.build()
            .setCustomView(object : OnBindView<CustomDialog>(R.layout.layout_edit_dialog) {
                override fun onBind(dialog: CustomDialog, v: View) {
                    val 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.checkcode)
                    enterTv.setOnClickListener {
                        val code = editText.text
                        if ((!code.isNullOrBlank()) && code.length >= 6) {
                            dialog.dismiss()
                            ManageApplication.getDeviceInfo()?.let {sn->
                                viewModel.postExitControl(code.toString(),sn)
                            }
                        }
                    }
                    cancelTv.setOnClickListener {
                        dialog.dismiss()
                    }
                }
            }).setCancelable(false).setMaskColor(Color.parseColor("#66000000"))
            .setAlign(CustomDialog.ALIGN.CENTER).show()
    }

    private fun useTimeStrategy() {
        //当前登录页面不进行锁定
        //获得sputils中的平板锁定策略

 /*       try {
            //如果存储的是锁定则锁定
            val param = spUtils.getParam(Const.DISABLEPAD, false) as Boolean
            if (param) {
                mBinding.loginMainLlayout.visibility = View.GONE
                mBinding.lockLlayout.visibility = View.VISIBLE
            } else {
                mBinding.loginMainLlayout.visibility = View.VISIBLE
                mBinding.lockLlayout.visibility = View.GONE
            }
            mBinding.lockEt.setText("")
        } catch (e: Exception) {
            //默认不锁定
            mBinding.loginMainLlayout.visibility = View.VISIBLE
            mBinding.lockLlayout.visibility = View.GONE
        }*/
    }

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