import type { ElTable } from "element-plus"
import Sortable from 'sortablejs'

export function useSettingRule<T>() {
    const tableList = ref<T[]>([])
    const selectTableList = ref<T[]>([])
    const tableDataRef = ref<InstanceType<typeof ElTable>>()

    /**添加时间节点 */
    const handleAddItem = (item: T) => {
        tableList.value.push(item)
    }
    /**批量删除 */
    const handleBatchDelete = () => {
        const selectedIds = unref(selectTableList).map(item => item.uid)
        tableList.value = unref(tableList).filter(item => !selectedIds.includes(item.uid))
        selectTableList.value = []
        tableDataRef.value?.clearSelection()
    }
    /**删除（取消选中删除项）*/
    const handleDelete = (scope: any) => {
        const { $index, row } = scope
        tableList.value.splice($index, 1)
        if (!unref(selectTableList).length) return
        selectTableList.value = unref(selectTableList).filter(item => item.uid !== row.uid)
        tableDataRef.value?.toggleRowSelection(row, false)
    }
    /**拖拽表格 */
    const initDropTable = () => {
        if (tableDataRef.value) {
            const el = tableDataRef.value.$el.querySelector('.el-table__body tbody')
            return Sortable.create(el, {
                handle: '.el-table__row',
                onEnd: ({ newIndex, oldIndex }: { newIndex: number; oldIndex: number }) => {
                    const arr = tableList.value
                    const currRow = arr.splice(oldIndex, 1)[0]
                    arr.splice(newIndex, 0, currRow)
                    tableList.value = []
                    nextTick(() => {
                        tableList.value = arr
                    })
                }
            })
        }
    }

    return {
        selectTableList,
        tableList,
        tableDataRef,
        handleAddItem,
        handleBatchDelete,
        handleDelete,
        initDropTable,
    }
}
