import { ref } from 'vue'
import { hasOnlyKey } from '@/utils'

const useSelectTable = () => {
    const tableChosenData = ref([])
    const refsList = ref({})

    const handleRowClick = ({ type, refs, onlyKey }, $event) => {
        const tableRef = refsList.value.tableLayoutRef
        const hasExist = hasOnlyKey(tableChosenData.value, { keyName: onlyKey, keyValue: $event[onlyKey] })
        // 多选
        if (type === 'multi') {
            tableChosenData.value.push($event)
            tableRef.toggleRowSelection($event, !hasExist)
        }
        // 单选
        if (type === 'single') {
            if (hasExist) tableChosenData.value = []
            else tableChosenData.value = [$event]
            tableRef.clearSelection()
            tableRef.toggleRowSelection($event, !hasExist)
        }
    }

    const handleSelectionChange = ({ type, refs, onlyKey }, $event) => {
        const tableRef = refsList.value.tableLayoutRef
        // 多选
        if (type === 'multi') tableChosenData.value = $event
        // 单选
        if (type === 'single') {
            if ($event.length > 1) {
                tableRef.clearSelection()
                tableRef.toggleRowSelection($event.pop())
            } else {
                tableChosenData.value = $event
            }
        }
    }

    /**
     * 清空所有选中
     */
    const clearAllSelect = () => { 
        const tableRef = refsList.value.tableLayoutRef
        tableChosenData.value = []
        tableRef.clearSelection()
     }

    return {
        tableChosenData,
        refsList,
        handleRowClick,
        handleSelectionChange,
        clearAllSelect
    }
}

export default useSelectTable;