package com.zj365.mime.act

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.xty.base.act.BaseVmAct
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.MyLinkedMovementMethod
import com.xty.common.aMapUtils.AmapInit
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.bracelet.YCBBlueConnectHelper
import com.xty.common.event.BlueToothConnectEvent
import com.xty.common.event.MyInfoEvent
import com.xty.common.event.ReChangeEvent
import com.xty.common.setImage
import com.xty.common.util.PermissionUtils
import com.xty.network.MyRetrofit
import com.xty.network.model.SettingBean
import com.xty.network.model.UserEquipmentInformationizationBean
import com.zj365.mime.BuildConfig
import com.zj365.mime.R
import com.zj365.mime.databinding.ActDevInfoBinding
import com.zj365.mime.vm.SettingVm
import com.zj365.mime.weight.FactorySettingDialog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import pub.devrel.easypermissions.EasyPermissions


/**
 * 设备解绑 设备信息
 */
@Route(path = ARouterUrl.DEV_INFO)
class DevInfoAct : BaseVmAct<SettingVm>() {

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

    companion object{
        val perssionCode = 0x0001
    }

    var user: SettingBean.User? = null
    var userId: String? = null

    var devInfo: UserEquipmentInformationizationBean? = null
    private val unBindDialog by lazy {
        FactorySettingDialog(this, getString(R.string.dialog_un_bind)) {
            //确认解除绑定
            mViewModel.unBind()
        }
    }

    override fun initData() {
        super.initData()
        isDarkBar = true
        val userBean = intent.getSerializableExtra("user")
        if (userBean != null) {
            user = userBean as SettingBean.User
        }
      //  userId = intent.getStringExtra("userId")
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener { finish() }
        binding.title.mTvTitle.text = "设备信息"
        binding.title.mTvRight.apply {
            if (user != null) {
                visibility = View.VISIBLE
            } else {
                visibility = View.GONE
            }
            text = "解除绑定"
            setTextColor(ContextCompat.getColor(this@DevInfoAct, R.color.col_02c))
            setOnClickListener {
                unBindDialog.showDialog()
            }
        }
        user?.let {
            mViewModel.getUserDeviceInfo(it.id)
           /* binding.mNickName.text = "设备名称：${it.watchName}"
            binding.mNum.text = "设备地址：${it.bluetooth}"
            binding.mCode.text = "设备编号：${it.deviceId}"
            binding.mActiveCode.text = "设备激活码：${it.activationCode}"
            binding.mActiveCode.visibility = View.VISIBLE*/
           // setDevicePic(it.deviceType, binding.ivDevice)
        }

        userId?.let {

        }


        var txtCol = ContextCompat.getColor(this, R.color.col_02c)
        binding.tvContactKefu.movementMethod = MyLinkedMovementMethod().getInstance()
        var span = SpannableString("续期或信号问题请联系客服")
        span.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                if(EasyPermissions.hasPermissions(this@DevInfoAct,
                        Manifest.permission.CALL_PHONE)){
                    startActivity(Intent(Intent.ACTION_CALL, Uri.parse("tel:4000063365")))
                }else{
                    EasyPermissions.requestPermissions(this@DevInfoAct,"",
                        0x00011,
                        Manifest.permission.CALL_PHONE)
                }

            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = txtCol
                ds.isUnderlineText = false
            }

        }, 8, span.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)

        binding.tvContactKefu.text = span

        binding.tvDeviceSetting.setOnClickListener {
            devInfo?.let {
                if(it.bindType == 1){
                    bundle.clear()
                    bundle.putString("web_site_url","${BuildConfig.h5url}pages/index/index?pageId=braceletSetting")
                    RouteManager.goAct(ARouterUrl.H5_ACT,bundle)
                }else{
                    RouteManager.goAct(ARouterUrl.WEAR_MANAGER)
                }
            }

        }

        binding.tvRecharge.setOnClickListener {
            bundle.clear()
            bundle.putString(
                "web_site_url",
                "${BuildConfig.h5url}pages/index/index?pageId=flowRecharge"
            )
            RouteManager.goAct(ARouterUrl.H5_ACT, bundle)
        }


    }

    override fun onSuccess(requestCode: Int) {
        super.onSuccess(requestCode)
        startActivity(Intent(Intent.ACTION_CALL, Uri.parse("tel:4000063365")))
    }

    override fun liveObserver() {
        mViewModel.unbindLive.observe(this) {
            user!!.bluetooth = ""
            Const.mainLiveData.value!!.user.bluetooth = ""//将蓝牙信息清空
            MyRetrofit.get().BLUETOOTH_MAC = ""//清除蓝牙信息
            MMkvHelper.remove(Const.Watch_Device_Type)//清除手表型号
            Const.watchType = -1//将手表型号恢复初始值
            Const.battery = ""//电池信息恢复初始值
            MMkvHelper.remove(Const.Blue_Tooth)//清除蓝牙信息
          /*  YCBBlueConnectHelper.disconnect()
            YCBBlueConnectHelper.cancelTimer()*/
            MMkvHelper.clearWhatchInfo()//删除手表信息
            EventBus.getDefault().post(BlueToothConnectEvent())//刷新蓝牙连接信息
            EventBus.getDefault().post(MyInfoEvent())  //刷新个人信息
            finish()
        }

        mViewModel.deviceInfo.observe(this) {
            devInfo = it.data
            if(it.data.bindType == 1){
                binding.mNickName.text = "设备名称：${it.data.watchName?:""}"
                binding.mNum.text = "设备编码：${it.data.bluetooth?:""}"
                binding.mCode.text = "物联网卡：${it.data.iccid?:""}"
                binding.mActiveCode.text = "流量到期：${it.data.flowExpireTime?:""}"
                binding.mActiveCode.visibility = View.VISIBLE
                binding.ivDevice.setImage(this,it.data.deviceImageUrl)

            }else{
                binding.mNickName.text = "设备名称：${it.data.watchName?:""}"
                binding.mNum.text = "设备编码：${it.data.bluetooth?:""}"
                binding.mCode.text = "设备激活码：${it.data.activationCode?:""}"
                binding.mActiveCode.text = "设备激活码：${it.data.activationCode?:""}"
                binding.mActiveCode.visibility = View.GONE
                binding.tvRecharge.visibility = View.GONE
                binding.tvDeviceSetting.visibility = View.VISIBLE
                binding.ivDevice.setImage(this,it.data.deviceImageUrl)
            }


        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshUI(event: ReChangeEvent){
        user?.let {
            mViewModel.getUserDeviceInfo(it.id)
        }
    }

}