package com.abbidot.tracker.ui.activity.account

import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.R
import com.abbidot.tracker.adapter.NotificationV2Adapter
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.constant.GetResultCallback
import com.abbidot.tracker.database.MyDatabase
import com.abbidot.tracker.databinding.ActivityNotificationV2Binding
import com.abbidot.tracker.deprecated.ui.activity.vm.NotificationsViewModel
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 消息列表
 */
class NotificationV2Activity :
    BaseActivity<ActivityNotificationV2Binding>(ActivityNotificationV2Binding::inflate) {

    private val mNotificationsViewModel: NotificationsViewModel by viewModels()

    private lateinit var mMessageAdapter: NotificationV2Adapter

    override fun getTopBar() = mViewBinding.notificationV2DetailBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_notifications)

        mMessageAdapter = NotificationV2Adapter(mContext, null).apply {
            setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
                override fun onItemClick(itemView: View?, pos: Int) {
                    val message = getItem(pos)
                    message.isSelect = !message.isSelect
                    if (!message.isRead) {
                        message.isRead = true
                        lifecycleScope.launch(Dispatchers.IO) {
                            MyDatabase.messageDao().insert(message)
//                            XEventBus.post(EventName.RefreshMessage)
                        }
                    }
                    notifyItemChanged(pos)
                }
            })
        }
        ViewUtil.instance.setRecyclerViewDecorationLinearLayoutManager(
            mContext, mViewBinding.rvNotificationV2Detail, mMessageAdapter
        )
        setOnClickListenerViews(mViewBinding.btnNotificationV2ReadAll)

        mNotificationsViewModel.getMessageList()
    }

    override fun liveDataObserve() {
        mNotificationsViewModel.mNotificationsLiveData.observe(this) {
            dealRequestResult(it, object : GetResultCallback {
                override fun onResult(any: Any) {
                    it.getOrNull()?.apply {
                        lifecycleScope.launch(Dispatchers.IO) {
                            Util.dealMessage(this@apply)
                            setMessageData()
                        }
                    }
                }

                override fun onRequestError(exceptionCode: String?) {
                    setMessageData()
                }
            }, isShowRequestErrorTip = false)
        }
    }

    private fun setMessageData() {
        lifecycleScope.launch(Dispatchers.IO) {
            MyDatabase.messageDao().findAll(MyDatabase.MessageTableName)?.apply {
                LogUtil.e("消息列表个数：${size}")
                //按最新时间排序
                val sortedByList = this.sortedByDescending { it.sendTime }
                runOnUiThread {
                    mMessageAdapter.setData(sortedByList.toMutableList(), true)
                }
//                for (i in sortedByList){
//                    LogUtil.e(i.messageId+"："+i.message)
//                }
            }
        }
    }

    private fun readAllMessage() {
        lifecycleScope.launch(Dispatchers.IO) {
            MyDatabase.messageDao().findAll(MyDatabase.MessageTableName)?.apply {
                var isUpdate = false
                for (message in this) {
                    if (!message.isRead) {
                        message.isRead = true
                        isUpdate = true
                        MyDatabase.messageDao().insert(message)
                    }
                }
                runOnUiThread {
                    val list = mMessageAdapter.getData()
                    for (m in list) {
                        if (!m.isRead) {
                            m.isRead = true
                        }
                    }
                    mMessageAdapter.notifyItemRangeChanged(0, list.size)
                }
//                if (isUpdate) XEventBus.post(EventName.RefreshMessage)
            }
        }
    }

    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                btnNotificationV2ReadAll -> readAllMessage()
            }
        }
    }
}