Last active: 2 years ago
/**
* 虚拟法院
*
* 分类搜索
*/
addSearchData(
state,
action: PayloadAction<{
list: number[];
data: SearchDataContent;
}>
) {
const searchData = state.proj.data.searchData;
const { list, data } = action.payload;
const len = list.length;
const defaultItem = {
id: 0,
pid: 0,
};
// 当 list 长度为 1 时,只添加父分类
if (len === 1) {
if (!searchData) {
state.proj.data.searchData = {
[list[0]]: {
...defaultItem,
id: list[0],
children: [],
content: [],
},
};
} else {
state.proj.data.searchData = {
...searchData,
...{
[list[0]]: { ...defaultItem, id: list[0] },
},
};
}
} else {
// 处理子分组添加
// 先找到或创建最外层父分类
const parent: SearchData = {
...(searchData?.[list[0]] ?? {
...defaultItem,
children: [],
content: [],
}),
id: list[0],
};
/**
* 根据级联选择的分类,添加分类下内容
*
* 通过遍历级联选择器的状态,递归直到最后一个分类
* 并在该分类下创建内容
*
* @param parent 一级一下的父分类
* @param list 级联选择器的 value
* @param index 级联选择器 value 的下标
*/
const crateContent = (
parent: SearchData,
list: number[],
index: number,
data: SearchDataContent
): void => {
const len = list.length;
// 父分类是否已经存在
const parentExist = parent.children.find((c) => c.id === list[index]);
// 当下标与级联状态同样时,即为添加该分类下的内容
if (index === len - 1) {
if (parentExist) {
parentExist.content = [...parentExist.content, data];
} else {
parent.children.push({
...defaultItem,
id: list[index],
pid: parent.id,
content: [data],
children: [],
});
}
} else {
// 当下标与级联状态不同时,继续递归,添加到该分类的 children 下
if (parentExist) {
return crateContent(parentExist, list, index + 1, data);
} else {
const csParent = {
...{
...defaultItem,
children: [],
content: [],
},
id: list[index],
pid: parent.id,
};
parent.children.push(csParent);
return crateContent(csParent, list, index + 1, data);
}
}
};
crateContent(parent, list, 1, data);
if (searchData?.[list[0]]) {
searchData[list[0]] = parent;
} else {
state.proj.data.searchData = {
...searchData,
[list[0]]: parent,
};
}
}
},