import React, { Component } from "react";
import { Button, message, Modal, Spin, Table, Checkbox, Collapse, } from "antd";
import $ from "jquery/src/ajax";
import "./index.less";
class Cascaders extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
authTree: [],
checkedList: [],
};
this.itemHandle = this.itemHandle.bind(this);
this.onSelect = this.onSelect.bind(this);
this.onOks = this.onOks.bind(this);
this.onCancel = this.onCancel.bind(this);
}
componentDidMount() {
// 后端返回的数据,转成前端要用的数据保存页面使用
// const authTree = [...params.authTree];
// this.setState({
// authTree
// })
}
// 转成前端要用的数据
authTreeFun() {
const checkedList = this.state.checkedList;
checkedList.forEach((item) => {
this.itemHandle(item);
});
}
// 点击选择部门
onSelect() {
const list = JSON.parse(localStorage.getItem("departmentData"))
const authTree = list
this.setState({
visible: true,
authTree: authTree,
}, () => {
this.authTreeFun();
})
}
onOks() {
const { authTree, checkedList } = this.state
const { id = "id", children = "children", onSel } = this.props
let list = []
authTree.forEach((its) => {
if (its[children]) {
its[children].forEach((itl) => {
if (itl.checked) {
list.push(itl[id])
}
});
}
})
this.setState({
checkedList: list,
visible: false,
})
onSel(checkedList)
}
onCancel() {
this.setState({
visible: false,
})
}
// 代码三级联动核心就在这里
itemHandle(iD, checked = true) {
const { id = "id", children = "children" } = this.props
const { authTree } = this.state
// const authTree = [...this.state.authTree];
authTree.forEach((item1) => {
if (item1[id] == iD) {
item1.checked = checked;
if (item1[children]) {
item1[children].forEach((item2) => {
item2.checked = checked;
});
}
} else {
// 反向思路: 保存子选项框的个数, 子选项选中就-1, 等于0说明都选中了, 父选项就勾上
let temp1 = !!item1[children] ? item1[children].length : 0;
!!item1[children] && item1[children].forEach((item2) => {
if (item2[id] == iD) {
item2.checked = checked;
}
// 选中-1, 未选中不动
item2.checked ? temp1 -= 1 : temp1;
});
// 长度是0, 父选项框就勾选
!!item1[children] && temp1 === 0 ? item1.checked = true : item1.checked = false;
}
});
this.setState({
authTree,
});
}
render() {
const { Panel } = Collapse;
const { visible, authTree, checkedList } = this.state
const {
placeholder = "选择部门",
width = 200,
height = 32,
id = "id",
name = "name",
children = "children",
} = this.props
const authTreeMap = authTree.map((item1) => (
// Panel是手风琴