import React, { useState } from 'react'
import styles from './index.module.less'
import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useThrottleFn } from 'ahooks'

interface IProps {
  list: any[]
  itemHeight: number
  renderItem: any
  onchange: (value: any) => void
}

const DragSortList: React.FC<IProps> = (props) => {
  const [list, setList] = useState(
    props.list.map((item, index) => ({
      ...item,
      top: index * props.itemHeight
    }))
  )
  const [dragging, setDragging] = useState(null)
  const [startY, setStartY] = useState(0)

  //  拖拽长按
  const handleLongPress = (e, index) => {
    // 震动
    // Taro.vibrateShort()
    setStartY(e.touches[0].clientY)
    setDragging(index)
  }

  const { run: handleTouchMove } = useThrottleFn(
    (e) => {
      if (dragging === null) return
      const newY = e.touches[0].clientY
      const diff = newY - startY
      // 计算新的 top 值
      let newTop = list[dragging].top + diff
      // 确保元素不会超出列表范围
      newTop = Math.max(0, newTop)
      newTop = Math.min(newTop, (list.length - 1) * props.itemHeight)
      // 计算拖拽元素的当前索引
      const currentIndex = Math.round(newTop / props.itemHeight)
      // 只有当拖拽元素移动到新位置时才更新列表
      if (currentIndex !== dragging) {
        const newList = [...list]
        // 移除拖拽元素并插入到新位置
        const [draggingItem] = newList.splice(dragging, 1)
        newList.splice(currentIndex, 0, draggingItem)
        // 更新列表中每个元素的 top 值
        newList.forEach((item, index) => {
          item.top = index * props.itemHeight
        })
        setList(newList)
        // @ts-ignore
        setDragging(currentIndex) // 更新拖拽元素的索引
      }
      // 更新 startY
      setStartY(newY)
    },
    { wait: 500 }
  )

  //  拖拽结束
  const handleTouchEnd = () => {
    if (dragging === null) return
    // 根据最终位置更新列表顺序
    const targetIndex = Math.round(list[dragging].top / props.itemHeight)
    const newList = [...list]
    const movedItem = newList.splice(dragging, 1)[0]
    newList.splice(targetIndex, 0, movedItem)
    // 重置元素位置
    const arr = newList.map((item, index) => ({ ...item, top: index * props.itemHeight }))
    setList(arr)
    setDragging(null)
    props.onchange(arr)
  }

  return (
    <View className='drag_list'>
      {list.map((item, index) => (
        <View
          className='drag_item'
          key={item.id}
          style={{
            top: `${item.top}px`,
            zIndex: dragging === index ? 999 : 1,
            opacity: dragging === index ? 0.5 : 1
          }}
          onLongPress={(e) => {
            console.log('【长按】', e)
            handleLongPress(e, index)
          }}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
        >
          {props.renderItem(item)}
        </View>
      ))}
    </View>
  )
}

export default DragSortList