package com.zj365.health.act.binddevice

import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.lifesense.android.ble.core.application.ConnectionStateReceiver
import com.lifesense.android.ble.core.application.model.enums.ConnectionState
import com.lifesense.android.ble.core.serializer.AbstractMeasureData
import com.lifesense.android.ble.device.fatscale.model.WeightMeasureData
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.bracelet.checkBlueConnectPermission
import com.xty.common.bracelet.getBluePermission
import com.xty.common.event.MeasureWeightEvent
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.CommonUtils
import com.zj365.health.R
import com.zj365.health.act.datamanage.DataManageTypeAct
import com.zj365.health.adapter.binddevice.BindBodyFatAdapter
import com.zj365.health.vm.BindDeviceListVm
import com.zj365.health.weight.UnBindDialog
import com.xty.network.model.BindDeviceListBean
import com.zj365.health.BuildConfig
import io.reactivex.functions.Consumer
import org.greenrobot.eventbus.EventBus

/**
 * 绑定体脂秤列表
 */
@Route(path = ARouterUrl.BODY_FAT_BIND_LIST)
class BodyFatDeviceBindListAct : BaseDeviceBindListAct<BindDeviceListVm>(),
    ConnectionStateReceiver, Consumer<AbstractMeasureData> {

    private val mFatAdapter by lazy { BindBodyFatAdapter() }
    private var clickDevice: BindDeviceListBean? = null
    private var userId: String? = null
    private var isMe = false
    var unBindDialog: UnBindDialog? = null

    override fun initAdapter() {
        setRecycleRefresh(binding.mRecycle, binding.mRefresh)
        binding.mRecycle.layoutManager = LinearLayoutManager(this)
        binding.mRecycle.adapter = mFatAdapter
        mFatAdapter.setEmptyView(this.getNoneView())

        mFatAdapter.addChildClickViewIds(R.id.tvBindButton)
        mFatAdapter.setOnItemChildClickListener { adapter, view, position ->
            clickDevice = adapter.data[position] as BindDeviceListBean
            clickDevice?.apply {
                unBindDialog?.show()
            }
        }

//        mFatAdapter.setOnItemChildClickListener { adapter, view, position ->
//            RouteManager.goAct(ARouterUrl.BODY_FAT_USER_INFO)
//        }
    }

    override fun initView() {
        super.initView()
        binding.title.mTvTitle.text = "体脂秤"

        if (!checkBlueConnectPermission(this)) {
            getBluePermission(this) {
                if (it) {
                    //体脂秤sdk初始化
                    initBleSDK()
                } else {
                    return@getBluePermission
                }
            }
        } else {
            // 获取 BluetoothAdapter
            val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            if (!bluetoothAdapter.isEnabled) {
                // 如果蓝牙未启用，请求用户启用蓝牙
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(enableBtIntent, 10001)
            } else {
                if (BlueUtil.getBlueManage().isInitialized) {
                    BlueUtil.getBlueManage().registerConnectionStatusReceiver(this)
                } else {
                    initBleSDK()
                }
            }

        }

        if (!isMe) {
            binding.tvBindDeviceImdiatly.isEnabled = false
        }
        unBindDialog = UnBindDialog(this) {
            mViewModel.unBind(clickDevice?.sn, clickDevice?.mac, "")
        }
        mFatAdapter.isMe = isMe
    }

    private fun initBleSDK() {

        BlueUtil.getBlueManage().setDebug(BuildConfig.isRelease)
        BlueUtil.getBlueManage()
            .init(
                this,
                "lx1f367d71ff67ca73",
                "a713f5e2fa03ec19476a3ac96287c4645986c4c6",
                null,
                this
            )
        mViewModel.getBindList(DeviceType.BODYFAT.type)
    }


    override fun initData() {
        super.initData()
        userId = intent.getStringExtra("userId").toString()
        isMe = userId.isNullOrEmpty() || userId == CommonUtils.getMyUserId()
    }

    override fun loadData() {
        mViewModel.getBindList(DeviceType.BODYFAT.type, userId)
    }

    override fun goToBind() {
        RouteManager.goAct(ARouterUrl.BODY_FAT_DEVICE_SEARCH, null)
    }

    override fun goToHistoryList() {
        bundle.clear()
        if (userId.isNullOrEmpty()) {
            userId = CommonUtils.getMyUserId()
        }
        bundle.putString("userId", userId)
        bundle.putString(DataManageTypeAct.dataType, "3")
        bundle.putString(DataManageTypeAct.exceptionKey, "体脂历史数据")
        RouteManager.goAct(ARouterUrl.BODY_FAT_BIND_CHAT, bundle)
    }

    override fun onConnectionStateChange(p0: String?, p1: ConnectionState?) {
        mFatAdapter.notifyDataSetChanged()
    }

    override fun liveObserver() {
        super.liveObserver()
        mViewModel.list.observe(this) {
            //进行自动连接设置mac地址
            try {
                if (BlueUtil.getBlueManage().isInitialized) {
                    it.data.forEach {
                        BlueUtil.getBlueManage().addBondedMac(it.mac)
                    }
                    BlueUtil.getBlueManage().connectBondedDevices()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            setDate(mFatAdapter, it.data)
        }

        mViewModel.unbindLive.observe(this) {
            CommonToastUtils.showSucceedToast("解绑成功")
            clickDevice?.apply {
                mFatAdapter.remove(this)
                BlueUtil.getBlueManage().unBind(mac)
            }
        }

        mViewModel.boundDevices.observe(this) {
            if (BlueUtil.getBlueManage().isInitialized) {
                it.data.forEach {
                    BlueUtil.getBlueManage().addBondedMac(it.mac)
                }
                BlueUtil.getBlueManage().connectBondedDevices()
            }
        }
    }

    override fun accept(abstractMeasureData: AbstractMeasureData?) {
        if (abstractMeasureData is WeightMeasureData) {
            if (!abstractMeasureData.isProcessingData) {
                Log.i("LS-Bluetooth", "收到测量过程数据:${JSON.toJSONString(abstractMeasureData)}")
                val deviceInfo = abstractMeasureData.deviceInfo
                mViewModel.saveWeight(
                    abstractMeasureData.weight,
                    abstractMeasureData.resistance50K,
                    deviceInfo.sn,
                    deviceInfo.mac
                )
                EventBus.getDefault()
                    .post(MeasureWeightEvent(JSON.toJSONString(abstractMeasureData)))
                return
            }
        }
    }
}