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

import android.content.Intent
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
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.AssignOptionsAdapter
import com.abbidot.tracker.adapter.MyTrackerV2Adapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDialog
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.bean.DeviceBean
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.database.MyDatabase
import com.abbidot.tracker.databinding.ActivityMyTrackerV2Binding
import com.abbidot.tracker.ui.activity.pet.PetProfileActivity
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.PetRelationViewModel
import com.abbidot.tracker.vm.TrackerInfoViewModel
import com.abbidot.tracker.vm.TrackerSetViewModel
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MyTrackerV2Activity :
    BaseActivity<ActivityMyTrackerV2Binding>(ActivityMyTrackerV2Binding::inflate) {

    private val mTrackerViewModel: TrackerInfoViewModel by viewModels()
    private val mTrackerSetViewModel: TrackerSetViewModel by viewModels()
    private val mPetRelationViewModel: PetRelationViewModel by viewModels()

    private lateinit var mMyTrackerAdapter: MyTrackerV2Adapter
    private lateinit var mAssignOptionsAdapter: AssignOptionsAdapter

    private var mQMUIBottomSheet: QMUIBottomSheet? = null

    private lateinit var mUnAssignPetList: MutableList<PetBean>
    private lateinit var mUnAssignDeviceList: MutableList<DeviceBean>

    //当前操作的DeviceBean下标
    private var mCurrentBeanOption = 0

    //是底部弹窗跳转添加的
    private var isShowBottomSheetAdd = false

    //是否只有绑定一个的设备
    private var isOnlyBindOneDevice = false

    override fun getTopBar() = mViewBinding.ilMyTrackerV2TopBar.titleTopBar

    override fun initData() {
        //刷新下邀请家人的数据
        XEventBus.post(EventName.RefreshHomeList)
        super.initData()
        setTopBarTitle(R.string.tracker_manage_mine)
        setLeftBackImage(R.drawable.icon_white_back_svg)

        mUnAssignPetList = mutableListOf()
        mUnAssignDeviceList = mutableListOf()

        mViewBinding.apply {
            val trackerList = mutableListOf<DeviceBean>()
            trackerList.add(DeviceBean())
            mMyTrackerAdapter = MyTrackerV2Adapter(mContext, trackerList)
            ViewUtil.instance.setRecyclerViewVerticalLinearLayout(
                mContext,
                rvMyTrackerV2List,
                mMyTrackerAdapter,
                top = AppUtils.dpToPx(10),
                bottom = AppUtils.dpToPx(10)
            )

            mAssignOptionsAdapter = AssignOptionsAdapter(mContext, null).apply {
                setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                    override fun onItemClick(itemView: View?, pos: Int) {
                        val dataBean = mAssignOptionsAdapter.getData()[pos]
                        if (pos == 0) {
                            isShowBottomSheetAdd = true
                            //处理设备类型
                            if (dataBean.menuType == ConstantInt.SpecialType) {
                                startActivity(Intent(mContext, AddNewTracker1Activity::class.java))
                            } else {
                                startActivity(Intent(mContext, PetProfileActivity::class.java))
                            }
                        } else {
                            //关联其他宠物/设备
                            val device = mMyTrackerAdapter.getData()[mCurrentBeanOption]
                            if (dataBean.menuType == ConstantInt.SpecialType) {
                                if (TextUtils.isEmpty(device.deviceOutId)) {
                                    mPetRelationViewModel.bindPet(
                                        this@MyTrackerV2Activity, dataBean.id, device.pet?.petId!!
                                    )
                                } else mTrackerSetViewModel.assignOtherPetTracker(
                                    this@MyTrackerV2Activity,
                                    device.pet?.petId!!,
                                    device.deviceId,
                                    dataBean.id
                                )
                            } else {
                                if (null == device.pet) {
                                    mPetRelationViewModel.bindPet(
                                        this@MyTrackerV2Activity, device.deviceId, dataBean.id
                                    )
                                } else mPetRelationViewModel.assignOtherPet(
                                    this@MyTrackerV2Activity,
                                    device.deviceId,
                                    device.pet?.petId!!,
                                    dataBean.id
                                )
                            }
                        }
                    }
                })
            }
        }

        mTrackerViewModel.getDeviceList(this, 1)
    }

    override fun liveDataObserve() {
        //更新宠物信息,添加/编辑宠物
        XEventBus.observe(this, EventName.RefreshPet) {
            if (isShowBottomSheetAdd) mPetRelationViewModel.getUnbindPetList(this@MyTrackerV2Activity)
            else mTrackerViewModel.getDeviceList(this, 1)
        }
        //添加了设备
        XEventBus.observe(this, EventName.RefreshDevice) {
            if (isShowBottomSheetAdd) mTrackerViewModel.getUnbindTrackerList(this@MyTrackerV2Activity)
            else mTrackerViewModel.getDeviceList(this, 1)
        }
        //删除设备
        XEventBus.observe(this, EventName.DeleteDevice) {
            mTrackerViewModel.getDeviceList(this, 1)
        }
        //删除设备
        XEventBus.observe(this, EventName.LogOut) {
            //删除了最后一个设备
            finish()
        }

        mTrackerViewModel.apply {
            //获取设备列表
            getDeviceListLiveData.observe(this@MyTrackerV2Activity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        dismissBottomSheet()
                        isOnlyBindOneDevice = false
                        //绑定的设备数量
                        var bindDeviceNumber = 0
                        it.getOrNull()?.let { list ->
                            lifecycleScope.launch {
                                withContext(Dispatchers.IO) {
                                    for (device in list) {
                                        //保存本地数据库
                                        if (!TextUtils.isEmpty(device.deviceOutId) && null != device.pet) {
                                            bindDeviceNumber++
                                            MyDatabase.deviceDao().insert(device)
                                        } else if (!TextUtils.isEmpty(device.deviceOutId) && null == device.pet) {
                                            //删除本地没绑定的设备
                                            MyDatabase.deviceDao().deleteByParams(
                                                ConstantString.DeviceId,
                                                device.deviceId,
                                                MyDatabase.DEVICE_TABLE
                                            )
                                        }
                                    }
                                    if (bindDeviceNumber == 1) isOnlyBindOneDevice = true
                                }
                                list.add(DeviceBean())
                                mMyTrackerAdapter.setData(list, true)
                            }
                        }
                    }
                })
            }
            //获取未绑定宠物的设备
            mUnbindTrackerListLiveData.observe(this@MyTrackerV2Activity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        mUnAssignDeviceList.clear()
                        it.getOrNull()?.let { deviceBeans ->
                            mUnAssignDeviceList.addAll(deviceBeans)
                        }
                        showAssignOptions(mUnAssignDeviceList, false)
                    }
                }, isShowNoDataTip = false)
            }
        }

        mTrackerSetViewModel.apply {
            //解绑设备/删除设备
//            mUnbindDeviceLiveData.observe(this@MyTrackerV2Activity) {
//                dealRequestResult(it, object : GetResultCallback {
//                    override fun onResult(any: Any) {
//                        showToast(R.string.txt_delete_success)
//                        XEventBus.post(EventName.DeleteDevice)
//                        lifecycleScope.launch {
//                            withContext(Dispatchers.IO) {
//                                val device = mMyTrackerAdapter.getData()[mCurrentBeanOption]
//                                SRBleUtil.instance.disconnectToMac(device.macId)
//                                //删除设备成功后,把本地数据库中的设备也删除
//                                MyDatabase.deviceDao().deleteByParams(
//                                    ConstantString.DeviceId,
//                                    device.deviceId,
//                                    MyDatabase.DeviceTableName
//                                )
//                            }
//                            mUnAssignDeviceList.clear()
//                            mTrackerViewModel.getDeviceList(this@MyTrackerV2Activity, 1)
//                        }
//                    }
//                })
//            }
            //关联其他设备
            mAssignOtherTrackerLiveData.observe(this@MyTrackerV2Activity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        dismissBottomSheet()
                        XEventBus.post(EventName.RefreshPet)
//                        mTrackerViewModel.getDeviceList(this@MyTrackerV2Activity, 1)
                        mUnAssignPetList.clear()
                    }
                })
            }
        }

        mPetRelationViewModel.apply {
            //获取未绑定设备的宠物
            mUnbindPetListLiveData.observe(this@MyTrackerV2Activity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        mUnAssignPetList.clear()
                        it.getOrNull()?.let { petBeans ->
                            mUnAssignPetList.addAll(petBeans)
                        }
                        showAssignOptions(mUnAssignPetList, true)
                    }
                }, isShowNoDataTip = false)
            }
            //给设备绑定其他宠物
            mAssignOtherPetLiveData.observe(this@MyTrackerV2Activity) {
                dismissBottomSheet()
                XEventBus.post(EventName.RefreshPet)
//                mTrackerViewModel.getDeviceList(this@MyTrackerV2Activity, 1)
                mUnAssignPetList.clear()
            }
            //绑定设备/宠物
            mBindPetLiveData.observe(this@MyTrackerV2Activity) {
                dismissBottomSheet()
                XEventBus.post(EventName.RefreshPet)
//                mTrackerViewModel.getDeviceList(this@MyTrackerV2Activity, 1)
                mUnAssignPetList.clear()
                mUnAssignDeviceList.clear()
            }
            //解绑宠物
            mUnbindPetLiveData.observe(this@MyTrackerV2Activity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        lifecycleScope.launch {
                            withContext(Dispatchers.IO) {
                                val device = mMyTrackerAdapter.getData()[mCurrentBeanOption]
                                //解绑成功后,把本地数据库中的设备也删除
                                MyDatabase.deviceDao().deleteByParams(
                                    ConstantString.DeviceId,
                                    device.deviceId,
                                    MyDatabase.DEVICE_TABLE
                                )
                            }
                            mUnAssignDeviceList.clear()
                            mUnAssignPetList.clear()
                            XEventBus.post(EventName.RefreshPet)
//                            mTrackerViewModel.getDeviceList(this@MyTrackerV2Activity, 1)
                        }
                    }
                })
            }
            //删除宠物
            mDeletePetLiveData.observe(this@MyTrackerV2Activity) {
                dealRequestResult(it, object : GetResultCallback {
                    override fun onResult(any: Any) {
                        XEventBus.post(EventName.DeletePet)
                        mUnAssignPetList.clear()
                        mTrackerViewModel.getDeviceList(this@MyTrackerV2Activity, 1)
                    }
                })
            }
        }
    }

    /**
     * 获取哪个未绑定的数据
     */
    fun getAssignData(position: Int) {
        mCurrentBeanOption = position
        mMyTrackerAdapter.getData()[position].apply {
            if (TextUtils.isEmpty(deviceOutId)) {
                getUnAssignDeviceData()
            } else if (null == pet) {
                getUnAssignPetData()
            }
        }
    }

    private fun getUnAssignDeviceData() {
        if (mUnAssignDeviceList.size == 0) mTrackerViewModel.getUnbindTrackerList(this@MyTrackerV2Activity)
        else showAssignOptions(mUnAssignDeviceList, false)
    }

    private fun getUnAssignPetData() {
        if (mUnAssignPetList.size == 0) mPetRelationViewModel.getUnbindPetList(this@MyTrackerV2Activity)
        else showAssignOptions(mUnAssignPetList, true)
    }

    /**
     * 显示可添加的设备或者宠物
     */
    private fun showAssignOptions(any: Any, isPet: Boolean) {
        if (any is MutableList<*>) {
            val list = mutableListOf<DataBean>()
            if (isPet) {
                list.add(DataBean("+ " + getString(R.string.tracker_manage_add_pet), ""))
            } else {
                DataBean("+ " + getString(R.string.txt_new_tracker), "").apply {
                    menuType = ConstantInt.SpecialType
                    list.add(this)
                }
            }
            for (i in 0 until any.size) {
                val a = any[i]
                if (a is PetBean) {
                    DataBean(a.petName, a.imgurl).apply {
                        menuType = a.petType
                        id = a.petId
                        list.add(this)
                    }
                } else if (a is DeviceBean) {
                    DataBean(a.deviceOutId, "").apply {
                        menuType = ConstantInt.SpecialType
                        id = a.deviceId
                        list.add(this)
                    }
                }
            }
            mAssignOptionsAdapter.setData(list, true)
        }

        if (null == mQMUIBottomSheet) {
            val builder = ViewUtil.instance.showBottomSheetList(mContext, null).apply {
                val view =
                    LayoutInflater.from(mContext).inflate(R.layout.layout_assign_options_list, null)
                addContentFooterView(view)
                val recyclerView = view.findViewById<RecyclerView>(R.id.rv_assign_options_list)
                ViewUtil.instance.setRecyclerViewDecorationLinearLayoutManager(
                    mContext, recyclerView, mAssignOptionsAdapter
                )
//                setOnBottomDialogDismissListener {
//                    isShowBottomSheetAdd = false
//                }
            }
            mQMUIBottomSheet = builder.build().apply {
                setOnCancelListener {
                    if (isShowBottomSheetAdd) {
                        isShowBottomSheetAdd = false
                        mTrackerViewModel.getDeviceList(this@MyTrackerV2Activity, 1)
                    }
                }
                setCanceledOnTouchOutside(false)
            }
        }
        mQMUIBottomSheet?.show()
    }

    /**
     * 消失可添加的设备或者宠物的底部弹窗
     */
    private fun dismissBottomSheet() {
        isShowBottomSheetAdd = false
        mQMUIBottomSheet?.dismiss()
    }

    /**
     *底部弹出设备操作菜单
     */
    fun showDeviceBottomSheetMenu(pos: Int) {
        mCurrentBeanOption = pos
        val device = mMyTrackerAdapter.getData()[pos]
        ViewUtil.instance.showBottomSheetList(mContext, { dialog, itemView, position, tag ->
            dialog.dismiss()
            deleteDevice(device)
//            when (position) {
//                0 -> if (null == device.pet) deleteDevice(device)
//                else getUnAssignDeviceData()
//
//                1 -> if (!isOnlyBindOneDevice) unAssignDeviceDialogTips(device)
//                else deleteDevice(device)
//
//                2 -> deleteDevice(device)
//            }
        }).apply {
            addItem(getString(R.string.txt_unbind_device))
//            if (null == device.pet) {
//                addItem(
//                    getString(R.string.txt_delete) + " ${device.deviceOutId}"
//                )
//            } else {
//                addItem(getString(R.string.txt_assign_other_tracker))
//                if (!isOnlyBindOneDevice) {
//                    addItem(
//                        String.format(getString(R.string.txt_unassign_other), device.deviceOutId)
//                    )
//                }
//                addItem(
//                    getString(R.string.txt_delete) + " ${device.deviceOutId}"
//                )
//            }
        }.build().show()
    }

    /**
     *底部弹出宠物操作菜单
     */
    fun showPetBottomSheetMenu(pos: Int) {
        mCurrentBeanOption = pos
        val device = mMyTrackerAdapter.getData()[pos]
//        var petName = ""
//        device.pet?.let {
//            petName = it.petName
//        }
        ViewUtil.instance.showBottomSheetList(mContext, { dialog, itemView, position, tag ->
            dialog.dismiss()
            goEditPet(device)
//            when (position) {
//                0 -> {
//                    //关联其他宠物
//                    if (!TextUtils.isEmpty(device.deviceOutId)) {
//                        getUnAssignPetData()
//                    } else {
//                        //编辑
//                        goEditPet(device)
//                    }
//                }
//
//                1 -> {
//                    //有绑定对应的设备
//                    if (!TextUtils.isEmpty(device.deviceOutId)) {
//                        //只有最后一对设备，只有编辑
//                        if (isOnlyBindOneDevice) goEditPet(device)
//                        //解绑宠物
//                        else unAssignDeviceDialogTips(device)
//                    } else {
//                        //删除
//                        deletePetDialogTips(device)
//                    }
//                }
//                //编辑
//                2 -> goEditPet(device)
//                3 -> deletePetDialogTips(device)
//            }
        }).apply {
            addItem(getString(R.string.txt_edit_profile))
            //有绑定对应的设备
//            if (!TextUtils.isEmpty(device.deviceOutId)) {
//                addItem(getString(R.string.txt_assign_other_pet))
//                if (!isOnlyBindOneDevice) addItem(
//                    String.format(getString(R.string.txt_unassign_other), petName)
//                )
//                addItem(getString(R.string.pet_manage_detail_edit) + " $petName")
//                if (!isOnlyBindOneDevice) addItem(
//                    getString(R.string.txt_delete) + " $petName"
//                )
//            } else {
//                addItem(getString(R.string.pet_manage_detail_edit) + " $petName")
//                addItem(getString(R.string.txt_delete) + " $petName")
//            }
        }.build().show()
    }

    /**
     * 跳转宠物编辑
     */
    private fun goEditPet(device: DeviceBean) {
        device.pet?.apply {
            val intent = Intent(
                mContext, PetProfileActivity::class.java
            )
            intent.putExtra(ConstantString.Edit, true)
            intent.putExtra(ConstantString.Pet, this)
            startActivity(intent)
        }
    }

    /**
     * 添加红色的底部item
     */
//    private fun addBottomSheetRedItem(
//        text: String, bottomListSheetBuilder: QMUIBottomSheet.BottomListSheetBuilder
//    ) {
//        QMUIBottomSheetListItemModel(text, text).let {
//            it.skinTextColorAttr(R.attr.qmui_config_color_red)
//            bottomListSheetBuilder.addItem(it)
//        }
//    }

    /**
     * 删除设备
     */
    private fun deleteDevice(device: DeviceBean) {
        Intent(mContext, DeleteTracker1Activity::class.java).let {
            it.putExtra(ConstantString.DeviceInfo, device)
            val isUnbindLastOne = if (isOnlyBindOneDevice && null == device.pet) {
                false
            } else isOnlyBindOneDevice
            it.putExtra(ConstantString.isCheck, isUnbindLastOne)
            startActivity(it)
        }
//        ViewUtil.instance.showDialog(
//            mContext, getString(R.string.txt_delete_tips), object : BaseDialog.OnDialogOkListener {
//                override fun onOkClick(dialog: BaseDialog<*>) {
//                    dialog.dismiss()
//                    Intent(mContext, DeleteTracker1Activity::class.java).let {
//                        it.putExtra(ConstantString.DeviceInfo, device)
//                        val isUnbindLastOne = if (isOnlyBindOneDevice && null == device.pet) {
//                            false
//                        } else isOnlyBindOneDevice
//                        it.putExtra(ConstantString.isCheck, isUnbindLastOne)
//                        startActivity(it)
//                    }
////                    mTrackerSetViewModel.unbindDevice(this@MyTrackerV2Activity, device.deviceId)
//                }
//            }, okTextResId = R.string.txt_sure
//        )
    }

    /**
     * 解绑宠物/设备
     */
    private fun unAssignDeviceDialogTips(device: DeviceBean) {
        device.apply {
            pet?.let {
                val string = String.format(
                    getString(R.string.txt_unassign_pet_tracker), it.petName, deviceOutId
                )
                ViewUtil.instance.showDialog(
                    mContext, string, object : BaseDialog.OnDialogOkListener {
                        override fun onOkClick(dialog: BaseDialog<*>) {
                            dialog.dismiss()
                            mPetRelationViewModel.unbindPet(
                                this@MyTrackerV2Activity, deviceId, it.petId
                            )
                        }
                    }, okTextResId = R.string.txt_sure
                )
            }
        }
    }

    /**
     * 删除宠物
     */
    private fun deletePetDialogTips(device: DeviceBean) {
        device.apply {
            pet?.let {
                val string = String.format(
                    getString(R.string.txt_delete_pet_data), it.petName
                )
                ViewUtil.instance.showDialog(
                    mContext, string, object : BaseDialog.OnDialogOkListener {
                        override fun onOkClick(dialog: BaseDialog<*>) {
                            dialog.dismiss()
                            mPetRelationViewModel.deletePet(
                                this@MyTrackerV2Activity, it.petId
                            )
                        }
                    }, okTextResId = R.string.txt_sure
                )
            }
        }
    }
}