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

import android.animation.AnimatorSet
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.view.Gravity
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
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.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.WiFiListAdapter
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.bean.WiFiBleListBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.databinding.ActivityAddWifiPowerZone3Binding
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.google.gson.Gson
import com.hjq.permissions.permission.PermissionLists
import java.util.Locale


class AddWifiPowerZone3Activity :
    BaseActivity<ActivityAddWifiPowerZone3Binding>(ActivityAddWifiPowerZone3Binding::inflate) {

    private val mCountDownTimerViewModel: CountDownTimerViewModel by viewModels()
    private lateinit var mWifiManager: WifiManager
    private lateinit var mWiFiListAdapter: WiFiListAdapter

    //解析后json数据
    private var mReceiveWifiJsonData = ""

    private lateinit var mGson: Gson

    private var mBleTrackDeviceBean: BleTrackDeviceBean? = null

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

    private var mAnimatorSet: AnimatorSet? = null
    private var mWifiList = mutableListOf<WiFiBean>()

    override fun getTopBar() = mViewBinding.ilAddWifiZone3TopBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle("")
        setLeftBackImage(R.drawable.icon_white_back_svg)
        mRightImageButton = addRightImageButton(R.drawable.icon_refresh)

        intent.extras?.apply {
            mDecWiFiAddressData = Util.getParcelableAdaptive(
                intent, ConstantString.HistoryDataBean, HistoryDataBean::class.java
            )
            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 (null == mPetBean) finish()

        mGson = Gson()
        mWifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        mViewBinding.apply {
            mWiFiListAdapter = WiFiListAdapter(mContext, null).apply {
                setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        goSetWifiPassword(pos)
                    }
                })
            }
            ViewUtil.instance.setRecyclerViewDecorationLinearLayoutManager(
                mContext, rvAddWifiZone3WifiNetwork, mWiFiListAdapter
            )
            lavAddWifiZone3Anim.setAnimation("lottie/dfu_loading.json")
        }

        //查找是否连接了蓝牙
        mPetBean?.apply {
            SRBleUtil.instance.getConnectMacDevice(macID)?.let {
                updateConState(it)
            }

            if (BleManager.getInstance().isConnected(macID)) {
                sendWiFiCmd()
            } else {
                showToast(R.string.tracker_manage_set_ble_unconnect, gravity = Gravity.CENTER)
            }
        }

//        checkPermission()
    }

    private fun sendWiFiCmd() {
        mBleTrackDeviceBean?.apply {
            //判断是否有蓝牙连接
            if (BleManager.getInstance().isConnected(bleDevice)) {
                showLoading(true, R.string.txt_please_wait)
                mRightImageButton?.let {
                    it.isEnabled = false
                    mCountDownTimerViewModel.stopCountDown()
                    mCountDownTimerViewModel.startCountDown(15)
                    mAnimatorSet = ViewUtil.instance.viewRotationAnimator(it, true)
                    mViewBinding.rvAddWifiZone3WifiNetwork.visibility = View.GONE
                    mViewBinding.lavAddWifiZone3Anim.playAnimation()
                    mViewBinding.lavAddWifiZone3Anim.visibility = View.VISIBLE
                }
                mWiFiListAdapter.setData(null)
                SRBleUtil.instance.writeData(
                    bleDevice, SRBleCmdUtil.instance.getWiFiZoneList()
                )
            } else showToast(R.string.tracker_manage_set_ble_unconnect, gravity = Gravity.CENTER)
        }
    }

    override fun liveDataObserve() {
        mCountDownTimerViewModel.mCountDownEndLiveData.observe(this) {
            showToast(R.string.txt_time_out_try_again, true)
        }
        //添加成功结束页面
        XEventBus.observe(this, EventName.RefreshWiFiZone) {
            finish()
        }

        //接收蓝牙连接状态
        XEventBus.observe(
            this, EventName.ConnectDeviceState
        ) { trackBleDevice: BleTrackDeviceBean ->
            mPetBean?.apply {
                if (trackBleDevice.mac == macID) {
                    updateConState(trackBleDevice)
                }
            }
        }

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

    private fun goSetWifiPassword(pos: Int) {
        if (mWiFiListAdapter.getData().isNotEmpty()) {
            val wiFiBean = mWiFiListAdapter.getData()[pos]
            val intent = Intent(mContext, EditWifiPowerZoneActivity::class.java)
//            val intent = Intent(mContext, AddWifiPasswordActivity::class.java)
            intent.putExtra(ConstantString.WiFi, wiFiBean)
            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)
            startActivity(intent)
        }
    }

    /**
     * 解析蓝牙返回的数据
     */
    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 == 0x0F && data1 == 0x00) {
                if (data2 == 0) {
                    val data3 = SRBleCmdUtil.instance.byteToInt(data[3])
                    val data4 = SRBleCmdUtil.instance.byteToInt(data[4])
                    //当前第一个包
                    if (data4 == 1) {
                        mReceiveWifiJsonData = ""
                    }

                    val dataLength = data[5]
                    // 截取byteArray的子数组，从索引start到end-1
                    val start = 6 // 截取开始的索引
                    val end = start + dataLength // 截取结束的索引（不包括）
                    val subArray = data.sliceArray(start until end)
                    val byteToString = subArray.decodeToString()
                    mReceiveWifiJsonData += byteToString

                    //最后一个包
                    if (data3 == data4) {
                        mAnimatorSet?.cancel()
                        mRightImageButton?.isEnabled = true
                        LogUtil.e("接受到的完整JSON字符串：$mReceiveWifiJsonData")
                        // 定义TypeToken来表示Item类型的列表
//                val itemType = object : TypeToken<MutableList<WiFiBean>>() {}.type
//                val wifiList = mGson.fromJson<MutableList<WiFiBean>>(
//                    mGson.toJson(mReceiveWifiJsonData),
//                    itemType
//                )
                        try {
                            val wifiList = mGson.fromJson(
                                mReceiveWifiJsonData, WiFiBleListBean::class.java
                            )
                            mPetBean?.let {
                                mWifiList = wifiList.wifi
                                if (it.deviceType == ConstantInt.Type2) {
                                    checkPermission()
                                } else {
                                    showWifiData(mWifiList)
                                }
                            }

                        } catch (_: Exception) {
                            sendWiFiCmd()
                        }
                    }
                } else {
                    mAnimatorSet?.cancel()
                    mRightImageButton?.isEnabled = true
                    showToast(R.string.txt_time_out_try_again, true)
                }
            }
        }
    }

    private fun showWifiData(list: MutableList<WiFiBean>) {
        mCountDownTimerViewModel.stopCountDown()
        mWiFiListAdapter.setData(list, true)
        showLoading(false)
        mViewBinding.rvAddWifiZone3WifiNetwork.visibility = View.VISIBLE
        mViewBinding.lavAddWifiZone3Anim.cancelAnimation()
        mViewBinding.lavAddWifiZone3Anim.visibility = View.GONE
    }

    /**
     * 更新设备连接状态
     */
    private fun updateConState(trackBleDevice: BleTrackDeviceBean) {
        mBleTrackDeviceBean = trackBleDevice
        if (trackBleDevice.conState == ConState.CONNECTED) {
//            showToast(R.string.tracker_manage_set_ble_connect)
        } else {
            showToast(R.string.tracker_manage_set_ble_unconnect, gravity = Gravity.CENTER)
        }
    }

    private fun checkPermission() {
        //从 Android 6.0（API 23）开始，定位权限现在被用于 Wi-Fi 扫描
        Util.checkPermissions(
            this, object : Util.RequestPermissionCallback {
                override fun onRequestPermissionSuccess() {
                    addListData()
                }

                override fun onRequestPermissionFail() {
                    showToast(R.string.permissions_die_easy_photos)
                }
            }, "wifi", PermissionLists.getAccessFineLocationPermission()
        )
    }

    private fun addListData() {
        val list = getConnectedWifiSSID()
        val wifiList = mutableListOf<WiFiBean>()
        if (!list.isNullOrEmpty()) {
            for (bleWifi in mWifiList) {
                for (wifi in list) {
                    if (bleWifi.mac.uppercase(Locale.getDefault()) == wifi.BSSID.uppercase(Locale.getDefault())) {
                        val wifiName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                            wifi.wifiSsid.toString()
                        } else {
                            wifi.SSID
                        }
                        bleWifi.name = wifiName.replace("\"", "")
                        wifiList.add(bleWifi)
                        break
                    }
                }
            }
        }
        if (wifiList.size > 0) {
            showWifiData(wifiList)
        } else {
            showToast(R.string.txt_time_out_try_again, true)
        }
    }


    /**
     * 接收开启wifi操作
     */
    private val mActivityResultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            checkPermission()
        }

    @SuppressLint("MissingPermission")
    private fun getConnectedWifiSSID(): MutableList<ScanResult>? {
        // 首先，你需要开启WiFi扫描
        if (mWifiManager.isWifiEnabled) {
            val scanResults = mWifiManager.scanResults
            scanResults.sortBy { -it.level }
            return scanResults
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                val intent = Intent(Settings.Panel.ACTION_WIFI)
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                startActivity(intent)
                val intent = Intent(Settings.Panel.ACTION_WIFI)
                launchActivity(mActivityResultLauncher, intent)
            } else {
                mWifiManager.isWifiEnabled = true
            }
        }
        return null
    }


    override fun onClick(v: View?) {
        when (v!!) {
            mRightImageButton -> sendWiFiCmd()
        }
    }
}