package com.module.backstage.activity.setting

import android.annotation.SuppressLint
import android.app.XzjhSystemManager
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.VISIBLE
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.core.view.get
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hboxs.serialport.plc.DialogClickListener
import com.hboxs.serialport.sbc.SBCHeartbeat
import com.hboxs.serialport.sbc.VBoxMessage
import com.hjq.http.EasyHttp
import com.hjq.http.listener.OnDownloadListener
import com.hjq.http.model.HttpMethod
import com.module.backstage.R
import com.module.backstage.databinding.BackstageActivitySettingBinding
import com.module.backstage.dialog.ConnectionServerDialog
import com.module.backstage.dialog.DevOnOffDialog
import com.module.backstage.dialog.UpdateAppDialog
import com.module.backstage.model.ApkInfoBean
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.base.utils.RegisterEventBus
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.bean.SettingTypeBean
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.constant.MqName
import com.quyunshuo.androidbaseframemvvm.common.constant.RouteUrl
import com.quyunshuo.androidbaseframemvvm.common.constant.SavaAddress
import com.quyunshuo.androidbaseframemvvm.common.constant.event.ApiMessageEvent
import com.quyunshuo.androidbaseframemvvm.common.enums.ConnectStateEnum
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseActivity
import com.quyunshuo.androidbaseframemvvm.base.utils.LanguageUtil
import com.quyunshuo.androidbaseframemvvm.common.util.LongClickUtils
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File


/**
 * 首页
 */
@Route(path = RouteUrl.Home.SettingActivity)
@AndroidEntryPoint
@RegisterEventBus
class SettingActivity : BaseActivity<BackstageActivitySettingBinding, SettingViewModel>(),
    View.OnClickListener {
    private val TAG = "SettingActivity"
    private var backPressedTime: Long = 0
    var devOnOffDialog: DevOnOffDialog? = null

    var connectionServerDialog: ConnectionServerDialog? = null
    var updateAppDialog: UpdateAppDialog? = null
    var apkInfoBean: ApkInfoBean? = null//更新信息
    private var TEN_MINUTES =
        SpUtils.getString(MMKVName.AUTO_RETURN_HOME, "10")?.toLong()!! * 60 * 1000L// 10 分钟
    var delayMillis = TEN_MINUTES // 倒计时


    /**
     * 通过 viewModels() + Hilt 获取 ViewModel 实例
     */
    override val mViewModel by viewModels<SettingViewModel>()
    override fun createVB() = BackstageActivitySettingBinding.inflate(layoutInflater)

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("ResourceType")
    override fun BackstageActivitySettingBinding.initView() {
        LanguageUtil.setLanguage();
        // 设置布局延伸到状态栏和导航栏下方
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)

        /**设置MenuItem默认选中项 */
        showItem()
        bnvMainNavigationbar.setNavigationItemSelectedListener {
            val findNavController = findNavController(homeFragmentcontainerview.id)
            findNavController.navigate(it.itemId)
            true

        }

        bnvMainNavigationbar.setItemIconTintList(null)
        homeReturnToUpperLevel.setOnClickListener(this@SettingActivity)
        ivDevOnAndOff.setOnClickListener(this@SettingActivity)
        btnConnectionServer.setOnClickListener(this@SettingActivity)
        btnUpdateApp.setOnClickListener(this@SettingActivity)
        //设置连接状态
        connectState(
            SpUtils.getString(
                MMKVName.CONNECT_STATE, ConnectStateEnum.DISCONNECTED.name
            )!!
        )
        Log.d(
            TAG, "connectState initView: " + SpUtils.getString(
                MMKVName.CONNECT_STATE, ConnectStateEnum.DISCONNECTED.name
            )!!
        )
        //退出App
        LongClickUtils.setLongClick(
            Handler(),
            tvSystemSet,
            3000,
            object : View.OnLongClickListener {
                override fun onLongClick(v: View?): Boolean {
                    finish()
                    return true
                }

            })
        mBinding.tvSoftwareVersion.text =
            "Plcc:" + SBCHeartbeat.softwareVersion + "_" + SBCHeartbeat.softDate
        mBinding.tvCrateVersion.text = "Chassis:" + SBCHeartbeat.crateVersion
        mBinding.tvDevDogtag.text =
            "Nameplate:" + SBCHeartbeat.devDogtag + "_" + SBCHeartbeat.productionDate
        mBinding.tvAppVersion.text = "App：" + mViewModel.getVersionName()
        mBinding.customized.text = "FlowerVersion：" + SBCHeartbeat.customizedVersion
        mBinding.deviceNo.text = "Device:" + XLogUtil.getDeviceId()
            .substring(XLogUtil.getDeviceId().length - 6, XLogUtil.getDeviceId().length)
        //倒计时返回主页
        lifecycleScope.launch {
            while (true) {
                delayMillis = delayMillis - 1000
                if (delayMillis == 0L) {
                    ToastUtil.switchToastStyleToSuccess("返回主页")
                    back()
                    break
                }
                delay(1000)
                Log.d(TAG, "initView: " + delayMillis)
            }

        }
    }

    override fun initObserve() {
        observeLiveData(mViewModel.data, ::processData)
        lifecycle.addObserver(mViewModel.threadSettingParam)
        observeLiveData(mViewModel.isM3Success, ::closeDialog)
        observeLiveData(mViewModel.connectState, ::connectState)
        observeLiveData(mViewModel.apkInfo, ::updateApp)
        observeLiveData(mViewModel.powerOncomplete, ::completeStartupOrShutdown)
    }

    private fun updateApp(apkInfoBean: ApkInfoBean) {
        this.apkInfoBean = apkInfoBean
        mBinding.tvUpdateHint.visibility = View.VISIBLE
        Log.d(TAG, "updateApp: $apkInfoBean")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(message: ApiMessageEvent) {
        when (message.name) {
            MqName.IS_SLEEP -> {
                Log.d(TAG, "我收到了要开关机:" + message.data)
                if (message.data == "0") {
                    Log.d(TAG, "11event: IS_SLEEP:" + message.data)
                    //关掉休眠
                    SpUtils.putBoolean(MMKVName.SLEEP, false)
                    finish()
                    ARouter.getInstance().build(RouteUrl.Main.MainActivity).navigation()
                    /*   val navController = findNavController(mBinding.homeFragmentcontainerview.id)
                       navController.navigate(R.id.home_action_home_sleepfragment_to_home_buyfragment)*/

                } else {
                    Log.d(TAG, "12event: IS_SLEEP:" + message.data)
                    SpUtils.putBoolean(MMKVName.SLEEP, true)
                    finish()
                    ARouter.getInstance().build(RouteUrl.Main.MainActivity).navigation()
                    //开启休眠
                    /*    val navController = findNavController(mBinding.homeFragmentcontainerview.id)
                        navController.navigate(R.id.home_sleepfragment)*/
                }
            }


            MqName.BLOCK -> {
                if (message.data == "0") {
                    Log.d(TAG, "关掉锁机P:" + message.data)
                    //关掉锁机
                    SpUtils.putBoolean(MMKVName.BLOCK, false)
                    ARouter.getInstance().build(RouteUrl.Main.MainActivity).navigation()
                    finish()
                } else {
                    Log.d(TAG, "开启锁机:" + message.data)
                    SpUtils.putBoolean(MMKVName.BLOCK, true)
                    ARouter.getInstance().build(RouteUrl.Main.MainActivity).navigation()
                    //开启锁机
                    finish()
                }
            }

            else -> {}
        }
    }

    @SuppressLint("SetTextI18n")
    private fun connectState(state: String) {
        Log.d(TAG, "connectState: $state")
        when (state) {
            ConnectStateEnum.CONNECTING.name -> {
                mBinding.btnConnectionServer.text =
                    UiUtil.getStringRes(R.string.base_backstage_connecting)
                mBinding.btnConnectionServer.isEnabled = false
            }

            ConnectStateEnum.CONNECTED.name -> {
                mBinding.btnConnectionServer.text =
                    getString(R.string.base_backstage_connected) + SpUtils.getString(
                        MMKVName.MANAGER_ID,
                        ""
                    )
                mBinding.btnConnectionServer.isEnabled = false
            }

            ConnectStateEnum.DISCONNECTED.name -> {
                mBinding.btnConnectionServer.isEnabled = true
            }

            ConnectStateEnum.DEFAULT.name -> {
                mBinding.btnConnectionServer.text =
                    UiUtil.getStringRes(R.string.base_backstage_connection_server)
                mBinding.btnConnectionServer.isEnabled = true
            }

            else -> {

            }
        }
    }

    private fun closeDialog(flag: Boolean) {
        if (flag) {
            //关掉对话框
            devOnOffDialog?.dismiss()
        }
    }

    private fun processData(data: String) {
    }

    override fun initRequestData() {
        // 模拟获取数据
        mViewModel.getData()
        mViewModel.getApkinfo()
    }

    override fun onBackPressed() {
        // 获取当前时间戳
        val currentTime = System.currentTimeMillis()
        // 判断与上一次点击返回键的时间间隔是否小于1秒
        if (currentTime - backPressedTime < 1000) {
            super.onBackPressed() // 执行默认的返回键操作（退出Activity）
        } else {
            Toast.makeText(
                this,
                UiUtil.getStringRes(R.string.base_backstage_quit_app),
                Toast.LENGTH_SHORT
            ).show()
            backPressedTime = currentTime // 更新上一次点击返回键的时间戳
        }
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.iv_dev_on_and_off -> {
                showOnOffDialog()
            }

            R.id.home_return_to_upper_level -> {
                back()
            }

            R.id.btn_connection_server -> {
                showConnectionServer()
            }

            R.id.btn_update_app -> {
                if (mBinding.tvUpdateHint.visibility != VISIBLE) {
                    ToastUtil.switchToastStyleToInfo(UiUtil.getStringRes(R.string.base_backstage_latest_version))
                    return
                }
                showUpdateApp()
            }

            else -> {}
        }
    }

    private fun showUpdateApp() {
        if (updateAppDialog == null) {
            updateAppDialog = UpdateAppDialog(this@SettingActivity)
            updateAppDialog?.setListener(object : DialogClickListener {
                override fun onClickListener(type: Int, text: String?) {
                    when (type) {
                        updateAppDialog?.type1 -> {
                            updateApk()

                            Log.d(TAG, "onClickListener: ")
                        }

                        else -> {}
                    }
                }

            })
        }
        updateAppDialog?.setContent(this.apkInfoBean)
        updateAppDialog?.show()

    }

    private fun showConnectionServer() {
        if (connectionServerDialog == null) {
            connectionServerDialog = ConnectionServerDialog(this@SettingActivity)
            connectionServerDialog?.setListener(object : DialogClickListener {
                override fun onClickListener(type: Int, text: String?) {
                    when (type) {
                        connectionServerDialog?.type1 -> {
                            // 连接服务器
                            mViewModel.initDev(text)
                            Heartbeat.managerId = text

                            connectionServerDialog?.dismiss()
                        }

                        else -> {}
                    }
                }

            })
        }
        connectionServerDialog?.show()

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(messageEvent: VBoxMessage) {

        mViewModel.disposeData(messageEvent)
    }

    /* @Subscribe(threadMode = ThreadMode.MAIN)
     fun event(messageEvent: Message) {
         Log.d(TAG, "messageEvent event: " + messageEvent.type)
         when (messageEvent.type) {
             Message.Type.ack -> {
                 mViewModel.ack(messageEvent)
             }

             Message.Type.response -> {
                 mViewModel.response(messageEvent)
             }

             Message.Type.connected -> {}
             Message.Type.disconnected -> {}
             Message.Type.sendError -> {}
             Message.Type.nak -> {}
         }
     }*/

    private fun showOnOffDialog() {
        if (devOnOffDialog == null) {
            devOnOffDialog = DevOnOffDialog(this@SettingActivity)
        }
        devOnOffDialog?.setListener(object : DialogClickListener {
            override fun onClickListener(type: Int, text: String?) {
                when (type) {
                    devOnOffDialog?.type1 -> {
                        Log.d(TAG, "onClickListener: ")

                        mViewModel.threadSettingParam.startSetM3("01")
                        devOnOffDialog?.dismiss()
                    }

                    devOnOffDialog?.type2 -> {

                        mViewModel.threadSettingParam.startSetM3("00")
                        devOnOffDialog?.dismiss()

                    }

                    else -> {}
                }
            }

        })

        devOnOffDialog?.show()
    }

    private fun back() {
        ARouter.getInstance().build(RouteUrl.Main.MainActivity).navigation()
        finish()
    }

    fun updateApk() {
        // 如果是放到外部存储的应用专属目录则不需要适配分区存储特性
//        val file = File(getExternalFilesDir("apk" + "/"), "mht.apk")
        val file = File(SavaAddress.apkAddress)
        Log.d(TAG, "onDownloadStart: " + file)
        val url = apkInfoBean?.downloadUrl
        EasyHttp.download(this).method(HttpMethod.GET)
            .file(file)
            .url(url).listener(object : OnDownloadListener {
                override fun onDownloadStart(file: File) {
                    Log.d(TAG, "onDownloadStart: 开始下载" + file)
                }

                override fun onDownloadProgressChange(file: File, progress: Int) {
                    Log.d(TAG, "onDownloadStart: 下载进度：" + progress)
                    updateAppDialog?.setUpdateProgress(progress)
                }

                override fun onDownloadSuccess(file: File) {
                    Log.d(TAG, "onDownloadEnd: 下载成功")
                    //下载成功安装
//                    val intent = Intent(Intent.ACTION_VIEW)
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    intent.setDataAndType(
//                        Uri.fromFile(file), "application/vnd.android.package-archive"
//                    )
//                    startActivity(intent)
                    val mManager: XzjhSystemManager =
                        getSystemService("xzjh_server") as XzjhSystemManager
                    mManager.xzjhSilentInstallApkV2(
                        SavaAddress.apkAddress,
                        true
                    )

                    Log.d(
                        TAG,
                        "onDownloadStart 安装查找目录: " + Environment.getExternalStorageDirectory().path
                    )
                    updateAppDialog?.dismiss()
                }

                override fun onDownloadFail(file: File?, e: Throwable?) {
                    Log.d(TAG, "onDownloadFail: 下载失败")
                }
            }).start()
    }


    /**
     * 哪些item要显示
     */
    fun showItem() {
        val menu = mBinding.bnvMainNavigationbar.menu
        val loginName = intent.extras?.getString("loginName")
        loginName?.let { SpUtils.putString(MMKVName.LOGIN_USER, it) }
        Log.d(TAG, "loginName: $loginName")
        if (loginName != null && loginName == "Staff") {
            val productStr = SpUtils.getString(MMKVName.SETTING_TYPE, "")
            if (productStr != "") {
                val arrayListState: HashMap<Int, SettingTypeBean> = Gson().fromJson(
                    productStr,
                    object : TypeToken<HashMap<Int, SettingTypeBean>?>() {}.type
                )
                for (i in 0 until menu.size()) {
                    val itemMenu = menu[i]
                    val settingTypeBean = arrayListState[i]
                    if (settingTypeBean == null || !settingTypeBean.isSelected) itemMenu.setVisible(
                        false
                    )
                    Log.d(TAG, "initView: $settingTypeBean")
                }
            }
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        //这个触摸，是不管在任何的fragment都可以使用的。
        when (ev?.action) {
            MotionEvent.ACTION_UP -> {
                delayMillis = TEN_MINUTES
            }

            else -> {}
        }
        return super.dispatchTouchEvent(ev)
    }


    private fun completeStartupOrShutdown(dismiss: Boolean) {
        Log.d("backinfo", "我收到了要关闭开关机弹框")

    }

}