package com.abbidot.tracker.deprecated.ui.activity

import android.graphics.Color
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.base.BaseDiffCallBack
import com.abbidot.tracker.base.BaseQMUIRVItemSwipeAction
import com.abbidot.tracker.base.BaseSwipeMenuAdapter
import com.abbidot.tracker.databinding.ActivitySwipeActionBinding
import com.abbidot.tracker.util.ViewUtil
import com.qmuiteam.qmui.recyclerView.QMUIRVItemSwipeAction
import com.qmuiteam.qmui.recyclerView.QMUISwipeAction
import com.qmuiteam.qmui.recyclerView.QMUISwipeViewHolder
import com.qmuiteam.qmui.widget.pullRefreshLayout.QMUIPullRefreshLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SwipeActionActivity :
    BaseActivity<ActivitySwipeActionBinding>(ActivitySwipeActionBinding::inflate) {

    private lateinit var mAdapter: BaseSwipeMenuAdapter<String>
    private lateinit var list: MutableList<String>

    override fun getTopBar() = mViewBinding.swipeTestBar.titleTopBar

    override fun initData() {
        setTopBarTitle("滑动菜单")

        list = mutableListOf()

        initMenu()

        ViewUtil.instance.setRecyclerViewDecorationLinearLayoutManager(mContext!!,
                mViewBinding.swipeTestPull.pullRefreshRv,mAdapter)

        mViewBinding.swipeTestPull.onlyPullToRefresh.setOnPullListener(object :
            QMUIPullRefreshLayout.OnPullListener {
            override fun onMoveTarget(offset: Int) {
            }

            override fun onMoveRefreshView(offset: Int) {
            }

            override fun onRefresh() {
                mViewBinding.swipeTestPull.onlyPullToRefresh.postDelayed(Runnable {
                    list.clear()
                    onDataLoaded()
                    mViewBinding.swipeTestPull.onlyPullToRefresh.finishRefresh()
                }, 1000)
            }
        })
        mAdapter.setOnAgainClickListener(object : BaseRecyclerAdapter.OnAgainClickListener {
            override fun onAgainListener() {
                showLoading(true)
                mViewBinding.swipeTestPull.pullRefreshRv.postDelayed(Runnable {
                    onDataLoaded()
                    showLoading(false)
                }, 1500)
            }
        })

//        onDataLoaded()
    }

    private fun initMenu() {
        val menu: MutableList<QMUISwipeAction> = mutableListOf()
        mAdapter = object : BaseSwipeMenuAdapter<String>(mContext!!, list) {

            override fun getEmptyLayoutId(viewType: Int) = R.layout.layout_empty_view
            override fun getItemLayoutId(viewType: Int) = R.layout.layout_list_item

            override fun getSwipeActions(): MutableList<QMUISwipeAction> {
                return menu
            }

            override fun bindData(holder: QMUISwipeViewHolder?, position: Int, item: String) {
                holder!!.itemView.findViewById<TextView>(R.id.sdagfdsgg).text = item
            }

        }
        val deleteAction = mAdapter.mActionBuilder.text("删除").backgroundColor(Color.RED).build()
        val writeReviewAction =
            mAdapter.mActionBuilder.text("写想法").backgroundColor(Color.BLUE).build()
        menu.add(deleteAction)
//        menu.add(writeReviewAction)

        val itemSwipeAction = object : BaseQMUIRVItemSwipeAction(QMUIRVItemSwipeAction.SWIPE_LEFT) {
            override fun removeItem(position: Int) {
                val newList = mAdapter.remove(mAdapter.getData(), position)
                updateAdapter(mAdapter.getData(), newList)
            }

            override fun onClickAction(swipeAction: QMUIRVItemSwipeAction?,
                                       selected: RecyclerView.ViewHolder?,
                                       action: QMUISwipeAction?) {
                super.onClickAction(swipeAction, selected, action)
                if (action == deleteAction) {
                    removeItem(selected!!.adapterPosition)
                } else {
                    swipeAction!!.clear()
                }
            }
        }
        val swipeAction = QMUIRVItemSwipeAction(true, itemSwipeAction)
        swipeAction.attachToRecyclerView(mViewBinding.swipeTestPull.pullRefreshRv)
    }

    private fun onDataLoaded() {
        val data: MutableList<String> = ArrayList(
                listOf("Helps", "Maintain", "Liver", "Health", "Function", "Supports", "Healthy",
                        "Fat", "Metabolism", "Nuturally", "Bracket", "Refrigerator", "Bathtub",
                        "Wardrobe", "Comb", "Apron", "Carpet", "Bolster", "Pillow", "Cushion"))
        data.shuffle()
        list = mAdapter.getData()

        updateAdapter(list, data)
    }

    private fun updateAdapter(oldList: MutableList<String>, newList: MutableList<String>) {
        if (oldList.size == 0) {
            mAdapter.setData(newList)
            mAdapter.notifyDataSetChanged()
            return
        }
        lifecycleScope.launch {
            //异步新旧数据比较
            withContext(Dispatchers.Default) {
                useDiffUtil(oldList, newList)
            }.dispatchUpdatesTo(mAdapter)

            //刷新完成重新定位到第一个数据
            mViewBinding.swipeTestPull.pullRefreshRv.scrollToPosition(0)
        }

    }

    /**
     * 数据比较
     */
    private fun useDiffUtil(oldList: MutableList<String>,
                            newList: MutableList<String>): DiffUtil.DiffResult {
        mAdapter.setData(newList)
        return DiffUtil.calculateDiff(object : BaseDiffCallBack<String>(oldList, newList) {
            override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
                oldList[oldItemPosition] == newList[newItemPosition]

            override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
                oldList[oldItemPosition] == newList[newItemPosition]

        }, true)
    }
}