package com.zj365.mime.act

import android.app.Service
import android.content.Intent
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.tamsiree.rxkit.RxActivityTool
import com.xty.base.act.BaseVmAct
import com.xty.common.Const
import com.xty.common.bracelet.YCBBlueConnectHelper
import com.xty.common.MMkvHelper
import com.xty.common.WxUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.event.MyInfoEvent
import com.xty.common.event.WxLoginEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.work.MyWorkManger
import com.zj365.mime.R
import com.zj365.mime.databinding.ActAccountSafeBinding
import com.zj365.mime.vm.AccountSafeVm
import com.xty.network.model.SettingBean
import com.zj365.mime.weight.FactorySettingDialog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 账号与安全
 */
@Route(path = ARouterUrl.ACCOUNT_SAFE)
class AccountSafeAct : BaseVmAct<AccountSafeVm>() {

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

    private val bindWxDialog by lazy {
        FactorySettingDialog(this, getString(R.string.dialog_bind_wx)) {
            //确认绑定
            WxUtils.signInWx()
        }
    }

    private var destStr = """
        一旦您注销中健三六五健康账号后，您的中健三六五健康APP将会被清除账号信息，请知悉并谨慎操作！
        注销中健三六五健康账号前，请确保您的账号符合以下注销条件：
        1、账号处于安全状态
        您的账号没有被盗、被封等风险（最近15天账号未在其他设备登录）
        2、其他关联用户解绑
        您的账号已经解除对其他中健三六五手表佩戴用户的关注与绑定
        3、中健三六五手表解绑
        您的账号已经解除对中健三六五手表的绑定
        4、账号不可找回
        注销后，账号绑定的信息将被释放，账号无法登录中健三六五健康APP
    """.trimIndent()

    private val destAccount by lazy {
        FactorySettingDialog(this, destStr) {
            //确认解除绑定
            user?.let {
                mViewModel.destAccount(it.id.toString())
            }
        }
    }
    var user: SettingBean.User? = null

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

    override fun liveObserver() {
        mViewModel.allData.observe(this) {
            it.data.user?.let {
                user = it
                binding.mServerTime.text = ""
                binding.mPhone.text = it.phone
                binding.mServerTime.text = it.sPeriodic
                if (it.esignatureDate.isNullOrEmpty()) {
                    binding.mElec.visibility = View.GONE
                }
                if (it.openId.isNullOrEmpty()) {
                    binding.mBindWx.visibility = View.VISIBLE
                    binding.mBindWxView.visibility = View.VISIBLE
                } else {
                    binding.mBindWx.visibility = View.GONE
                    binding.mBindWxView.visibility = View.GONE
                }

            }
        }
        mViewModel.bindWx.observe(this) {
            //微信是否绑定成功
            CommonToastUtils.showToast("微信绑定成功")
            EventBus.getDefault().post(MyInfoEvent()) //更新个人信息
            mViewModel.getAllInfo()
        }
        mViewModel.destLive.observe(this) {
            logoOut()
        }
    }

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


        binding.title.mTvTitle.text = getString(R.string.account_safe)

        binding.title.mIvBack.setOnClickListener {
            finish()
        }
        binding.mTvMyInfo.setOnClickListener {

            user?.let {
                if (it.esignatureDate.isNullOrEmpty()) {
                    bundle.clear()
                    bundle.putSerializable("user", user)
                    RouteManager.goAct(ARouterUrl.MY_INFO, bundle)
                } else {
                    RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE)
                }

            }
        }

        binding.mElec.setOnClickListener {
            bundle.clear()
            user?.let {
                bundle.putString("time", it.esignatureDate)
                bundle.putString("picture", it.esignature)
                RouteManager.goAct(ARouterUrl.ELECTRONIC, bundle)
            }

        }
        binding.mPhone.setOnClickListener {
            //换绑手机号
            bundle.clear()
            bundle.putString("phone", binding.mPhone.text.toString().trim())
            RouteManager.goAct(ARouterUrl.CHANGE_PHONE, bundle)

        }
        /**
         * 绑定微信
         */
        binding.mBindWx.setOnClickListener {
            bindWxDialog.show()

        }
        binding.mTvPwd.setOnClickListener {
            RouteManager.goAct(ARouterUrl.CHANGE_PWD)
        }
        binding.mDest.setOnClickListener {
            destAccount.changeTextSetting()
            destAccount.show()
        }
        /*       //激活信息修改
               binding.mTvAllInfo.setOnClickListener {
                   RouteManager.goAct(ARouterUrl.BASE_INFO_CHANGE)
               }*/
        mViewModel.getAllInfo()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshInfo(event: MyInfoEvent) {
        mViewModel.getAllInfo()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getWxLoginToken(event: WxLoginEvent) {
        //微信登陆
        mViewModel.getWxOpenId(event.code)
    }

    private fun logoOut() {
        //退出音乐播放器
        var service = RouteManager.getAny(ARouterUrl.MUSIC_SERVICE) as Service
        var intent = Intent(this, service::class.java)
        intent.putExtra("close", "")
        stopService(intent)
        //结束mqtt服务
        var mqttService = RouteManager.getAny(ARouterUrl.MQTT_SERVICE) as Service
        var mqttIntent = Intent(this, mqttService::class.java)
        mqttIntent.putExtra("close", "")
        YCBBlueConnectHelper.disconnect()
        stopService(mqttIntent)

        //清除用户登录信息
        Const.mainLiveData.value = null

        MyWorkManger.cancelWork()
        MMkvHelper.clearAll()
        RouteManager.goAct(ARouterUrl.LOGIN_ACT)
        RxActivityTool.finishAllActivity()
    }
}