package com.abbidot.tracker.ui.activity.device.wifi

import android.animation.ValueAnimator
import android.content.Intent
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.activity.viewModels
import androidx.core.animation.doOnEnd
import androidx.core.content.ContextCompat
import com.abbidot.baselibrary.constant.ConState
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.databinding.ActivityAddWifiPowerZone1Binding
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.ConnectionDeviceViewModel
import com.clj.fastble.BleManager

class AddWifiPowerZone1Activity :
    BaseActivity<ActivityAddWifiPowerZone1Binding>(ActivityAddWifiPowerZone1Binding::inflate) {

    private val mConnectionDeviceViewModel: ConnectionDeviceViewModel by viewModels()

    private val mAnimatorDuration = 2000L
    private var mHaveSignal = true

    private var mPetBean: PetBean? = null
    private var isFirstBind = false
    private var mPetCurrentLat = 0.0
    private var mPetCurrentLon = 0.0

    override fun getTopBar() = mViewBinding.ilAddWifiZone1TopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")

        intent.extras?.apply {
            isFirstBind = getBoolean(ConstantString.isFirstBind, false)
            mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)
            mPetCurrentLat = getDouble(ConstantString.Latitude, 0.0)
            mPetCurrentLon = getDouble(ConstantString.Longitude, 0.0)
        }

        if (isFirstBind) setLeftBackImage(0)
        else setLeftBackImage(R.drawable.icon_white_back_svg)

        mViewBinding.apply {
            mPetBean?.let {
                ViewUtil.instance.setPetTypeHead(
                    ivAddWifiZone1PetHead.appHeadImage, it.imgurl, it.petType
                )
            }

            tvAddWifiZone1LaterBtn.visibility = if (isFirstBind) View.VISIBLE
            else View.INVISIBLE

            svAddWifiZone1Signal.setValue(2)
            setOnClickListenerViews(
                btnAddWifiZone1Next,
                tvAddWifiZone1LaterBtn,
                ilAddWifiZone1BluetoothTips.trbBleConnectState
            )
            mHaveSignalAnimator.start()
        }

        connectBle()
    }

    override fun liveDataObserve() {
        //添加成功结束页面
        XEventBus.observe(this, EventName.RefreshWiFiZone) {
            finish()
        }

        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { ble: BleTrackDeviceBean ->
            showLoading(false)
            mPetBean?.apply {
                if (TextUtils.isEmpty(macID)) macID = ble.mac
                if (macID == ble.mac) {
                    mViewBinding.ilAddWifiZone1BluetoothTips.trbBleConnectState.let { view ->
                        val bgColor = if (ble.conState == ConState.CONNECTED) {
                            ViewUtil.instance.viewShowFadeInAnimation(mViewBinding.btnAddWifiZone1Next)
                            view.text = getString(R.string.tracker_manage_set_ble_connect)
                            ContextCompat.getColor(mContext, R.color.cyan_color1)
                        } else {
                            ViewUtil.instance.viewHideFadeInAnimation(mViewBinding.btnAddWifiZone1Next)
                            view.text = getString(R.string.tracker_manage_set_ble_unconnect)
                            ContextCompat.getColor(mContext, R.color.red_color4)
                        }
                        view.setBackgroundColor(bgColor)
                        ViewUtil.instance.bleConStateToast(
                            this@AddWifiPowerZone1Activity, ble.conState, Gravity.CENTER
                        )
                    }
                }
            }
        }

        //搜索蓝牙的设备状态
        XEventBus.observe(this, EventName.ActionConDeviceState) { conState: Int ->
            ViewUtil.instance.viewHideFadeInAnimation(mViewBinding.btnAddWifiZone1Next)
            if (conState == ConState.DEVICE_NOT_FOUND) {
                ViewUtil.instance.showDialog(
                    mContext,
                    R.string.txt_no_search_device,
                    object : BaseDialog.OnDialogOkListener {
                        override fun onOkClick(dialog: BaseDialog<*>) {
                            dialog.dismiss()
                        }
                    },
                    okTextResId = R.string.txt_sure,
                    cancelTextResId = R.string.txt_cancel
                )
            }
            mViewBinding.ilAddWifiZone1BluetoothTips.trbBleConnectState.let { view ->
                ViewUtil.instance.bleConActionState(this, view, conState)
            }
        }
    }

    private val mHaveSignalAnimator = ValueAnimator.ofInt(0, 3).apply {
        duration = mAnimatorDuration
//        repeatCount = ValueAnimator.INFINITE
        //匀速变化
        interpolator = LinearInterpolator()
        addUpdateListener {
            val value = it.animatedValue as Int
            mViewBinding.svAddWifiZone1Signal.setValue(value)
        }

        doOnEnd {
            startDelay = 3000
            if (mHaveSignal) {
                mViewBinding.rvAddWifiZone1Room.playCloseAnimator()
                setIntValues(3, 0)
            } else {
                mViewBinding.rvAddWifiZone1Room.playOpenAnimator()
                setIntValues(0, 3)
            }
            mHaveSignal = !mHaveSignal
            start()
        }
    }

    private fun connectBle() {
        mPetBean?.apply {
//            if (isFirstBind)
//                mConnectionDeviceViewModel.connectDeviceToDeviceOutId(
//                    this@AddWifiPowerZone1Activity, deviceOutId
//                )

            //是否连接了蓝牙
            if (BleManager.getInstance().isConnected(macID)) {
                ViewUtil.instance.viewShowFadeInAnimation(mViewBinding.btnAddWifiZone1Next)
                mViewBinding.ilAddWifiZone1BluetoothTips.trbBleConnectState.let {
                    it.setBackgroundColor(
                        ContextCompat.getColor(mContext, R.color.cyan_color1)
                    )
                    it.text = getString(R.string.tracker_manage_set_ble_connect)
                }
            } else {
                mConnectionDeviceViewModel.connectDeviceToMac(
                    this@AddWifiPowerZone1Activity, macID
                )
            }
        }
    }

    private fun goNext() {
        Util.checkLocationPermissionsGpsEnabled(this, {
            Intent(mContext, AddWifiPowerZone2Activity::class.java).let {
                mPetBean?.let { pet ->
                    it.putExtra(ConstantString.Pet, pet)
                }
                it.putExtra(ConstantString.isFirstBind, isFirstBind)
                it.putExtra(ConstantString.Latitude, mPetCurrentLat)
                it.putExtra(ConstantString.Longitude, mPetCurrentLon)
                if (isFirstBind) {
                    startActivityFinish(it)
                } else {
                    startActivity(it)
                }
            }
        })
    }

    /**
     * 手动连接/断开设备
     */
    private fun connectionBtn(btnString: String) {
        if (btnString == getString(R.string.tracker_manage_set_ble_unconnect)) {
            connectBle()
        } else if (btnString == getString(R.string.tracker_manage_set_ble_connect)) {
//            ViewUtil.instance.operateDialogTips(mContext, R.string.txt_disconnect_tips) {
//                mPetBean?.apply {
//                    SRBleUtil.instance.disconnectToMac(macID)
//                }
//            }
        }
    }

    override fun listenBackPressed() {
        if (!isFirstBind) super.listenBackPressed()
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnAddWifiZone1Next -> goNext()

                tvAddWifiZone1LaterBtn -> startActivityFinish(
                    Intent(
                        mContext, HomeV2Activity::class.java
                    )
                )

                ilAddWifiZone1BluetoothTips.trbBleConnectState -> connectionBtn(
                    ilAddWifiZone1BluetoothTips.trbBleConnectState.text.toString()
                )
            }
        }
    }
}