package com.xty.common.recycleUtils

import android.app.Service
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Vibrator
import androidx.core.content.ContextCompat.getSystemService
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.ACTION_STATE_DRAG
import androidx.recyclerview.widget.ItemTouchHelper.ACTION_STATE_SWIPE
import androidx.recyclerview.widget.RecyclerView
import com.hjq.toast.ToastUtils
import java.util.*


class ItemHelperCallBack(var move:(fromPosition:Int,toPosition:Int)->Unit,var status:(action:Int)->Unit,var moveFinish:(position:Int)->Unit,var restoreColor:Drawable?=null): ItemTouchHelper.Callback() {
    val dragFlags = (ItemTouchHelper.UP or ItemTouchHelper.DOWN)
    val swipeFlags = 0 // 0 表禁止用户各个方向的操作，即禁止用户滑动
    var startPosition=-1
    override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder )=
        makeMovementFlags(dragFlags,swipeFlags)

    override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
        //得到当拖拽的viewHolder的Position
        val fromPosition = viewHolder.adapterPosition
        //拿到当前拖拽到的item的viewHolder
        val toPosition: Int = target.adapterPosition
/*        Collections.swap(data, fromPosition, toPosition)
        recyclerView.adapter!!.notifyItemMoved(fromPosition, toPosition)
        return true*/
        //记录开始位置
        if(startPosition==-1){
            startPosition=fromPosition
        }

        move.invoke(fromPosition,toPosition)

        return true

    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        super.onSelectedChanged(viewHolder, actionState)
        //获取系统震动服务
        //获取系统震动服务

        status.invoke(actionState)
        when(actionState) {
            ACTION_STATE_DRAG -> {
                viewHolder!!.itemView.setBackgroundColor(Color.TRANSPARENT)
            }
        }
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        super.clearView(recyclerView, viewHolder)
        //还原背景色


        if(restoreColor==null){
            viewHolder.itemView.setBackgroundColor(0)
        }else{
            viewHolder.itemView.background = restoreColor
        }
        //移动位置不一样才请求接口
        if(startPosition!= viewHolder.bindingAdapterPosition){
            startPosition=-1
            moveFinish( viewHolder.bindingAdapterPosition)
        }


    }
}