package com.casic.br.fragment

import android.os.Handler
import androidx.lifecycle.ViewModelProvider
import com.casic.br.R
import com.casic.br.adapter.MessageListAdapter
import com.casic.br.base.BaseApplication
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.extensions.showEmptyPage
import com.casic.br.model.PushMessageModel
import com.casic.br.utils.BadeHelper
import com.casic.br.vm.MessageViewModel
import com.pengxh.kt.lite.base.KotlinBaseFragment
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import kotlinx.android.synthetic.main.fragment_message.*
import kotlinx.android.synthetic.main.include_empty_view.*
import kotlinx.android.synthetic.main.include_main_title.*

class MessagePageFragment : KotlinBaseFragment() {

    companion object {
        lateinit var weakReferenceHandler: WeakReferenceHandler
    }

    private lateinit var messageAdapter: MessageListAdapter
    private lateinit var messageViewModel: MessageViewModel
    private var dataBeans: MutableList<PushMessageModel.DataModel.RowsModel> = ArrayList()
    private var pageIndex = 1
    private var isRefresh = false
    private var isLoadMore = false
    private var clickedPosition = 0

    override fun initLayoutView(): Int = R.layout.fragment_message

    override fun setupTopBarLayout() {
        requireContext().initLayoutImmersionBar(rootView)
        leftTitleView.text = "消息"
    }

    override fun initData() {
        weakReferenceHandler = WeakReferenceHandler(callback)
        messageViewModel = ViewModelProvider(this)[MessageViewModel::class.java]
        messageViewModel.listModel.observe(this, {
            if (it.code == 200) {
                val dataRows = it.data?.rows!!
                countBadeNumber(dataRows)
                when {
                    isRefresh -> {
                        dataBeans.clear()
                        dataBeans = dataRows
                        messageLayout.finishRefresh()
                        isRefresh = false
                    }
                    isLoadMore -> {
                        if (dataRows.size == 0) {
                            "到底了，别拉了".show(requireContext())
                        }
                        dataBeans.addAll(dataRows)
                        messageLayout.finishLoadMore()
                        isLoadMore = false
                    }
                    else -> {
                        dataBeans = dataRows
                    }
                }
                weakReferenceHandler.sendEmptyMessage(2022101001)
            }
        })

        messageViewModel.deleteResult.observe(this, {
            dataBeans.removeAt(clickedPosition)
            messageAdapter.notifyItemRemoved(clickedPosition)
            messageAdapter.notifyItemRangeChanged(
                clickedPosition, dataBeans.size - clickedPosition
            )
            countBadeNumber(dataBeans)
            if (dataBeans.size == 0) {
                emptyView!!.showEmptyPage("没有任何消息") {
                    pageIndex = 1
                    obtainMessageListByPage()
                }
            }
        })

        messageViewModel.updateResult.observe(this, {
            val rowsModel = dataBeans[clickedPosition]
            rowsModel.messageStatus = "1"
            messageAdapter.notifyItemChanged(clickedPosition)
            messageAdapter.notifyItemRangeChanged(
                clickedPosition, dataBeans.size - clickedPosition
            )
            countBadeNumber(dataBeans)
        })
    }

    override fun initEvent() {
        messageLayout.setOnRefreshListener {
            isRefresh = true
            //刷新之后页码重置
            pageIndex = 1
            obtainMessageListByPage()
        }

        messageLayout.setOnLoadMoreListener {
            isLoadMore = true
            pageIndex++
            obtainMessageListByPage()
        }
    }

    override fun onResume() {
        super.onResume()
        obtainMessageListByPage()
    }

    override fun observeRequestState() {

    }

    private fun obtainMessageListByPage() {
        messageViewModel.obtainMessageListByPage("", "", "", pageIndex)
    }

    private fun countBadeNumber(dataRows: MutableList<PushMessageModel.DataModel.RowsModel>) {
        var unReadMessage = 0
        dataRows.forEach { message ->
            if (message.messageStatus == "0") {
                unReadMessage += 1
            }
        }
        BadeHelper.setBadgeNum(BaseApplication.obtainInstance(), unReadMessage)
    }

    private val callback = Handler.Callback {
        when (it.what) {
            2022101001 -> {
                if (isRefresh || isLoadMore) {
                    messageAdapter.notifyDataSetChanged()
                } else {
                    if (dataBeans.size == 0) {
                        emptyView!!.showEmptyPage("没有任何消息") {
                            pageIndex = 1
                            obtainMessageListByPage()
                        }
                    } else {
                        emptyView!!.hide()
                        messageAdapter = MessageListAdapter(requireContext(), dataBeans)
                        messageRecyclerView.adapter = messageAdapter
                        messageAdapter.setOnItemClickListener(object :
                            MessageListAdapter.OnItemClickListener {
                            override fun onDeleteClicked(position: Int) {
                                clickedPosition = position
                                messageViewModel.deleteMessageById(dataBeans[clickedPosition].id)
                            }

                            override fun onShowMoreClicked(position: Int) {
                                //更改数据库里通知状态
                                clickedPosition = position
                                messageViewModel.updateMessageById(
                                    dataBeans[clickedPosition].id, "1"
                                )
                            }
                        })
                    }
                }
            }
            2022101002 -> {
                isRefresh = true
                pageIndex = 1
                obtainMessageListByPage()
            }
        }
        true
    }
}