wujingjing
2024-04-22 f106e4dffb8279cb90726e83e7edd631f4c77699
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import type { Ref } from 'vue';
import { onActivated, onDeactivated, onMounted, onUnmounted, ref, watch } from 'vue';
import { deepClone } from '/@/utils/other';
import { convertListToTree, flatten } from '/@/utils/util';
 
/**
 *
 * @param tableData 原始数据,接口拿到的数据
 * @param queryParams 查询参数 form
 * @param getTableData
 * @param isTree 是否是 ParentID 构建树的数组
 * @param isChildTree 是否是 Children 构建的树的数组
 * @returns
 */
export const useQueryTable = (
    tableData: Ref<any[]>,
    queryParams: Ref<Object>,
    getTableData: () => void | Promise<void>,
    isTree?: Boolean,
    isChildTree = false
) => {
    const displayTableData = ref(null as any[]);
 
    const resetQuery = () => {
        for (const key in queryParams.value) {
            if (typeof queryParams.value[key] === 'string') {
                queryParams.value[key] = '';
            } else if (typeof queryParams.value[key] === 'number') {
                queryParams.value[key] = null;
            }
        }
        getTableData();
    };
 
    const handleQueryTable = () => {
        if (checkQueryParamsIsEmpty()) {
            return getTableData();
        }
        const convertData = isChildTree ? flatten(tableData.value) : tableData.value;
        const filterTableData = convertData.filter((item: any) => {
            return Object.keys(queryParams.value).every((key) => {
                const queryValue = queryParams.value[key];
                let queryStr = '';
                if (queryValue !== null) {
                    queryStr = String(queryValue);
                }
 
                return String(item[key]).toLowerCase().includes(queryStr.trim().toLowerCase());
            });
        });
        displayTableData.value = filterTableData;
    };
    const handleTableDataChange = isTree
        ? (val) => {
                // convertListToTree 克隆原始数据,不影响原始数据
                displayTableData.value = convertListToTree(deepClone(val));
          }
        : (val) => {
                displayTableData.value = val;
          };
 
    const checkQueryParamsIsEmpty = () => {
        return Object.values(queryParams.value).every((objectValue) => objectValue === '' || objectValue === null);
    };
 
    watch(
        () => tableData.value,
        (val) => {
            handleTableDataChange(val);
        },
        { immediate: true }
    );
 
    return {
        checkQueryParamsIsEmpty,
        resetQuery,
        handleQueryTable,
        displayTableData,
    };
};