package com.swago.user.black

import android.graphics.Rect
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.swago.baseswago.UserVm
import com.swago.baseswago.cusview.SwagoRecyclerView
import com.swago.baseswago.fragment.BaseListFragment
import com.swago.baseswago.model.BlackListModel
import com.swago.baseswago.util.DpPxUtil
import com.swago.baseswago.util.IMUtil
import com.swago.user.adapter.BlackListAdapter
import com.swago.user.databinding.FragmentBlackBinding

/**
 *@date 2022/2/26 09:46
 *description:私信黑名单
 */
class BlackMessageFragment : BaseListFragment<FragmentBlackBinding, BlackListModel.ListBean>() {

    private val userVm by viewModels<UserVm>()

    private var position = -1

    override val smartRecyclerView: SwagoRecyclerView<BlackListModel.ListBean> by lazy {
        binding.swagoRv as SwagoRecyclerView<BlackListModel.ListBean>
    }
    override val adapter: BaseQuickAdapter<BlackListModel.ListBean, *> by lazy {
        BlackListAdapter()
    }
    override val layoutManager: RecyclerView.LayoutManager by lazy {
        LinearLayoutManager(context)
    }
    override val loadData: (page: Int) -> Unit = {
        userVm.getBlackList(it + 1)
    }

    override fun initLiveData() {
        userVm.blackListLiveData.observe(this) {
            if (it == null){
                smartRecyclerView.onFetchDataError()
            }else{
                smartRecyclerView.onFetchDataFinish(it.list,true)
            }
        }

        userVm.hasBeenBlackLiveData.observe(this) {
            adapter.data.removeAt(position)
            adapter.notifyDataSetChanged()
        }
    }

    inner class VerticalItemDecoration : RecyclerView.ItemDecoration() {

        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            val margin = DpPxUtil.dip2px(20f)
            outRect.set(0, margin, 0, 0)
        }
    }

    override fun initViewData() {
        smartRecyclerView.recyclerView?.addItemDecoration(VerticalItemDecoration())
        adapter.setOnItemChildClickListener { _, _, position ->
            this.position = position
            val list = ArrayList<String>()
            list.add(adapter.data[position].user_account)
            IMUtil.deleteBlackList(list) {
                userVm.addBlack(adapter.data[position].user_account, 1)
            }
        }
    }

}