/**
 *  跨页全选
 * @param multipleTableRef 多选的表格
 * @param showData  显示的数据
 * @param idKey 选中的id名称
 * @param tableFilterData 过滤掉不能选择数据后的全部数据，如果没有不能选中的数据，则为全部数据
 * @returns checkAll： 跨页全选状态
 *          checkedIds 选中的所有行的id
 *          initTableRowCheckStatus 初始化选中行  
 *          handlMultipageSelect 跨页全选状态操作
 *          handleRowSelect 操作行选中  
 *          handleAllSelect 操作当前页选中
 */
export function useCrossPageSelect(multipleTableRef: any, showData: any, idKey: string, tableFilterData: any) {

    const checkAll = ref(false) // 跨页全选转态
    const checkedIds = ref([]) // 选中的ids

    // 初始化行选中状态
    const initTableRowCheckStatus = () => {
        nextTick(() => {
            showData.value.forEach((item: any) => {
                if (checkedIds.value.includes(item[idKey])) {
                    multipleTableRef.value!.toggleRowSelection(item, true)
                    return
                }
                multipleTableRef.value!.toggleRowSelection(item, false)
            })
        })
    }

    watch(() => showData.value, () => {
        initTableRowCheckStatus()
    })
    watch([checkedIds, tableFilterData], ([ids, tableData]) => {
        ids.length === tableData.length ? (checkAll.value = true) : (checkAll.value = false)
    }, { deep: true })

    // 跨页全选
    const handlMultipageSelect = (status: boolean) => {
        if (status) {
            checkedIds.value = tableFilterData.value.map((item: any) => item[idKey])
            // checkedIds.value = tableData.value.filter(val => val.channel == "渠道销售").map(item => item.icapplynum)
        } else {
            checkedIds.value = []
        }
        initTableRowCheckStatus()
    }

    // 切换选中行
    const handleRowSelect = (selection: any, row: any) => {
        const id = row[idKey]
        const item = selection.find((item: any) => item[idKey] === id)

        if (item) {
            if (!checkedIds.value.includes(id)) {
                checkedIds.value.push(id)
            }
            return
        }
        const index = checkedIds.value.indexOf(id)
        if (index !== -1) {
            checkedIds.value.splice(index, 1)
        }
        checkAll.value = false
    }
    // 单页全选
    const handleAllSelect = (selection: any) => {
        if (selection.length > 0) {
            selection.forEach((item: any) => {
                if (!checkedIds.value.includes(item[idKey])) {
                    checkedIds.value.push(item[idKey])
                }
            });
            return
        }
        showData.value.forEach((item: any) => {
            const index = checkedIds.value.indexOf(item[idKey])
            if (index != -1) {
                checkedIds.value.splice(index, 1)
            }
        });
        checkAll.value = false
    }

    return { checkAll, checkedIds, initTableRowCheckStatus, handlMultipageSelect, handleRowSelect, handleAllSelect }
}