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

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
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.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.LedLightColorAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.MapDeviceBean
import com.abbidot.tracker.bean.PetBean
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


/**
 * LedLight颜色光源设置
 */
class LedLightActivityV0 : 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 var mOldMapDeviceBean: MapDeviceBean? = null
    private var mBleTrackDeviceBean: BleTrackDeviceBean? = null
    private lateinit var mLedLightColorAdapter: LedLightColorAdapter
    private lateinit var mLedModeList: MutableList<String>

    //防止多次按返回键执行
    private var isFinishSave = false

    //禁用模式
    private var isDisabledMode = true

    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)
//        initStatus()

        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()
                ledMode = position + 1
                mViewBinding.ledLightMode.detailText = mLedModeList[position]
                mViewBinding.ledLightOpenAndClose.switch.let {
                    if (!it.isChecked) {
                        it.isChecked = true
                    }
                    setBleLedMode(ledMode)
                }
            }
        })
        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))
//            mMapDeviceBean?.apply {
//                detailText = when {
//                    ledMode - 1 >= mLedModeList.size -> {
//                        mLedModeList[mLedModeList.size - 1]
//                    }
//
//                    ledMode == 0 -> {
//                        mLedModeList[0]
//                    }
//
//                    else -> mLedModeList[ledMode - 1]
//                }
//            }
        }

        val colorListResId = mutableListOf(
            R.color.white,
            R.color.colormenu,
            R.color.corner_color,
            R.color.blue_light,
            R.color.deep_blue,
            R.color.red_blue,
            R.color.yellow_color,
            R.color.yellow_red_color
        )
        mLedLightColorAdapter = LedLightColorAdapter(mContext, colorListResId)
        mLedLightColorAdapter.setOnItemClickListener(object :
            BaseRecyclerAdapter.OnItemClickListener {
            override fun onItemClick(itemView: View?, pos: Int) {
                setLedLightColor(ContextCompat.getColor(mContext, colorListResId[pos]))
            }
        })


        mViewBinding.apply {
            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)
            }
            ViewUtil.instance.setRecyclerViewGridLayout(
                mContext,
                colorSelectRecyclerView,
                mLedLightColorAdapter,
                spanCount = 2,
                bottom = AppUtils.dpToPx(9),
                itemWidth = AppUtils.dpToPx(30),
                offset = AppUtils.dpToPx(290)
            )

            selectColorPaintView.setOnColorSelectListener {
                setLedLightColor(it)
            }

            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@LedLightActivityV0, 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
                        mOldMapDeviceBean = data.copy()
                        setDeviceData(data)
                    }
                }
            })
        }
        mLedLightViewModel.mSetLedLightLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    showToast(R.string.txt_change_successful, isFinish = true)
                }

                override fun onRequestError(exceptionCode: String?) {
                    isFinishSave = false
                    mViewBinding.btnLedLightSetSave.isEnabled = true
                }
            })
        }

        //接收开蓝牙操作,然后搜索连接设备
        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)
                }
            }
        }
    }

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

                setLedLightColor(
                    Color.rgb(ledRedValue, ledGreenValue, ledBlueValue), true
                )
                if (ledMode == 0 || ledMode > mLedModeList.size) ledMode = 1
                it.ledLightMode.detailText = mLedModeList[ledMode - 1]

                updateDisabledState(this)
            }
        }
    }

    private fun updateDisabledState(mapDeviceBean: MapDeviceBean) {
        mapDeviceBean.apply {
            if (SRBleUtil.instance.isMacConnect(deviceMacId)) {
                setDisabledState(false)
            } else {
                //是否超时上报
                val isTimeoutReport = Util.isTimeoutReport(updateTime,gnssInterval)
                if (powerSwitch == ConstantInt.Type0 || powerSwitch == ConstantInt.Type2 || powerSwitch == ConstantInt.Type3 || inWifiZone == ConstantInt.Type1 || isTimeoutReport) {
                    setDisabledState(true)
                } else {
                    setDisabledState(false)
                }
            }
        }
    }

    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.VISIBLE
                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) {
        mBleTrackDeviceBean = trackBleDevice
        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) {
        mBleTrackDeviceBean?.apply {
            SRBleUtil.instance.setBleLedSwitch(this@LedLightActivityV0, bleDevice, mode)
        }
    }

    override fun leftBackOnClick() {
        if (null == mMapDeviceBean || null == mOldMapDeviceBean) {
            super.leftBackOnClick()
            return
        }
        if (isFinishSave) return
        //是否是蓝牙连接了,修改设备数据返回，同步服务器
        if (null != mBleTrackDeviceBean) {
            mMapDeviceBean?.apply {
                mOldMapDeviceBean?.let {
                    if (it == mMapDeviceBean) {
                        super.leftBackOnClick()
                    } else {
                        //判断是否有蓝牙连接
                        if (BleManager.getInstance().isConnected(mBleTrackDeviceBean!!.bleDevice)) {
                            finishAndSave(ConstantInt.Type1)
                        } else {
                            super.leftBackOnClick()
                        }
                    }
                }
            }
        } else {
            super.leftBackOnClick()
        }
    }

    /**
     * 保存设置数据
     */
    private fun finishAndSave(modeType: Int) {
        if (null == mMapDeviceBean) {
            finish()
            return
        }
        mMapDeviceBean?.apply {
            isFinishSave = true
            mLedLightViewModel.setLedLight(this@LedLightActivityV0, this, modeType)
        }
    }

    /**
     * @param show 只显示,不作为命令处理
     */
    private fun setLedLightColor(color: Int, show: Boolean = false) {
        val drawableColor = ColorDrawable(color)
        mViewBinding.currentSelectColor.appHeadImage.setImageDrawable(drawableColor)
//        mViewBinding.ledLightBarColorImage.setBackgroundColor(color)

        val red = color and 0xff0000 shr 16
        val green = color and 0x00ff00 shr 8
        val blue = color and 0x0000ff

        mMapDeviceBean?.apply {
            ledRedValue = red
            ledGreenValue = green
            ledBlueValue = blue
        }

//        mViewBinding.tvLedLightCurrentRgb.text = String.format("#%06X", -0x1 and color)
        mViewBinding.tvLedLightCurrentRgb.text = String.format("#%06X", 0xffffff and color)

        if (!show) {
            mBleTrackDeviceBean?.let {
                //判断是否有蓝牙连接
                if (BleManager.getInstance().isConnected(it.bleDevice)) {
                    SRBleUtil.instance.writeData(
                        it.bleDevice, SRBleCmdUtil.instance.ledColor(
                            SRBleCmdUtil.CMD_WRITE, red, green, blue
                        )
                    )
                }
            }
        }
    }

    /**
     * 断开连接设备
     */
    private fun operateDeviceTips(messageID: Int, type: Int = 0) {
        ViewUtil.instance.showDialog(mContext, messageID, object : BaseDialog.OnDialogOkListener {
            override fun onOkClick(dialog: BaseDialog<*>) {
                dialog.dismiss()
                when (type) {
                    0 -> {
                        mBleTrackDeviceBean?.let {
                            mConnectionDeviceViewModel.disconnect(it.bleDevice)
                        }
                    }
                }
            }
        }, okTextResId = R.string.start_txt_yes)
    }

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

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

    private fun setLedSwitch() {
        mViewBinding.ledLightOpenAndClose.switch.apply {
            mMapDeviceBean?.let {
                if (isChecked) {
                    it.ledSwitch = ConstantInt.Open
                    setBleLedMode(it.ledMode)
                } else {
                    it.ledSwitch = ConstantInt.Close
                    setBleLedMode(0)
                }
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v) {
                //手动连接设备
                ledLightBluetoothTips.trbBleConnectState -> connectionBtn(ledLightBluetoothTips.trbBleConnectState.text.toString())
                btnLedLightSetSave -> {
                    val modeType = if (null != mBleTrackDeviceBean && BleManager.getInstance()
                            .isConnected(mBleTrackDeviceBean!!.bleDevice)
                    ) ConstantInt.Type1
                    else ConstantInt.Type2
                    btnLedLightSetSave.isEnabled = false
                    finishAndSave(modeType)
                }

                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()
    }
}