package com.zj365.mime.act

import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.provider.Settings
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.xty.base.act.BaseVmAct
import com.xty.base.dialog.CustomDialog
import com.xty.base.dialog.SmsSignDialog
import com.xty.common.bracelet.YCBBlueConnectHelper
import com.xty.common.bracelet.YCBManager
import com.xty.common.bracelet.YCBOrder
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.util.CommonToastUtils
import com.zj365.mime.R
import com.zj365.mime.databinding.ActDeviceSettingBinding
import com.zj365.mime.vm.DeviceSettingVm
import com.zj365.mime.weight.*
import kotlinx.coroutines.launch

/**
 * 设备设置
 */
@Route(path = ARouterUrl.DEVICE_SETTING)
class DeviceSettingAct : BaseVmAct<DeviceSettingVm>() {

    val binding by lazy { ActDeviceSettingBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root

    //左右手设置
    val dialogGesture by lazy {
        GestureDialog(this) { it, str ->
            YCBManager.settingHandWear(it) { it1 ->
                if (it1) mainScope.launch {
                    binding.mVersion.text = str
                    MMkvHelper.put(Const.WHATCH_HAND_SETTING, it)
                }
            }
        }
    }
    //亮度设置
    val light by lazy {
        LightDialog(this) { it, str ->
            YCBManager.settingDisplayBrightness(it) { it1 ->
                if (it1)
                    mainScope.launch {
                        binding.mTvLight.text = str
                        MMkvHelper.put(Const.WHATCH_SCREEN_LIGHT_SETTING, it)
                    }
            }
        }
    }
    //恢复出厂设置
    val factoryDialog by lazy {
        FactorySettingDialog(this, getString(R.string.factory_setting_tip)) {
            YCBManager.settingRestoreFactory() {
                MMkvHelper.clearWhatchInfo()
                setData()//刷新数据
            }
        }
    }
    //主题设置
    val themeDialog by lazy {
        ThemeSelectDialog(this) {
            YCBManager.settingMainTheme(it) { it1 ->
                if (it1) mainScope.launch {
                    binding.mTheme.text = "主题${it + 1}"
                    MMkvHelper.put(Const.WHATCH_THEME_SETTING, it)
                }
            }
        }
    }
    //预警短信设置
    val smsDialog by lazy {
        CustomDialog(this, getString(R.string.dialog_title), getString(R.string.dialog_sms_content), {
            dialog.show()
        }){
            binding.mSmsSwitchBtn.isChecked = !binding.mSmsSwitchBtn.isChecked
        }
    }
    //签名
    val dialog by lazy {
        SmsSignDialog(this, {
            signDialog.show()
        }){
            binding.mSmsSwitchBtn.isChecked = !binding.mSmsSwitchBtn.isChecked
        }
    }
    val signDialog by lazy {
        SignDialog1(this, {
            LogUtils.d(it)
            smsSetting(it, if (binding.mSmsSwitchBtn.isChecked) 1 else 0)
        }){
            binding.mSmsSwitchBtn.isChecked = !binding.mSmsSwitchBtn.isChecked
        }
    }

    override fun initData() {
        super.initData()
        isDarkBar = true
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)

        setData()

        binding.title.mIvBack.setOnClickListener {
            finish()
        }
        binding.title.mTvTitle.text = getString(R.string.device_set)

        binding.mTvDont.setOnClickListener {
            RouteManager.goAct(ARouterUrl.DONT_DISTURB)

        }

        binding.mRelLocation.setOnClickListener {
            dialogGesture.showHand(MMkvHelper.getInt(Const.WHATCH_HAND_SETTING))
        }
        binding.switchButton.setOnCheckedChangeListener { view, isChecked ->
            var intType = if (isChecked) YCBOrder.SCREEN_ON else YCBOrder.SCREEN_OFF
            //保存抬腕亮屏状态
            YCBManager.settingRaiseScreen(intType) {
                mainScope.launch {
                    if (it) MMkvHelper.put(Const.WHATCH_WRIST_SCREEN_SETTING, isChecked)
                    //设置抬腕亮屏失败，重置check状态
                    else binding.switchButton.isChecked = !isChecked
                }
            }

        }
        binding.mTheme.setOnClickListener {
            if (MMkvHelper.getInt(Const.WHATCH_THEME_SIZE) > 0) {
                themeDialog.showThemeDialog(
                    MMkvHelper.getInt(Const.WHATCH_THEME_SIZE),
                    MMkvHelper.getInt(Const.WHATCH_THEME_SETTING)
                )
            } else {
                //重新查询主题信息
                getWhatchThemInfo()
                CommonToastUtils.showToast("手表连接异常，请确认连接好以后再重试！")
            }
        }

        binding.mTvMsg.setOnClickListener {
            if (YCBBlueConnectHelper.getBlueStatus()) {
                msgReceive()
            }

        }


        binding.mLight.setOnClickListener { light.show() }
        binding.mTvOff.setOnClickListener { factoryDialog.show() }
        mViewModel.getSmsList()
    }

    private fun setData() {

        //获取手表主题信息并设置
        getWhatchThemInfo()

        //抬腕亮屏状态设置 默认未开启
        binding.switchButton.isChecked =
            MMkvHelper.getBoolean(Const.WHATCH_WRIST_SCREEN_SETTING, false)

        //左右手设置，默认为左手
        binding.mVersion.text = getHandlerText()

        //屏幕亮度设置,默认为中
        binding.mTvLight.text = getScreenLightText()
    }

    private fun getWhatchThemInfo() {
        //获取手表主题信息并设置
        YCBManager.getThemeInfo { ok, allTheme, current ->
            if (ok) {
                MMkvHelper.put(Const.WHATCH_THEME_SIZE, allTheme)
                MMkvHelper.put(Const.WHATCH_THEME_SETTING, current)
                var rightDrawable = ContextCompat.getDrawable(this, R.mipmap.ic_next)
                //必须通过setBounds方法设置drawable资源边界信息，否则setCompoundDrawables方法无效
                rightDrawable!!.setBounds(
                    0,
                    0,
                    rightDrawable.minimumWidth,
                    rightDrawable.minimumHeight
                )
                binding.mTheme.text = "主题${current + 1}"
                binding.mTheme.setCompoundDrawables(
                    null,
                    null,
                    rightDrawable,
                    null
                )

            } else {
                binding.mTheme.setCompoundDrawables(null, null, null, null)
                binding.mTheme.text = ""
            }
        }
    }

    private fun getScreenLightText(): String {
        return if (MMkvHelper.getInt(Const.WHATCH_SCREEN_LIGHT_SETTING) == YCBOrder.LIGHT_1)
            "低"
        else if (MMkvHelper.getInt(Const.WHATCH_SCREEN_LIGHT_SETTING) == YCBOrder.LIGHT_3)
            "高"
        else
            "中"
    }

    private fun getHandlerText(): String {
        return if (MMkvHelper.getInt(Const.WHATCH_HAND_SETTING) == YCBOrder.RIGHT_HAND)
            "右手"
        else
            "左手"
    }

    /**
     * 消息接收开启
     */
    private fun msgReceive11() {

        var service = RouteManager.getAny(ARouterUrl.NOTIFICATION_LISTENER) as Service
        val string = Settings.Secure.getString(contentResolver, "enabled_notification_listeners")
        if (string != null && !string.contains(service.javaClass.name)) {
            startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))
        } else {
            RouteManager.goAct(ARouterUrl.MSG_RECEIVE)
        }

    }


    private fun notificationListenerEnable(): Boolean {
        var enable = false
        val packageName = packageName
        val flat = Settings.Secure.getString(contentResolver, "enabled_notification_listeners")
        if (flat != null) {
            enable = true
            if (!flat.contains(packageName)) {
                startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))
            } else {
                RouteManager.goAct(ARouterUrl.MSG_RECEIVE)
            }
        }
        return enable
    }


    private fun msgReceive() {
        if (notificationListenerEnable()) {
            return
        }
        try {
            val intent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        } catch (e: Exception) {
            try {
                val intent = Intent()
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                val cn = ComponentName(
                    "com.android.settings",
                    "com.android.settings.Settings\$NotificationAccessSettingsActivity"
                )
                intent.component = cn
                intent.putExtra(":settings:show_fragment", "NotificationAccessSettings")
                startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace();
            }
        }
    }

    private fun smsSetting(path: String?, state: Int){
        mViewModel.smsSetting(path, 1, state)
    }

    override fun liveObserver() {
        mViewModel.smsListLive.observe(this){
            LogUtils.d("${it.data}")
            binding.mSmsSwitchBtn.isChecked = it.data?.state == 1
            binding.mSmsSwitchBtn.apply {//预警消息开关按钮
                setOnCheckedChangeListener { _, isChecked ->
                    if (!isChecked){
                        smsDialog.show()
                    }else{
                        smsSetting(null, if (binding.mSmsSwitchBtn.isChecked) 1 else 0)
                    }
                }
            }

        }

        mViewModel.smsSettingLive.observe(this){

        }
    }
}