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

import android.view.Gravity
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
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.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.MapDeviceBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.bean.ReceiveDeviceData
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityLedLightBinding
import com.abbidot.tracker.deprecated.ui.activity.vm.LedLightViewModel
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.util.bluetooth.SRBleCmdUtil
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.abbidot.tracker.vm.ConnectionDeviceViewModel
import com.abbidot.tracker.vm.TrackerInfoViewModel
import com.clj.fastble.BleManager
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView


/**
 * LedLight颜色光源设置
 */
class LedLightActivity : BaseActivity<ActivityLedLightBinding>(ActivityLedLightBinding::inflate) {

    private val mLedLightViewModel: LedLightViewModel by viewModels()
    private val mTrackerManageSetViewModel: TrackerInfoViewModel by viewModels()
    private val mConnectionDeviceViewModel: ConnectionDeviceViewModel by viewModels()

    private var mPetBean: PetBean? = null
    private var mMapDeviceBean: MapDeviceBean? = null
    private lateinit var mLedModeList: MutableList<String>

    //禁用模式
    private var isDisabledMode = true
    private var mLedControlType = ConstantInt.Type0
    private var mLedSwitch = ConstantInt.Type1
    private var mLedMode = ConstantInt.Type1
    private var mLedTempMode = ConstantInt.Type1

    override fun getTopBar() = mViewBinding.ilLedLightBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.tracker_manage_set_led)
        setLeftBackImage(R.drawable.icon_white_back_svg)

        mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)

        mLedModeList = mutableListOf(
            getString(R.string.tracker_light_mode_sustained),
            getString(R.string.tracker_light_mode_breathing),
//                getString(R.string.tracker_light_mode_slow_flash),
            getString(R.string.tracker_light_mode_flash)
        )

        ViewUtil.instance.showQMUICommonListItemView(
            mContext,
            mViewBinding.ledLightOpenAndClose,
            null,
            getString(R.string.tracker_manage_set_led)
        )

        val builder = ViewUtil.instance.showBottomSheetList(mContext, { dialog, _, position, _ ->
            mMapDeviceBean?.apply {
                dialog.dismiss()
                mLedSwitch = ledSwitch
                mLedMode = ledMode
                mLedTempMode = position + 1
                setBleLedMode(mLedTempMode)
            }
        })
        for (i in 0 until mLedModeList.size) builder.addItem(mLedModeList[i])

        mViewBinding.ledLightMode.apply {
            ViewUtil.instance.showQMUICommonListItemView(mContext, this, {
                if (!isDisabledMode) builder.build().show()
            }, getString(R.string.txt_light_mode))
        }


        mViewBinding.apply {
            ViewUtil.instance.viewRotationAnimator(ilLedLightBtnState.ivLedBtnState, true)
            ilLedLightIssueLayout.let {
                it.tvIssueOneBigTitle.setText(R.string.txt_led_light_set)
                it.tvIssueTwoSmallOneTitle.setText(R.string.txt_bluetooth_setup)
                it.tvIssueTwoSmallOneTitle.setText(R.string.txt_bluetooth_setup)
                it.tvIssueTwoSmallTitleOneContent.setText(R.string.txt_bluetooth_setup_dec)
                it.tvIssueTwoSmallTwoTitle.setText(R.string.txt_network_setup)
                it.tvIssueTwoSmallTitleTwoContent.setText(R.string.txt_network_setup_dec)
            }

            setOnClickListenerViews(
                ledLightBluetoothTips.trbBleConnectState,
                btnLedLightSetSave,
                btnLedLightIssue,
                ilLedLightIssueLayout.tvCloseIssueBtn,
                mViewBinding.ledLightOpenAndClose.switch
            )
        }

        setDisabledState(true)
        mPetBean?.apply {
            //查找是否连接了蓝牙
            SRBleUtil.instance.getConnectMacDevice(macID)?.let {
                updateConState(it, false)
            }
            mTrackerManageSetViewModel.getPetTrackerInfo(this@LedLightActivity, deviceId)
        }
    }

    override fun liveDataObserve() {
        mTrackerManageSetViewModel.mTrackerInfoLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    val data = it.getOrNull()
                    data?.apply {
                        mMapDeviceBean = data
                        setDeviceData(data)
                    }
                }
            })
        }
        mLedLightViewModel.apply {
            mLedSwitchLiveData.observe(this@LedLightActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        mPetBean?.apply {
                            if (!SRBleUtil.instance.isMacConnect(macID)) {
                                mViewBinding.ledLightOpenAndClose.switch.isChecked =
                                    !mViewBinding.ledLightOpenAndClose.switch.isChecked
                                mMapDeviceBean?.let { m ->
                                    val ledSwitch = if (m.ledSwitch == ConstantInt.Open) {
                                        ConstantInt.Close
                                    } else {
                                        ConstantInt.Open
                                    }
                                    m.ledSwitch = ledSwitch
                                }
                            }
                        }
                        setLedControlState()
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        setLedControlState()
                    }

                    override fun onInterceptCode() {
                        setLedControlState()
                    }
                })
            }
            mSetLedLightLiveData.observe(this@LedLightActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        mLedMode = mLedTempMode
                        mLedSwitch = ConstantInt.Type1
                        mViewBinding.ledLightOpenAndClose.switch.isChecked = true
                        setLedModeControlState()
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        setLedModeControlState()
                    }

                    override fun onInterceptCode() {
                        setLedModeControlState()
                    }
                })
            }
        }

        //接收开蓝牙操作,然后搜索连接设备
        XEventBus.observe(this, EventName.ActionConDeviceState) { conState: Int ->
            mViewBinding.ledLightBluetoothTips.trbBleConnectState.let { view ->
                if (!isDisabledMode) {
                    ViewUtil.instance.bleConActionState(this, view, conState)
                }
            }
        }
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { ble: BleTrackDeviceBean ->
            mPetBean?.apply {
                if (ble.mac == macID) {
                    mMapDeviceBean?.let {
                        updateDisabledState(it)
                    }
                    updateConState(ble)
                }
            }
        }
        //接收发送指令后设备返回的数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receiveData: ReceiveDeviceData ->
            mPetBean?.apply {
                if (macID == receiveData.mac) {
                    parseData(receiveData.data)
                }
            }
        }
    }

    /**
     * 设置LED可以点击状态
     */
    private fun setLedControlState() {
        mPetBean?.apply {
            if (!SRBleUtil.instance.isMacConnect(macID)) {
                setBtnState(true)
            }
        }
    }

    private fun setLedModeControlState() {
        mPetBean?.apply {
            if (!SRBleUtil.instance.isMacConnect(macID)) {
                setBtnState(true)
                mMapDeviceBean?.let {
                    it.ledSwitch = mLedSwitch
                    it.ledMode = mLedMode
                }
            }
        }
    }

    private fun parseData(data: ByteArray?) {
        if (null != data && data.isNotEmpty()) {
            val data0 = SRBleCmdUtil.instance.byteToInt(data[0])
            val data1 = SRBleCmdUtil.instance.byteToInt(data[1])
            val data2 = SRBleCmdUtil.instance.byteToInt(data[2])
            if (data0 == 3 && data1 == 1) {
                val data3 = SRBleCmdUtil.instance.byteToInt(data[3])
                val ledSwitch = if (data3 > 0) {
                    mLedMode = data3
                    mViewBinding.ledLightOpenAndClose.switch.isChecked = true
                    ConstantInt.Open
                } else {
                    mViewBinding.ledLightOpenAndClose.switch.isChecked = false
                    ConstantInt.Close
                }

                val modeType = if (data2 == 0) {
                    ConstantInt.Type1
                } else {
                    ConstantInt.Type3
                }
                mMapDeviceBean?.let {
                    it.ledSwitch = ledSwitch
                    setBtnState(true)
                    //控制开关
                    if (mLedControlType == ConstantInt.Type0) {
                        //远程控制
                        mLedLightViewModel.setLedSwitch(
                            null, it.deviceServerId, ledSwitch, modeType
                        )
                    } else {
                        //控制模式
                        it.ledMode = data3
                        //远程控制
                        mLedLightViewModel.setLedLight(this@LedLightActivity, it, modeType)
                    }
                }
            }
        }
    }

    private fun setDeviceData(mapDeviceBean: MapDeviceBean) {
        mapDeviceBean.apply {
            mLedMode = ledMode
            mLedSwitch = ledSwitch
            mViewBinding.let {
                it.ledLightOpenAndClose.switch.isChecked = ledSwitch == ConstantInt.Open

                if (ledMode == 0 || ledMode > mLedModeList.size) ledMode = 1
                it.ledLightMode.detailText = mLedModeList[ledMode - 1]

                updateDisabledState(this)
            }
        }
    }

    private fun updateDisabledState(mapDeviceBean: MapDeviceBean) {
        mapDeviceBean.apply {
            setDisabledState(!Util.getLedControlState(deviceMacId, mapDeviceBean))
        }
    }

    private fun setDisabledState(isDisabled: Boolean) {
        isDisabledMode = isDisabled
        mViewBinding.apply {
            val tColor = if (isDisabled) {
                btnLedLightSetSave.visibility = View.GONE
                ledLightBluetoothTips.root.visibility = View.GONE
                R.color.grey_color
            } else {
                btnLedLightSetSave.visibility = View.GONE
                ledLightBluetoothTips.root.visibility = View.VISIBLE
                R.color.qmui_config_color_gray_1
            }
            ledLightOpenAndClose.textView.setTextColor(ContextCompat.getColor(mContext, tColor))
            ledLightMode.textView.setTextColor(ContextCompat.getColor(mContext, tColor))
        }
    }

    /**
     * 更新设备连接状态
     */
    private fun updateConState(
        trackBleDevice: BleTrackDeviceBean, isShowToast: Boolean = true
    ) {
        mViewBinding.ledLightBluetoothTips.trbBleConnectState.let { view ->
            val bgColor = if (trackBleDevice.conState == ConState.CONNECTED) {
                view.text = getString(R.string.tracker_manage_set_ble_connect)
                ContextCompat.getColor(mContext, R.color.cyan_color1)
            } else {
                view.text = getString(R.string.tracker_manage_set_ble_unconnect)
                ContextCompat.getColor(mContext, R.color.red_color4)
            }
            view.setBackgroundColor(bgColor)
        }
        if (!isDisabledMode && isShowToast) {
            ViewUtil.instance.bleConStateToast(this, trackBleDevice.conState, Gravity.CENTER)
        }
    }

    private fun setBleLedMode(mode: Int) {
        mMapDeviceBean?.apply {
            mLedControlType = ConstantInt.Type1
            setBtnState(false)
            if (BleManager.getInstance().isConnected(deviceMacId)) {
                //蓝牙控制
                SRBleUtil.instance.getConnectMacDevice(deviceMacId)?.let {
                    SRBleUtil.instance.setBleLedSwitch(this@LedLightActivity, it.bleDevice, mode)
                }
            } else {
                //远程控制
                ledMode = mode
                ledSwitch = ConstantInt.Open
                mLedLightViewModel.setLedLight(this@LedLightActivity, this, ConstantInt.Type2)
            }
        }
    }

    /**
     * 手动连接/断开设备
     */
    private fun connectionBtn(btnString: String) {
        mPetBean?.apply {
            ViewUtil.instance.connectionBtn(mContext, btnString, macID) {
                mConnectionDeviceViewModel.connectDeviceToMac(this@LedLightActivity, macID)
            }
        }
    }

    /**
     * 显示led问题
     */
    private fun showLedIssue() {
        mViewBinding.apply {
            if (ilLedLightIssueLayout.root.isGone) {
                YoYo.with(Techniques.BounceInUp).duration(700).onStart {
                    ilLedLightIssueLayout.root.visibility = View.VISIBLE
                    vLedIssueShadeView.visibility = View.VISIBLE
                }.playOn(ilLedLightIssueLayout.root)
            } else {
                vLedIssueShadeView.visibility = View.GONE
                YoYo.with(Techniques.SlideOutDown).duration(600).onEnd {
                    ilLedLightIssueLayout.root.visibility = View.GONE
                }.playOn(ilLedLightIssueLayout.root)
            }
        }
    }

    private fun setBtnState(setEnabled: Boolean) {
        mViewBinding.apply {
            if (setEnabled) {
                ledLightMode.detailText = mLedModeList[mLedMode - 1]
                ledLightMode.isEnabled = true
                lvLedLightModeLoading.visibility = View.GONE
                ledLightOpenAndClose.accessoryType = QMUICommonListItemView.ACCESSORY_TYPE_SWITCH
                ilLedLightBtnState.root.visibility = View.GONE
            } else {
                ledLightMode.detailText = ""
                ledLightMode.isEnabled = false
                lvLedLightModeLoading.visibility = View.VISIBLE
                ledLightOpenAndClose.accessoryType = QMUICommonListItemView.ACCESSORY_TYPE_NONE
                ilLedLightBtnState.root.visibility = View.VISIBLE
            }
        }
    }

    private fun setLedSwitch() {
        mMapDeviceBean?.apply {
            mLedControlType = ConstantInt.Type0
            mViewBinding.ledLightOpenAndClose.switch.isChecked =
                !mViewBinding.ledLightOpenAndClose.switch.isChecked
            setBtnState(false)
            val ledSwitch = if (ledSwitch == ConstantInt.Open) {
                ConstantInt.Close
            } else {
                ConstantInt.Open
            }
            if (BleManager.getInstance().isConnected(deviceMacId)) {
                //蓝牙控制
                SRBleUtil.instance.getConnectMacDevice(deviceMacId)?.let {
                    SRBleUtil.instance.setBleLedSwitch(
                        this@LedLightActivity, it.bleDevice, ledSwitch
                    )
                }
            } else {
                //远程控制
                mLedLightViewModel.setLedSwitch(
                    null, deviceServerId, ledSwitch, ConstantInt.Type2
                )
            }
        }
    }

//    val modeType = if (null != mBleTrackDeviceBean && BleManager.getInstance()
//            .isConnected(mBleTrackDeviceBean!!.bleDevice)
//    ) ConstantInt.Type1
//    else ConstantInt.Type2
//    btnLedLightSetSave.isEnabled = false
//    finishAndSave(modeType)

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v) {
                //手动连接设备
                ledLightBluetoothTips.trbBleConnectState -> connectionBtn(ledLightBluetoothTips.trbBleConnectState.text.toString())

                btnLedLightIssue -> showLedIssue()
                ilLedLightIssueLayout.tvCloseIssueBtn -> showLedIssue()
                ledLightOpenAndClose.switch -> {
                    if (isDisabledMode) {
                        ledLightOpenAndClose.switch.isChecked =
                            !ledLightOpenAndClose.switch.isChecked
                    } else setLedSwitch()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mViewBinding.selectColorPaintView.recycle()
    }
}