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

import android.content.Intent
import android.text.InputFilter
import android.view.Gravity
import android.view.View
import android.widget.RelativeLayout
import androidx.activity.viewModels
import androidx.core.view.marginBottom
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.EventName
import com.abbidot.baselibrary.eventbus.XEventBus
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.HistoryDataBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.bean.ReceiveDeviceData
import com.abbidot.tracker.bean.WiFiBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.databinding.ActivityAddWifiPasswordBinding
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.CountDownTimerViewModel
import com.clj.fastble.BleManager
import com.clj.fastble.utils.HexUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class AddWifiPasswordActivity :
    BaseActivity<ActivityAddWifiPasswordBinding>(ActivityAddWifiPasswordBinding::inflate) {

    private var isShowPassword = false
    private var mConnectingPointNum = 1

    private var mWiFiBean: WiFiBean? = null
    private var mBleTrackDeviceBean: BleTrackDeviceBean? = null
    private var mPetBean: PetBean? = null

    private var mDecWiFiAddressData: HistoryDataBean? = null
    private var isFirstBind = false
    private var mPetCurrentLat = 0.0
    private var mPetCurrentLon = 0.0

    private val mCountDownTimerViewModel: CountDownTimerViewModel by viewModels()

    override fun getTopBar() = mViewBinding.ilAddWifiPwdTopBar.titleTopBar

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

        intent.extras?.apply {
            mWiFiBean =
                Util.getParcelableAdaptive(intent, ConstantString.WiFi, WiFiBean::class.java)
            mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)

            mDecWiFiAddressData = Util.getParcelableAdaptive(
                intent, ConstantString.HistoryDataBean, HistoryDataBean::class.java
            )
            isFirstBind = getBoolean(ConstantString.isFirstBind, false)
            mPetCurrentLat = getDouble(ConstantString.Latitude, 0.0)
            mPetCurrentLon = getDouble(ConstantString.Longitude, 0.0)
        }

        mViewBinding.apply {

            mWiFiBean?.let {
                tvAddWifiPwdName.text = it.name
            }

            ilAddWifiPwdPassword.let {
                it.tvInputNameTitle.text = getString(R.string.login_txt_password)
                it.etInputContent.setHint(R.string.login_txt_password)
                ViewUtil.instance.setShowAndHidePassword(
                    it.etInputContent, it.ivInputRepresentImage
                )
                val filters = arrayOf<InputFilter>(InputFilter.LengthFilter(32))
                it.etInputContent.filters = filters
                ViewUtil.instance.setInputViewErrorHideClick(
                    mContext, it.rlEtInputLayout, tvAddWifiPwdErrorTip, it.etInputContent
                )
                it.etInputContent.addTextChangedListener { edit ->
                    edit?.let { e ->
                        btnAddWifiPwdConnect.isEnabled = e.length >= 8
                    }
                }
            }

            lavAddWifiPwdAnim.setAnimation("lottie/dfu_loading.json")

            setOnClickListenerViews(
                ilAddWifiPwdPassword.ivInputRepresentImage, btnAddWifiPwdConnect, btnAddWifiPwdSkip
            )
        }

        setListenKeyboardChange(1)

        mPetBean?.apply {
            mBleTrackDeviceBean = SRBleUtil.instance.getConnectMacDevice(macID)
        }

        mWiFiBean?.let {
            if (it.auth_type == ConstantInt.Type0) {
                mViewBinding.ilAddWifiPwdPassword.root.visibility = View.GONE
                noPasswordConnect()
            }
        }
    }

    override fun liveDataObserve() {
        mCountDownTimerViewModel.apply {
            mCountDowningLiveData.observe(this@AddWifiPasswordActivity) {
                var connectingPoint = ""
                when (mConnectingPointNum) {
                    1 -> connectingPoint = "."
                    2 -> connectingPoint = ".."
                    3 -> connectingPoint = "..."
                }
                mConnectingPointNum++
                val str = getString(R.string.txt_connect_ing) + connectingPoint
                mViewBinding.btnAddWifiPwdConnect.text = str
            }
            mCountDownEndLiveData.observe(this@AddWifiPasswordActivity) {
                mConnectingPointNum = 1
                mCountDownTimerViewModel.startCountDown(3)
            }
        }

        //接收蓝牙返回数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receiveData: ReceiveDeviceData ->
            mPetBean?.apply {
                if (macID == receiveData.mac) {
                    val data = receiveData.data
                    parseData(data)
                }
            }
        }
    }

    /**
     * * 解析蓝牙返回的数据
     */
    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 == 33 && data1 == 1) {
                sendPasswordEnd()
                when (data2) {
                    0 -> {
                        mViewBinding.btnAddWifiPwdConnect.isEnabled = false
                        showToast(R.string.txt_successful, gravity = Gravity.CENTER)
                        mViewBinding.root.postDelayed({
                            goEditWifiActivity()
                        }, 1000)
                    }

                    6 -> showToast(R.string.txt_fail)
                    else -> ViewUtil.instance.setInputViewErrorShow(
                        mContext,
                        mViewBinding.ilAddWifiPwdPassword.rlEtInputLayout,
                        mViewBinding.tvAddWifiPwdErrorTip
                    )
                }
            }
        }
    }

    override fun showSoftKeyboardCallback() {
        super.showSoftKeyboardCallback()
        mViewBinding.btnAddWifiPwdSkip.apply {
            val setBottomMargin = AppUtils.dpToPx(320)
            if (setBottomMargin != marginBottom) {
                val params = layoutParams as RelativeLayout.LayoutParams
                params.bottomMargin = setBottomMargin
                layoutParams = params
            }
        }
    }

    override fun hideSoftKeyboardCallback() {
        super.hideSoftKeyboardCallback()
        mViewBinding.btnAddWifiPwdSkip.apply {
            val setBottomMargin = AppUtils.dpToPx(28)
            if (setBottomMargin != marginBottom) {
                val params = layoutParams as RelativeLayout.LayoutParams
                params.bottomMargin = setBottomMargin
                layoutParams = params
            }
        }
    }

    private fun sendPasswordStart() {
        showLoading(true, R.string.txt_please_wait)
        mViewBinding.apply {
            hideInputMethod(ilAddWifiPwdPassword.etInputContent)
            btnAddWifiPwdConnect.isEnabled = false
            lavAddWifiPwdAnim.playAnimation()
            lavAddWifiPwdAnim.visibility = View.VISIBLE
        }
        mCountDownTimerViewModel.startCountDown(3)
    }

    private fun sendPasswordEnd() {
        showLoading(false)
        mViewBinding.btnAddWifiPwdConnect.apply {
            isEnabled = true
            setText(R.string.txt_connect)
        }
        mViewBinding.lavAddWifiPwdAnim.apply {
            cancelAnimation()
            visibility = View.GONE
        }
        mCountDownTimerViewModel.stopCountDown()
    }

    private fun noPasswordConnect() {
        mBleTrackDeviceBean?.let { ble ->
            mWiFiBean?.let {
                sendPasswordStart()
                val cmdByteArray = SRBleCmdUtil.instance.setConnectWiFi(it.mac, "", it.auth_type)
                SRBleUtil.instance.writeData(ble.bleDevice, cmdByteArray)
            }
        }
    }

    private fun savePassword() {
        val wifiPassword = mViewBinding.ilAddWifiPwdPassword.etInputContent.text.toString()

        mBleTrackDeviceBean?.apply {
            //判断是否有蓝牙连接
            if (BleManager.getInstance().isConnected(bleDevice)) {
                mWiFiBean?.let {
                    lifecycleScope.launch {
                        sendPasswordStart()
                        val cmdByteArray =
                            SRBleCmdUtil.instance.setConnectWiFi(it.mac, wifiPassword, it.auth_type)
                        LogUtil.e(
                            "长度=${cmdByteArray.size}，要发送的包：" + HexUtil.formatHexString(
                                cmdByteArray, true
                            )
                        )
                        //发送第一个包
                        if (cmdByteArray.size > 20) {
                            SRBleUtil.instance.writeData(bleDevice, cmdByteArray.sliceArray(0..19))
                        } else SRBleUtil.instance.writeData(bleDevice, cmdByteArray)
                        for (i in 1 until SRBleCmdUtil.instance.byteToInt(cmdByteArray[2])) {
                            var cmdPackage = cmdByteArray.sliceArray(0..2)
                            //当前的包序号
                            cmdPackage = cmdPackage.plus((i + 1).toByte())
                            val startIndex = 20 + 16 * (i - 1)
                            cmdPackage = if (cmdByteArray.size - 20 - 16 * (i - 1) > 16) {
                                cmdPackage.plus(cmdByteArray.sliceArray(startIndex until 20 + 16 * i))
                            } else cmdPackage.plus(cmdByteArray.sliceArray(startIndex until cmdByteArray.size))

                            delay(500)
                            SRBleUtil.instance.writeData(bleDevice, cmdPackage)
                        }
                    }
                }
            } else showToast(R.string.tracker_manage_set_ble_unconnect, gravity = Gravity.CENTER)
        }
    }

    private fun goEditWifiActivity() {
        Util.checkLocationPermissionsGpsEnabled(this, {
            val intent = Intent(mContext, EditWifiPowerZoneActivity::class.java)
            intent.putExtra(ConstantString.WiFi, mWiFiBean)
            mDecWiFiAddressData?.let {
                intent.putExtra(ConstantString.HistoryDataBean, it)
            }
            intent.putExtra(ConstantString.isFirstBind, isFirstBind)
            intent.putExtra(ConstantString.Pet, mPetBean)
            intent.putExtra(ConstantString.Latitude, mPetCurrentLat)
            intent.putExtra(ConstantString.Longitude, mPetCurrentLon)
            val pws = mViewBinding.ilAddWifiPwdPassword.etInputContent.text.toString()
            intent.putExtra(ConstantString.Password, pws)
            startActivityFinish(intent)
        })
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ilAddWifiPwdPassword.ivInputRepresentImage -> {
                    isShowPassword = !isShowPassword
                    ViewUtil.instance.showAndHidePasswordClick(
                        ilAddWifiPwdPassword.etInputContent,
                        ilAddWifiPwdPassword.ivInputRepresentImage,
                        isShowPassword
                    )
                }

                btnAddWifiPwdSkip -> goEditWifiActivity()

                btnAddWifiPwdConnect -> mWiFiBean?.let {
                    if (it.auth_type == ConstantInt.Type0) noPasswordConnect()
                    else savePassword()
                }
            }
        }
    }
}