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

import android.annotation.SuppressLint
import android.content.Intent
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
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.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.SelectFencesTypeCardShadeAdapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.BleTrackDeviceBean
import com.abbidot.tracker.bean.DataBean
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.bean.WiFiZoneBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.databinding.ActivityEditPowerZoneBinding
import com.abbidot.tracker.ui.activity.HomeV2Activity
import com.abbidot.tracker.ui.common.map.EditWifiZoneMapCommon
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.WiFiZoneViewModel
import com.clj.fastble.BleManager


class EditWifiPowerZoneActivity :
    BaseActivity<ActivityEditPowerZoneBinding>(ActivityEditPowerZoneBinding::inflate) {

    private val mWiFiZoneViewModel: WiFiZoneViewModel by viewModels()
    private val mConnectionDeviceViewModel: ConnectionDeviceViewModel by viewModels()

    private lateinit var mSelectTypeShadeAdapter: SelectFencesTypeCardShadeAdapter
    private var mWiFiBean: WiFiBean? = null

    private lateinit var mWiFiZoneBean: WiFiZoneBean

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

    private lateinit var mEditZoneMapCommon: EditWifiZoneMapCommon
    private lateinit var mFragment: Fragment

    private var mShowCenterLocationType = ConstantInt.OtherLocationType

    //是否是编辑
    private var isEdit = false
    private var isFirstBind = false
    private var mBleTrackDeviceBean: BleTrackDeviceBean? = null

    //禁用模式,无法点击的情况
    private var isDisabledMode = false

    //冻结点击
    private var isBlockedClick = false

    override fun getTopBar() = mViewBinding.editPowerZoneTopBar.titleTopBar

    @SuppressLint("ClickableViewAccessibility")
    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_edit_power_zone)
        setLeftBackImage(R.drawable.icon_white_back_svg)

        initWifiData()

        if (isEdit) {
            mRightImageButton = if (isDisabledMode) {
                mViewBinding.ilEditPowerZoneBluetoothTips.root.visibility = View.GONE
                addRightImageButton(R.drawable.icon_grey_delete, false)
            } else {
                addRightImageButton(R.drawable.icon_gray_delete_svg)
            }
        }

        mEditZoneMapCommon = EditWifiZoneMapCommon()
        mFragment = mEditZoneMapCommon.getMapFragment(mContext, mWiFiZoneBean) { mapLoadOk() }

        mViewBinding.apply {
            ilWifiNameInputLayout.tvInputNameTitle.text = getString(R.string.txt_zone_name)
//            ViewUtil.instance.setMapSwitchLocationButtonImage(
//                ivEditWifiZoneRefreshBtn, mShowCenterLocationType
//            )
            setOnClickListenerViews(
                ivEditWifiZoneRefreshBtn,
                btnSaveWifiZone,
                ivEditWifiZoneMapTypeBtn,
                btnCancelWifiZone,
                ilEditPowerZoneBluetoothTips.trbBleConnectState
            )
            rvEditWifiZoneType.setOnTouchListener { v, _ ->
                v?.let { hideInputMethod(it) }
                false
            }

            setListData()

            ViewUtil.instance.setRecyclerViewFlexboxLayout(
                mContext, rvEditWifiZoneType, mSelectTypeShadeAdapter, right = AppUtils.dpToPx(8)
            )

            supportFragmentManager.commit {
                add(R.id.fc_edit_power_zone_map_fragment, mFragment)
            }

//            setListenKeyboardChange(600)

            if (null != mBleTrackDeviceBean) {
                ilEditPowerZoneBluetoothTips.trbBleConnectState.let {
                    it.setBackgroundColor(ContextCompat.getColor(mContext, R.color.cyan_color1))
                    it.text = getString(R.string.tracker_manage_set_ble_connect)
                }
            }
        }
    }

    override fun leftBackOnClick() {
        if (isBlockedClick) return
        super.leftBackOnClick()
    }

    override fun liveDataObserve() {
        //接收蓝牙返回数据
        XEventBus.observe(this, EventName.DeviceReceiveData) { receiveData: ReceiveDeviceData ->
            mPetBean?.apply {
                if (macID == receiveData.mac) {
                    val data = receiveData.data
                    parseData(data)
                }
            }
        }
        //接收蓝牙连接状态
        XEventBus.observe(this, EventName.ConnectDeviceState) { trackDevice: BleTrackDeviceBean ->
            showLoading(false)
            mViewBinding.ilEditPowerZoneBluetoothTips.trbBleConnectState.let { view ->
                val bgColor = if (trackDevice.conState == ConState.CONNECTED) {
                    view.text = getString(R.string.tracker_manage_set_ble_connect)
                    mPetBean?.let {
                        //查找当前Mac的设备
                        mBleTrackDeviceBean = SRBleUtil.instance.getConnectMacDevice(it.macID)
                    }
                    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)
            }
        }

        //搜索蓝牙的设备状态
        XEventBus.observe(this, EventName.ActionConDeviceState) { conState: Int ->
            mViewBinding.ilEditPowerZoneBluetoothTips.trbBleConnectState.let { view ->
                ViewUtil.instance.bleConActionState(this, view, conState, Gravity.CENTER)
            }
        }

        mWiFiZoneViewModel.apply {
            mAddWiFiZoneLiveData.observe(this@EditWifiPowerZoneActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        XEventBus.post(EventName.RefreshWiFiZone)
                        if (isFirstBind) {
                            showToast(R.string.txt_add_successful, gravity = Gravity.CENTER)
                            mViewBinding.root.postDelayed({
                                startActivityFinish(
                                    Intent(
                                        mContext, HomeV2Activity::class.java
                                    )
                                )
                            }, 1500)
                        } else {
                            showToast(R.string.txt_add_successful, true, gravity = Gravity.CENTER)
                        }
                    }

                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        isBlockedClick = false
                    }
                })
            }

            mUpdateWiFiZoneLiveData.observe(this@EditWifiPowerZoneActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        XEventBus.post(EventName.RefreshWiFiZone)
                        showToast(R.string.txt_change_successful, true, gravity = Gravity.CENTER)
                    }
                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        isBlockedClick = false
                    }
                })
            }

            mDeleteWiFiZoneLiveData.observe(this@EditWifiPowerZoneActivity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        XEventBus.post(EventName.DeleteWiFiZone)
                        showToast(R.string.txt_delete_success, true, gravity = Gravity.CENTER)
                    }
                    override fun onRequestError(exceptionCode: String?) {
                        super.onRequestError(exceptionCode)
                        isBlockedClick = false
                    }
                })
            }
        }
    }

    /**
     * 地图加载好了
     */
    private fun mapLoadOk() {
        mWiFiZoneBean.apply {
            mEditZoneMapCommon.setShowWifiLocation(latitude, longitude, false)
//            mPetBean?.let {
//                mEditZoneMapCommon.setPetLatLon(
//                    it.imgurl, it.petType, mPetCurrentLat, mPetCurrentLon
//                )
//            }
        }
    }

    private fun initWifiData() {
        var pws = ""
        intent.extras?.apply {
            isFirstBind = getBoolean(ConstantString.isFirstBind, false)
            isDisabledMode = getBoolean(ConstantString.isCheck, false)
            pws = getString(ConstantString.Password, "")
            //设备里的wifi数据,添加使用到
            mWiFiBean =
                Util.getParcelableAdaptive(intent, ConstantString.WiFi, WiFiBean::class.java)
            //选地址页面的数据
            val decPetAddressData = Util.getParcelableAdaptive(
                intent, ConstantString.HistoryDataBean, HistoryDataBean::class.java
            )
            //宠物相关数据，包括deviceId
            mPetBean = Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)
            //编辑传过来的wiFiZone数据
            val wiFiZoneBean = Util.getParcelableAdaptive(
                intent, ConstantString.WiFiZone, WiFiZoneBean::class.java
            )
            if (null == wiFiZoneBean) {
                isEdit = false
                mWiFiZoneBean = WiFiZoneBean()
                decPetAddressData?.let {
                    mWiFiZoneBean.address = it.address
                    mWiFiZoneBean.latitude = it.latitude
                    mWiFiZoneBean.longitude = it.longitude
                }
            } else {
                isEdit = true
                mWiFiZoneBean = wiFiZoneBean
            }
            mPetBean?.let {
                mWiFiZoneBean.deviceId = it.deviceId
                //查找当前Mac的设备
                mBleTrackDeviceBean = SRBleUtil.instance.getConnectMacDevice(it.macID)
                if (null != mBleTrackDeviceBean) isDisabledMode = false
            }

            mPetCurrentLat = getDouble(ConstantString.Latitude, 0.0)
            mPetCurrentLon = getDouble(ConstantString.Longitude, 0.0)
        }

        mWiFiZoneBean.apply {
            mWiFiBean?.let {
                wifiName = it.name
                wifiMac = it.mac
                wifiAuth = it.auth_type
                wifiPass = pws
                wifiZoneName = getString(R.string.txt_home)
            }
            mViewBinding.let {
                it.tvWifiNameContent.text = wifiName
                it.tvWifiGpsLocation.text = address
                it.ilWifiNameInputLayout.etInputContent.setText(wifiZoneName)
                it.tvWifiGpsLocation.text = address
            }
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        mViewBinding.apply {
            ViewUtil.instance.setMapViewBottomMarginOverlap(
                rlEditPowerZoneMapLayout, rlEditWifiInfoLayout.height, AppUtils.dpToPx(20)
            )
        }
    }

    private fun setListData() {
        val typeList = mutableListOf<DataBean>()
        DataBean().apply {
            imageId = R.drawable.icon_wifi_zone_home_type_svg
            typeList.add(this)
        }
        DataBean().apply {
            imageId = R.drawable.icon_wifi_zone_office_type_svg
            typeList.add(this)
        }
        mSelectTypeShadeAdapter = SelectFencesTypeCardShadeAdapter(mContext, typeList).apply {
            setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                override fun onItemClick(itemView: View?, pos: Int) {
                    hideInputMethod(mViewBinding.root)
                    ViewUtil.instance.updateDataBeanOnlySelectedItem(
                        mSelectTypeShadeAdapter, typeList, pos
                    )
                    if (mWiFiZoneBean.type == pos + 1) return
                    mWiFiZoneBean.type = pos + 1
                    mViewBinding.apply {
                        ilWifiNameInputLayout.let {
                            val zoneName = it.etInputContent.text.toString()
                            if (TextUtils.isEmpty(zoneName)) {
                                val name = if (pos == 0) getString(R.string.txt_home)
                                else getString(R.string.txt_office)
                                mWiFiZoneBean.wifiZoneName = name
                                it.etInputContent.setText(name)
                            } else if (zoneName == getString(R.string.txt_home)) {
                                val name = getString(R.string.txt_office)
                                mWiFiZoneBean.wifiZoneName = name
                                it.etInputContent.setText(name)
                            } else if (zoneName == getString(R.string.txt_office)) {
                                val name = getString(R.string.txt_home)
                                mWiFiZoneBean.wifiZoneName = name
                                it.etInputContent.setText(name)
                            }
                        }
                    }
                }
            })
        }

        ViewUtil.instance.updateDataBeanOnlySelectedItem(
            mSelectTypeShadeAdapter, typeList, mWiFiZoneBean.type - 1
        )
    }

    private fun saveWiFiZone() {
        if (isBlockedClick) return
        val name = mViewBinding.ilWifiNameInputLayout.etInputContent.text.toString()
        if (!TextUtils.isEmpty(name)) {
            mWiFiZoneBean.wifiZoneName = name
        }
        isBlockedClick = true
        if (isEdit) {
            mWiFiZoneViewModel.updateWifiZone(this, mWiFiZoneBean)
        } else {
            sendAddWiFiZoneCmd()
        }
    }

    private fun deleteWifiZone() {
        if (isBlockedClick) return
        if (isDisabledMode) return
        if (null == mBleTrackDeviceBean) {
            showToast(R.string.tracker_manage_set_ble_unconnect, gravity = Gravity.CENTER)
            return
        }
        ViewUtil.instance.showDialog(
            mContext, R.string.txt_delete_tips, object : BaseDialog.OnDialogOkListener {
                override fun onOkClick(dialog: BaseDialog<*>) {
                    dialog.dismiss()
                    isBlockedClick = true
                    sendDeleteWiFiZoneCmd()
                }
            }, okTextResId = R.string.txt_sure
        )
    }

    /**
     * 解析数据
     */
    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 == 0x10 || data0 == 0x11) {
                if (data1 == 0x01 && data2 == 0x00) {
                    //添加wifi 指令成功
                    if (data0 == 0x10) {
                        LogUtil.e("设置设备wifi指令成功")
                        mWiFiZoneViewModel.addWifiZone(this, mWiFiZoneBean)
                    }
                    //删除成功
                    else {
                        LogUtil.e("删除设备wifi指令成功")
                        mWiFiZoneViewModel.deleteWifiZone(
                            this@EditWifiPowerZoneActivity, mWiFiZoneBean
                        )
                    }
                } else if (data1 == 0x01 && data2 == 0x01) {
                    showLoading(false)
                    mRightImageButton?.isEnabled = true
                    setButtonEnabled(mViewBinding.btnSaveWifiZone, ConstantInt.Type1)
                    isBlockedClick = false
                    showToast(R.string.txt_duplicate_wifi_not, gravity = Gravity.CENTER)
                } else {
                    mRightImageButton?.isEnabled = true
                    setButtonEnabled(mViewBinding.btnSaveWifiZone, ConstantInt.Type1)
                    showLoading(false)
                    isBlockedClick = false
                    showToast("Fail", gravity = Gravity.CENTER)
                    LogUtil.e("设备wifi指令失败")
                }
            }
        }
    }


    /**
     * 添加WiFi指令
     */
    private fun sendAddWiFiZoneCmd() {
        senCmd(SRBleCmdUtil.instance.setWiFiZone(mWiFiZoneBean))
    }

    /**
     * 删除WiFi指令
     */
    private fun sendDeleteWiFiZoneCmd() {
        senCmd(SRBleCmdUtil.instance.deleteWiFiZone(mWiFiZoneBean.wifiMac))
    }

    private fun senCmd(cmd: ByteArray) {
        if (null == mBleTrackDeviceBean) {
            showToast(R.string.tracker_manage_set_ble_unconnect, gravity = Gravity.CENTER)
            return
        }
        mBleTrackDeviceBean?.apply {
            //判断是否有蓝牙连接
            if (BleManager.getInstance().isConnected(bleDevice)) {
                showLoading(true, R.string.txt_please_wait)
                mRightImageButton?.isEnabled = false
                setButtonEnabled(mViewBinding.btnSaveWifiZone, ConstantInt.Type0)
                SRBleUtil.instance.writeData(bleDevice, cmd)
            } else {
                showToast(R.string.tracker_manage_set_ble_unconnect, gravity = Gravity.CENTER)
            }
        }
    }

    /**
     * 手动连接/断开设备
     */
    private fun connectionBtn(btnString: String) {
        mPetBean?.apply {
            if (btnString == getString(R.string.tracker_manage_set_ble_unconnect)) {
                if (isFirstBind) mConnectionDeviceViewModel.connectDeviceToDeviceOutId(
                    this@EditWifiPowerZoneActivity, deviceOutId
                )
                else mConnectionDeviceViewModel.connectDeviceToMac(
                    this@EditWifiPowerZoneActivity, macID
                )
            } else if (btnString == getString(R.string.tracker_manage_set_ble_connect)) {
//                ViewUtil.instance.operateDialogTips(mContext, R.string.txt_disconnect_tips) {
//                    if (isFirstBind) {
//                        BleManager.getInstance().disconnectAllDevice()
//                    } else {
//                        SRBleUtil.instance.disconnectToMac(macID)
//                    }
//                }
            }
        }
    }

    override fun onClick(v: View?) {
        if (isLimitClick()) return
        mViewBinding.apply {
            hideInputMethod(root)
            when (v!!) {
                ivEditWifiZoneRefreshBtn -> {
                    mWiFiZoneBean.let {
                        when (mShowCenterLocationType) {
                            ConstantInt.PetLocationType -> {
                                mShowCenterLocationType = ConstantInt.UserLocationType
                            }

                            ConstantInt.UserLocationType -> {
                                mShowCenterLocationType = ConstantInt.OtherLocationType
                            }

                            ConstantInt.OtherLocationType -> {
                                mShowCenterLocationType =
                                    if (mPetCurrentLat == 0.0 && mPetCurrentLon == 0.0) {
                                        ConstantInt.UserLocationType
                                    } else {
                                        ConstantInt.PetLocationType
                                    }
                            }
                        }
                        mEditZoneMapCommon.switchShowLocation(
                            mShowCenterLocationType, it.latitude, it.longitude
                        )
                        ViewUtil.instance.setMapSwitchLocationButtonImage(
                            ivEditWifiZoneRefreshBtn, mShowCenterLocationType
                        )
                    }
                }

                ivEditWifiZoneMapTypeBtn -> mEditZoneMapCommon.switchSatelliteAndNormalMapType()

                btnSaveWifiZone -> saveWiFiZone()
                mRightImageButton -> deleteWifiZone()
                btnCancelWifiZone -> {
                    if (isBlockedClick) return
                    if (isFirstBind) {
                        finish()
                    } else {
                        if (!isEdit) XEventBus.post(EventName.RefreshWiFiZone)
                        finish()
                    }
                }

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