/* eslint-disable no-unused-expressions */
/* eslint-disable eqeqeq */
import React, { useState, useEffect, useRef } from 'react';
import {
  // Tree,
  Table,
  Space,
  message,
  Modal,
  Input,
  notification,
  Tooltip,
  Card,
  Button,
  Spin,
  Dropdown,
  Menu,
  Popconfirm,
  Form,
  Radio,
} from 'antd';
import {
  UserOutlined,
  UserAddOutlined,
  UsergroupAddOutlined,
  EditOutlined,
  EditTwoTone,
  DeleteOutlined,
  IdcardOutlined,
  UnlockOutlined,
  ApartmentOutlined,
  StopOutlined,
  DoubleLeftOutlined,
  DoubleRightOutlined,
  DownOutlined,
  BorderlessTableOutlined,
  LockOutlined,
  PlusSquareFilled,
  EllipsisOutlined,
  PlusOutlined,
  SyncOutlined,
  ClusterOutlined,
} from '@ant-design/icons';
import PageContainer from '@/components/BasePageContainer';
import voca from 'voca';
import zhCN from 'antd/es/locale/zh_CN';
import {
  addToOrg,
  addToOrgs,
  getOneOUUserListNew,
  getUserRelationList,
  getUserTree,
  // eslint-disable-next-line import/named
  deleteUser as postDeleteUser,
  setUserState as postSetUserState,
  multiDeleteUsers,
  setOrgArea,
  getOrgArea,
  GetMapSetByGroupID,
  GetOUTreeNew,
  GetUserRelationListNew,
  GetUserByKeyNew,
  UserStateOUNew,
  JumpToAnotherOUNew,
  DeleteUserNew,
  loadAllUserRole,
  DragGroup,
  GetAllSite,
  SetGroupManager,
} from '@/services/userManage/api';
import { AddUserAuthSetting, GetUserAuthSet } from '@/services/database/api';
import Tree from '@/components/ExpendableTree';
import classnames from 'classnames';
import DraggleLayout from 'components/DraggleLayout';
import AddUserModal from './AddUserModal';
import AddSubOrgModal from './AddSubOrgModal';
import EditOrgModal from './EditOrgModal';
import DeleteOrgModal from './DeleteOrgModal';
import RelateRoleModal from './RelateRoleModal';
import EditUserModal from './EditUserModal';
import ChangePasswordModal from './ChangePasswordModal';
import MapScopeEditModal from '@/components/MapScope';
import AuthModal from './AuthModal';
import styles from './UserManage.less';
import { createGuid } from '@/utils/transformUtil';
const TdCell = props => {
  // onMouseEnter, onMouseLeave在数据量多的时候，会严重阻塞表格单元格渲染，严重影响性能
  const { onMouseEnter, onMouseLeave, ...restProps } = props;
  return <td {...restProps} />;
};

const UserManage = () => {
  const { TreeNode } = Tree;

  const [form] = Form.useForm();
  const { Item } = Form;
  const [selectValue, setSelctValue] = useState(); // 用户鉴权

  const [width, setWidth] = useState(50);
  const [treeLoading, setTreeLoading] = useState(false);
  const [tableLoading, setTableLoading] = useState(false);
  const [loading, setLoading] = useState(true);
  const [currentOrgOperate, setCurrentOrgOperate] = useState(false); // 是否禁用当前机构操作
  const [multiOperate, setMultiOperate] = useState(true); // 是否禁用用户批量操作
  const [multiOperateButtonType, setMultiOperateButtonType] = useState(''); // 更改批量操作按钮样式

  const [treeData, setTreeData] = useState([]); // 用户机构树
  const [treeDataCopy, setTreeDataCopy] = useState([]); // 机构树数据备份，用于更改机构
  const [treeState, setTreeState] = useState(true); // 树第一次加载
  const [treeVisible, setTreeVisible] = useState(true); // 树是否可见
  const [tableData, setTableData] = useState([]); // 用户表
  const [selectColor, setSelectColor] = useState({}); // 当前选中颜色,操作时设置
  const [orgFilters, setOrgFilters] = useState([]); // 用户列筛选
  const [searchWord, setSearchWord] = useState(''); // 关键字
  const [currentSelectOrg1, setCurrentSelectOrg1] = useState('-1');
  const [currentSelectOrg, setCurrentSelectOrg] = useState('-1'); // 左侧机构树-选中组织,字符串类型默认全部机构'-1'，注意用户表中的OUID是数字
  const [currentSelectOldOrg, setCurrentSelectOldOrg] = useState([]); // 更改机构时的树-原先选中组织
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式

  /** ***Modal弹框,是否可视**** */
  const [userVisible, setUserVisible] = useState(false); // 添加用户
  const [addOrgVisible, setAddOrgVisible] = useState(false); // 添加机构
  const [editOrgVisible, setEditOrgVisible] = useState(false); // 编辑机构
  const [deleteOrgVisible, setDeleteOrgVisible] = useState(false); // 删除机构
  const [editOrgExtentVisible, setEditOrgExtentVisible] = useState(false); // 删除机构
  const [roleVisible, setRoleVisible] = useState(false); // 关联角色
  const [changeOrgVisible, setChangeOrgVisible] = useState(false); // 更改机构
  const [passwordVisible, setPasswordVisible] = useState(false); // 修改密码
  const [editUserVisible, setEditUserVisible] = useState(false); // 编辑用户
  // const [freezeUserVisible, setFreezeUserVisible] = useState(false); // 冻结用户
  const [deleteUserVisible, setDeleteUserVisible] = useState(false); // 删除用户
  const [authUserVisible, setAuthUserVisible] = useState(false); // 鉴权用户

  const [orgTitle, setOrgTitle] = useState('当前机构'); // 弹框标题
  const [groupId, setGroupId] = useState();
  const [orgTitle1, setOrgTitle1] = useState('当前机构'); // 弹框标题
  const [description, setDescription] = useState(''); // 机构描述信息
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 已选用户数,机构改变时重置
  const [tableLength, setTableLength] = useState(0); // 当前机构用户总数
  const [orgID, setOrgID] = useState(); // 当前选择的机构ID
  const [newOrgID, setNewOrgID] = useState(); // 更改机构新选择的ID
  const [currentUser, setCurrentUser] = useState({}); // 当前用户

  const [mult, setMult] = useState(''); // 判断是否是批量关联
  const [multiRoleList, setMultiRoleList] = useState([]);
  const [multistationList, setMultiStationList] = useState([]);
  const [userIDs, setUserIDs] = useState(''); // 批量删除的用户
  const [orgIDs, setOrgIDs] = useState(''); // 批量操作的机构
  const [multiDelete, setMultiDelete] = useState(false); // 是否批量删除用户
  const [multiChangeOrgs, setMultiChangeOrgs] = useState(false); // 是否批量更改机构
  const [multiRelateRoles, setMultiRelateRoles] = useState(false); // 是否批量更改机构

  const [rolelist, setRolelist] = useState([]); // 角色列表
  const [stationlist, setStationlist] = useState([]); // 站点列表

  const [orgAreas, setOrgAreas] = useState([]);
  const [currentOrgArea, setCurrentOrgArea] = useState('');
  const [currentOrgDistinct, setCurrentOrgDistinct] = useState('');
  const [saveExtentFlag, setSaveExtentFlag] = useState(0);
  const [filteredValue, setFilteredValue] = useState([]);
  const [keep1, setKeep1] = useState([4]); // 存储树选择
  const [id, setId] = useState('');
  const { Search } = Input;
  const [hoverItemIndex, setHoverItemIndex] = useState(0); // hover流程索引
  const [keepTree, setKeepTree] = useState([]); // 保存所有一级id用于控制只展开一项一级菜单

  const [expendKey, setExpendKey] = useState(''); // 保存默认展开项
  const [expendKeyOrg, setExpendKeyOrg] = useState(''); // 保存默认展开项
  const [menuID, setMenuID] = useState(''); // 选中的树IDs
  const [keepId, setKeepId] = useState('');
  const [flag, setFlag] = useState(1); // 刷新标志
  const userContainer = useRef();
  const flagRef = useRef(1);

  const [searchWordOrg, setSearchWordOrg] = useState('');
  const [keepDataList, setKeepDataList] = useState([]);
  const [siteList, setSiteList] = useState([]);
  const setRowClassName = record =>
    record.userID === selectColor.userID ? styles.clickRowStyle : '';
  // 用户表列名
  const columns = [
    {
      title: '登录名',
      dataIndex: 'loginName',
      key: 'loginName',
      // width: 100,
      // fixed: 'left',
      render: item => searchStyle(item),
    },
    {
      title: '用户姓名',
      dataIndex: 'userName',
      key: 'userName',
      // width: 100,
      render: item => searchStyle(item),
    },
    {
      title: '所在机构',
      dataIndex: 'OUName',
      key: 'OUName',
      // width: 150,
      ellipsis: true,
      filters: orgFilters,
      filteredValue,
      onFilter: (value, record) => record.OUName === value,
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
      key: 'phone',
      // width: 150,
      ellipsis: true,
      render: text => {
        if (text) {
          return searchStyle(text);
        }
        return <span>未绑定</span>;
      },
    },
    {
      title: '钉钉账户',
      dataIndex: 'ddid',
      key: 'ddid',
      // width: 150,
      render: record => {
        if (record) {
          return (
            <Tooltip title={record}>
              <span style={{ color: '#50aefc', cursor: 'pointer' }}>已绑定</span>
            </Tooltip>
          );
        }
        return <span>未绑定</span>;
      },
    },
    {
      title: '微信账户',
      dataIndex: 'wxid',
      key: 'wxid',
      // width: 140,
      render: record => {
        if (record) {
          return (
            <Tooltip title={record}>
              <span style={{ color: '#50aefc', cursor: 'pointer' }}>已绑定</span>
            </Tooltip>
          );
        }
        return <span>未绑定</span>;
      },
    },
    {
      title: '操作',
      key: 'action',
      // fixed: 'right',
      // width: 200,
      align: 'center',
      render: record => (
        <Space size="middle">
          <Tooltip title="设置为主管">
            <Popconfirm
              placement="bottomRight"
              title={
                <p>
                  确定将用户
                  <span className={styles.redText}>{voca.stripTags(record.loginName)}</span>
                  设置为{orgTitle}主管吗？
                </p>
              }
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                console.log(groupId, 'groupId');
                SetGroupManager({ groupId, userId: record.userID }).then(res => {
                  if (res.code === 0) {
                    // eslint-disable-next-line no-unused-expressions
                    currentSelectOrg === '-1' ? submitSearchUser() : onSelect([currentSelectOrg]);
                  } else {
                    notification.error({
                      message: '设置失败',
                      description: res.msg,
                    });
                  }
                });
              }}
            >
              <UserOutlined
                style={{ fontSize: '16px', color: record.isManager ? '#FAAD14' : '#1890FF' }}
              />
            </Popconfirm>
          </Tooltip>
          <Tooltip title="关联权限">
            <IdcardOutlined
              onClick={() => relateRole(record)}
              style={{ fontSize: '16px', color: '#1890FF' }}
            />
          </Tooltip>
          <Tooltip title="更改机构">
            <ApartmentOutlined
              onClick={() => changeOrg(record)}
              style={{ fontSize: '16px', color: '#1890FF' }}
            />
          </Tooltip>
          {/* <Tooltip title="修改密码">
            <UnlockOutlined
              onClick={() => changePassword(record)}
              style={{ fontSize: '16px', color: '#1890FF' }}
            />
          </Tooltip> */}
          {/* <Tooltip title="编辑用户">
            <EditTwoTone onClick={() => editUser(record)} style={{ fontSize: '16px' }} />
          </Tooltip> */}
          {(record.state == 0 || record.state == null) && (
            <>
              {record.loginName == 'panda' || record.loginName == 'admin' ? (
                <StopOutlined style={{ fontSize: '16px' }} />
              ) : (
                <Tooltip title="冻结用户">
                  <Popconfirm
                    placement="bottomRight"
                    title={
                      <p>
                        即将冻结用户{' '}
                        <span className={styles.redText}>{voca.stripTags(record.loginName)}</span>
                        ，是否确认冻结？
                      </p>
                    }
                    okText="确认"
                    cancelText="取消"
                    onConfirm={() => freezeUser(record)}
                  >
                    <StopOutlined style={{ fontSize: '16px', color: '#1890ff' }} />
                  </Popconfirm>
                </Tooltip>
              )}
            </>
          )}
          {record.state == 1 && (
            <>
              {console.log(record.state, 'record.state1')}
              <Tooltip title="解冻用户">
                <Popconfirm
                  placement="bottomRight"
                  title={
                    <p>
                      即将解冻用户
                      <span className={styles.redText}>{voca.stripTags(record.loginName)}</span>
                      ，是否确认解冻？
                    </p>
                  }
                  okText="确认"
                  cancelText="取消"
                  onConfirm={() => freezeUser(record)}
                >
                  <StopOutlined style={{ fontSize: '16px', color: '#e86060' }} />
                </Popconfirm>
              </Tooltip>
            </>
          )}
          {/* <Tooltip title="用户鉴权">
            <Popconfirm
              placement="bottomRight"
              title={
                <div style={{ width: '130px' }}>
                  <Form form={form}>
                    <Item>
                      <Radio.Group value={selectValue} onChange={onTypeChange}>
                        <Space direction="vertical">
                          <Radio value={0}>访客</Radio>
                          <Radio value={1}>普通用户</Radio>
                          <Radio value={2}>管理员</Radio>
                          <Radio value={3}>超级管理员</Radio>
                        </Space>
                      </Radio.Group>
                    </Item>
                  </Form>
                </div>
              }
              okText="确认"
              cancelText="取消"
              onConfirm={() => authUser(record)}
            >
              <LockOutlined
                onClick={() => jianquan(record)}
                style={{ fontSize: '16px', color: '#1890ff' }}
              />
            </Popconfirm>
          </Tooltip> */}
          {record.loginName == 'panda' || record.loginName == 'admin' ? (
            <DeleteOutlined style={{ fontSize: '16px' }} />
          ) : (
            <Popconfirm
              placement="bottomRight"
              title={
                <p>
                  即将删除用户{' '}
                  <span className={styles.redText}>{voca.stripTags(record.loginName)}</span>
                  ，是否确认删除？
                </p>
              }
              // title={`确认删除用户${currentUser}`}
              okText="确认"
              cancelText="取消"
              onConfirm={() => deleteUser(record)}
            >
              <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  useEffect(() => {
    setExpendKey(menuID);
    console.log(expendKey);
  }, [menuID]);
  // 获取用户机构树
  useEffect(() => {
    window.addEventListener('resize', resizeListener);
    GetAllSite().then(res => {
      if (res.code === 0) {
        setSiteList(res.data.map(item => ({ value: item.GroupId, label: item.GroupName })));
      }
    });

    updateTrees();
    return () => {
      window.removeEventListener('resize', resizeListener);
    };
  }, []);

  // 更新获取初始范围
  useEffect(() => {
    getOrgArea().then(res => {
      if (res.msg === 'Ok') {
        console.log(res);
        setOrgAreas(res.Results);
      }
    });
  }, [saveExtentFlag]);

  useEffect(() => {
    if (!changeOrgVisible) {
      setExpendKeyOrg('');
      setSearchWordOrg('');
      GetOUTreeNew({ keyword: '' })
        .then(newres => {
          if (newres.code === 0) {
            let res = newres.data;
            setTreeDataCopy(res);
          }
        })
        .catch(err => {
          setTreeLoading(false);
          message.error(err);
        });
    }
  }, [changeOrgVisible]);
  const resizeListener = () => {
    flagRef.current += 1;
    setFlag(flagRef.current);
  };
  // 模糊查询匹配的样式
  const searchStyle = val => {
    if (!val) {
      return val;
    }
    let n;
    if (showSearchStyle) {
      n = val.replace(new RegExp(searchWord, 'g'), `<span style='color:red'>${searchWord}</span>`);
    } else {
      n = val;
    }
    return <div dangerouslySetInnerHTML={{ __html: n }} />;
  };
  // 获取搜索框的值
  const handleSearch = e => {
    setSearchWord(e.target.value);
  };

  // 获取搜索框的值
  const handleSearchOrg = e => {
    setSearchWordOrg(e.target.value);
  };

  const submitSearch = () => {
    GetOUTreeNew({ keyword: searchWordOrg })
      .then(newres => {
        if (newres.code === 0) {
          let res = newres.data;
          setTreeDataCopy(res);
          console.log(res);
          let aa = [];
          res.map(i => {
            if (i.children.length > 0) {
              aa.push(i.id);
            }
            console.log(i.id);
            aa = i.id;
          });
          setExpendKeyOrg(aa.toString());
        } else {
          notification.error({
            message: '获取失败',
            // eslint-disable-next-line no-undef
            description: res.message,
          });
        }
      })
      .catch(err => {
        setTreeLoading(false);
        message.error(err);
      });
  };
  // 复选框
  const rowSelection = {
    selectedRowKeys,
    onChange: (RowKeys, Rows) => {
      console.log(RowKeys);
      console.log(Rows);
      setSelectedRowKeys(RowKeys);
      getCheckList(RowKeys);
      setUserIDs(RowKeys.toString()); // 数组转字符串，逗号连接
      setOrgIDs(Rows.map(item => item.OUID).toString());
      // 选中行数大于0时设置批量操作可行
      if (RowKeys.length > 0) {
        setSelectColor({});
        setMultiOperate(false);
        setMultiOperateButtonType('primary');
      } else {
        setMultiOperate(true);
        setMultiOperateButtonType('default');
      }
    },
  };
  // 渲染机构树
  const mapTree = org => {
    const haveChildren = Array.isArray(org.children) && org.children.length > 0;
    return {
      title: (
        <div className={styles.title1}>
          <span className={styles.titleText}>
            {org.children.length == 0 ? (
              <ApartmentOutlined
                style={{
                  fontSize: '14px',
                  color: '#1890FF',
                  verticalAlign: 'middle',
                  marginTop: '-3px',
                }}
              />
            ) : (
              <span />
            )}
            <span style={{ marginLeft: '5px' }}>{org.text}</span>
          </span>
          <span
            className={classnames({
              [styles.tip1]: true,
              [styles.listHover]: org === hoverItemIndex,
            })}
            onMouseEnter={() => {
              setHoverItemIndex(org);
            }}
            onMouseLeave={() => {
              setHoverItemIndex('');
            }}
          >
            <Tooltip title="添加用户" className={styles.fs1}>
              <UserAddOutlined
                style={{ marginLeft: 20, lineHeight: '24px' }}
                onClick={e => {
                  e.stopPropagation();
                  addUser();
                }}
                onMouseEnter={e => {
                  setOrgID(org);
                  setOrgTitle1(org.text);
                  console.log(org);
                }}
              />
            </Tooltip>
            <Dropdown overlay={orgButtonMenu1}>
              <EllipsisOutlined
                style={{ marginLeft: 10, fontSize: '20px', lineHeight: '24px' }}
                onClick={e => e.stopPropagation()}
                onMouseEnter={e => {
                  setOrgID(org);
                  setOrgTitle1(org.text);
                  getDescription(org.id);
                  // getMapSetByGroupID(org.id);
                  setCurrentSelectOrg1(org.id);
                  setId(org.text);
                  console.log(org);
                }}
              />
            </Dropdown>
          </span>
        </div>
      ),
      key: org.id,
      // 判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
      children: haveChildren ? org.children.map(i => mapTree(i)) : [],
    };
  };

  const mapTree1 = org => {
    const haveChildren = Array.isArray(org.children) && org.children.length > 0;
    return {
      title: org.text,
      key: org.id,
      // 判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
      children: haveChildren ? org.children.map(i => mapTree1(i)) : [],
    };
  };

  // 重新渲染树
  const updateTrees = () => {
    setTreeLoading(true);
    // getUserTree(-1, -1)
    //   .then(res => {
    //     if (res.length > 0) {
    //       setTreeLoading(false);
    //       setTreeData(res);
    //       setTreeDataCopy(res);
    //       // 第一次加载，默认选择第一个组织
    //       if (treeState) {
    //         onSelect([res[0].id], false);
    //         setTreeState(false);
    //       }
    //     } else {
    //       setTreeLoading(false);
    //       notification.error({
    //         message: '获取失败',
    //         description: res.message,
    //       });
    //     }
    //   })
    //   .catch(err => {
    //     setTreeLoading(false);
    //     message.error(err);
    //   });
    GetOUTreeNew({ selectOU: -1 })
      .then(newres => {
        if (newres.code === 0) {
          let res = newres.data;
          console.log(res);
          setTreeLoading(false);
          setTreeData(res);
          setTreeDataCopy(res);
          let aa = [];
          res.forEach(i => {
            aa.push(i.id);
          });
          setKeepTree(aa);

          // 第一次加载，默认选择第一个组织
          if (treeState) {
            onSelect([res[0].id]);
            setTreeState(false);
          }
        } else {
          setTreeLoading(false);
          notification.error({
            message: '获取失败',
            // eslint-disable-next-line no-undef
            description: res.message,
          });
        }
      })
      .catch(err => {
        setTreeLoading(false);
        message.error(err);
      });
  };

  const updateTrees1 = e => {
    console.log(e);
    setTreeLoading(true);
    GetOUTreeNew({ selectOU: -1 })
      .then(newres => {
        if (newres.code === 0) {
          let res = newres.data;
          console.log(res);
          setTreeLoading(false);
          setTreeData(res);
          setTreeDataCopy(res);
          let aa = [];
          res.forEach(i => {
            aa.push(i.id);
          });
          setKeepTree(aa);
          console.log(e);
          setMenuID(e.toString());
          setExpendKey(e);
        } else {
          setTreeLoading(false);
          notification.error({
            message: '获取失败',
            // eslint-disable-next-line no-undef
            description: res.message,
          });
        }
      })
      .catch(err => {
        setTreeLoading(false);
        message.error(err);
      });
  };

  // 点击树节点，获取当前机构下所有用户
  const onSelect = (props, e) => {
    console.log(props);
    console.log(e);
    if (e) {
      props[0] = e.node.key;
    } else {
      props[0] = props.toString();
    }
    setKeep1(props);
    setTableLoading(true);
    if (!props[0]) {
      setCurrentSelectOrg(currentSelectOrg);
      setCurrentSelectOrg1(currentSelectOrg);
    } else {
      setCurrentSelectOrg(props[0]);
      setCurrentSelectOrg1(props[0]);
    }
    GetMapSetByGroupID({
      groupID: props[0],
    }).then(res => {
      if (res.code === 0) {
        console.log(res);
        if (res.code.MapRange != null) {
          setCurrentOrgArea(res.data.MapRange);
          setCurrentOrgDistinct(res.data.AreeName);
        }
      }
    });
    setOrgID(props[0] || currentSelectOrg);
    // 树节点变化（即props不为空）时才请求，避免重复请求
    if (props[0]) {
      console.log(props[0]);
      setMenuID(props[0]);
      // eslint-disable-next-line no-console

      setGroupId(props[0]);
      getOneOUUserListNew(props[0] || currentSelectOrg)
        .then(res => {
          setCurrentOrgOperate(false); // 重置禁用当前机构操作为false
          setMultiOperate(true); // 重新禁止用户批量操作
          setSelectedRowKeys([]); // 重置选中用户数
          if (res.code === 0) {
            setTableLoading(false);
            setSearchWord(''); // 搜索框置空
            setOrgTitle(res.data.GroupName);
            setDescription(res.data.Description);
            // 返回用户表数据结构处理，扁平化
            console.log(res.data);
            const temp = flatten(getUsers(res.data));
            console.log(temp);
            // 设置过滤字段
            let arr = temp.map(item => item.OUName);
            console.log(arr);
            arr = arr.filter((value, index) => arr.indexOf(value) === index);
            console.log(arr);
            setOrgFilters(arr.map(item => ({ text: item, value: item })));
            setTableLength(temp.length);
            let datalist = [];
            const table = temp.map((item, index) => {
              console.log(item);
              if (item.loginName == 'panda' || item.loginName == 'admin') {
                datalist.push(item.userID);
              }
              item.key = index;
              return item;
            });
            console.log(datalist);
            setKeepDataList(datalist);
            setShowSearchStyle(false);
            setTableData(table);
          } else {
            setTableLoading(false);
            // notification.error({
            //   message: '获取失败',
            //   description: res.msg,
            // });
          }
        })
        .catch(err => {
          setTableLoading(false);
          message.error(err);
        });
    } else {
      setTableLoading(false);
    }
  };

  // 添加用户刷新表数据
  const onSelect1 = () => {
    console.log(orgID);
    setTableLoading(true);
    // eslint-disable-next-line no-console
    getOneOUUserListNew(orgID.id || currentSelectOrg)
      .then(res => {
        setCurrentOrgOperate(false); // 重置禁用当前机构操作为false
        setMultiOperate(true); // 重新禁止用户批量操作
        setSelectedRowKeys([]); // 重置选中用户数
        if (res.code === 0) {
          setTableLoading(false);
          setSearchWord(''); // 搜索框置空
          setOrgTitle(res.data.GroupName);
          setDescription(res.data.Description);
          // 返回用户表数据结构处理，扁平化
          const temp = flatten(getUsers(res.data));
          // 设置过滤字段
          let arr = temp.map(item => item.OUName);
          arr = arr.filter((value, index) => arr.indexOf(value) === index);
          setOrgFilters(arr.map(item => ({ text: item, value: item })));
          setTableLength(temp.length);
          const table = temp.map((item, index) => {
            item.key = index;
            return item;
          });
          setShowSearchStyle(false);
          setTableData(table);
        } else {
          setTableLoading(false);
        }
      })
      .catch(err => {
        setTableLoading(false);
        message.error(err);
      });
  };

  const getDescription = e => {
    getOneOUUserListNew(e).then(res => {
      if (res.code === 0) {
        setDescription(res.data.Description);
      }
    });
  };

  const getMapSetByGroupID = e => {
    GetMapSetByGroupID({
      groupID: e,
    }).then(res => {
      if (res.code === 0) {
        console.log(res);
        setCurrentOrgArea(res.data.MapRange);
        setCurrentOrgDistinct(res.data.AreeName);
      }
    });
  };
  // 返回用户表数据结构处理，扁平化
  const getUsers = orgObj => {
    let result = orgObj.Users;
    result.map(item => {
      item.OUID = orgObj.GroupId;
      item.OUName = orgObj.GroupName;
      return item;
    });
    if (orgObj.Childs.length > 0) result = [...result, ...orgObj.Childs.map(o => getUsers(o))];
    return result;
  };
  const flatten = arr => {
    while (arr.some(item => Array.isArray(item))) {
      arr = [].concat(...arr);
    }
    return arr;
  };
  // 添加用户
  const addUser = e => {
    setUserVisible(true);
  };
  // 添加顶级机构
  const addOrg = () => {
    setAddOrgVisible(true);
    setOrgID('-1');
  };
  // 添加下级机构
  const addSubOrg = e => {
    setAddOrgVisible(true);
  };
  // 编辑机构
  const editOrg = () => {
    setEditOrgVisible(true);
  };
  // 删除机构
  const deleteOrg = () => {
    setDeleteOrgVisible(true);
    console.log(orgID);
    console.log(keep1);
    if (orgID.id == keep1) {
      setTreeState(true);
    } else {
      setTreeState(false);
    }
  };
  // 编辑机构范围
  const EditOrgScope = () => {
    setEditOrgExtentVisible(true);
  };

  // 在currentUser变化后获取角色列表
  // useEffect(() => {
  //   if (currentUser && currentUser.userID) {
  //     getRoleList();
  //   }
  // }, [currentUser]);

  /** ***用户批量操作****** */
  // 关联角色
  const relateRoles = () => {
    setMult('Yes');
    getEmptyRoleList();
    // getCheckList()
    setRoleVisible(true);
    setMultiRelateRoles(true);
  };
  // 更改机构
  const changeOrgs = () => {
    setChangeOrgVisible(true);
    setMultiChangeOrgs(true);
  };
  // 删除用户
  const deleteUsers = () => {
    setDeleteUserVisible(true);
    setMultiDelete(true);
  };

  /** ***右侧表格相关操作****** */
  // 关联角色
  const relateRole = record => {
    // getEmptyRoleList(record.userID);
    setMult('No');
    console.log(record);
    getRoleList(record);
    setRoleVisible(true);
    setCurrentUser(record);
    setSelectColor(record);
  };
  // 更改机构
  const changeOrg = record => {
    setChangeOrgVisible(true);
    setCurrentUser(record);
    setSelectColor(record);
    setCurrentSelectOldOrg(record.OUID);
  };
  // 修改密码
  const changePassword = record => {
    setPasswordVisible(true);
    setCurrentUser(record);
    setSelectColor(record);
  };
  // 编辑用户
  const editUser = record => {
    setEditUserVisible(true);
    setCurrentUser(record);
    setSelectColor(record);
  };
  // 冻结用户
  const freezeUser = record => {
    console.log(currentUser);
    // setFreezeUserVisible(true);
    setCurrentUser(record);
    setSelectColor(record);
    let state = '';
    console.log(record);
    if (record.state === '0' || record.state === null) {
      state = '1';
    } else {
      state = '0';
    }
    UserStateOUNew({ ouid: record.userID })
      .then(res => {
        if (res.code === 0) {
          // 重新获取用户表
          // eslint-disable-next-line no-unused-expressions
          currentSelectOrg === '-1' ? submitSearchUser() : onSelect([currentSelectOrg]);
          notification.success({
            message: '提交成功',
            duration: 2,
          });
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      })
      .catch(err => {
        setTableLoading(false);
        message.error(err);
      });
  };
  // 删除用户
  const deleteUser = record => {
    console.log(record.userName);
    setCurrentUser(record.userName);
    setSelectColor(record);
    DeleteUserNew({
      userID: record.userID,
      ouID: record.OUID,
    })
      .then(res => {
        if (res.code === 0) {
          notification.success({
            message: '提交成功',
            duration: 2,
          });
          // eslint-disable-next-line no-unused-expressions
          currentSelectOrg === '-1' ? submitSearchUser() : onSelect([currentSelectOrg]);
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      })
      .catch(err => {
        setTableLoading(false);
        message.error(err);
      });
  };

  // 用户鉴权
  //   useEffect(() => {
  //     currentUser.userID
  //     GetUserAuthSet({
  //         UserId: currentUser.userID
  //     }).then(
  //         res => {
  //             if(res.code == 0){
  //                 setSelctValue(res.data)
  //                 console.log(selectValue);
  //                 console.log(res.data);
  //             }
  //         }
  //     )
  // }, [currentUser])
  const jianquan = record => {
    GetUserAuthSet({
      UserId: record.userID,
    }).then(res => {
      if (res.code === 0) {
        setSelctValue(res.data);
        console.log(res.data);
      }
    });
  };
  const onTypeChange = value => {
    setSelctValue(value.target.value);
  };
  const authUser = record => {
    setCurrentUser(record);
    console.log(selectValue);
    AddUserAuthSetting({
      userId: record.userID,
      userLevel: selectValue,
    }).then(res => {
      if (res.code === 0) {
        message.info('提交成功');
      }
    });
  };

  // 查找用户
  const submitSearchUser = () => {
    if (!searchWord || searchWord.trim(' ').length == 0) {
      message.warning('请输入搜索内容');
      return;
    }

    GetUserByKeyNew({ key: searchWord })
      .then(res => {
        if (res.code === 0) {
          setSelectedRowKeys([]); // 重置选中用户数
          setCurrentOrgOperate(true); // 禁止当前机构操作
          setMultiOperate(true); // 禁用批量操作
          setOrgTitle('全部机构搜索结果'); // 设置表头
          setCurrentSelectOrg('-1'); // 清空选中机构
          console.log(res.data);
          setShowSearchStyle(true);
          setTableData(res.data);
          setTableLength(res.data.length);
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });
  };

  /** ***表单提交相关操作****** */
  // 根据当前 userID 获取用户关联角色
  const getRoleList = e => {
    setLoading(true);
    GetUserRelationListNew({ userID: e.userID })
      .then(res => {
        console.log(111);

        if (res.code === 0) {
          const { roleList, stationList } = res.data;
          console.log(roleList);
          setRolelist(roleList);
          setStationlist(stationList);
          setLoading(false);
        } else {
          console.log(res);
          setLoading(false);
        }
      })
      .catch(err => {
        setLoading(false);
        setTableLoading(false);
        message.error(err);
      });
  };
  // 获取全部未勾选的角色列表与站点列表
  const getEmptyRoleList = () => {
    setLoading(true);
    GetUserRelationListNew({ userID: 0 })
      .then(res => {
        console.log(222);
        if (res.code === 0) {
          const { roleList, stationList } = res.data;
          setRolelist(roleList);
          setStationlist(stationList);
          setLoading(false);
        } else {
          console.log(res.msg);
          setLoading(false);
        }
      })
      .catch(err => {
        setLoading(false);
        setTableLoading(false);
        message.error(err);
      });
  };

  const getCheckList = e => {
    console.log(e);
    let aa = [];
    let bb = [];
    loadAllUserRole(e).then(res => {
      if (res.code === 0) {
        if (res.data.roleList !== undefined) {
          // eslint-disable-next-line array-callback-return
          Object.keys(res.data.roleList).map((item, index) => {
            aa.push(item);
          });
        }
        if (res.data.siteList !== undefined) {
          // eslint-disable-next-line array-callback-return
          Object.keys(res.data.siteList).map((item1, index1) => {
            bb.push(item1);
          });
        }
        console.log(aa);
        console.log(bb);
        setMultiRoleList(aa);
        setMultiStationList(bb);
      }
    });
  };
  // 提交-更改机构
  const submitChangeOrg = () => {
    // addToOrg(currentUser.userID, currentUser.OUID, newOrgID)
    // .then(res => {
    //   if (res.success) {
    //     setChangeOrgVisible(false);
    //     // 跳转到新组织机构下的用户表
    //     onSelect([newOrgID]);
    //     // setExpandedKeys([`${newOrgID}`]);
    //     notification.success({
    //       message: '提交成功',
    //       duration: 2,
    //     });
    //   } else {
    //     notification.error({
    //       message: '提交失败',
    //       description: res.message,
    //     });
    //   }
    // })
    // .catch(err => {
    //   message.error(err);
    // });
    JumpToAnotherOUNew({
      userID: currentUser.userID,
      oldOUID: currentUser.OUID,
      newOUID: newOrgID,
    })
      .then(res => {
        if (res.code === 0) {
          setChangeOrgVisible(false);
          // 跳转到新组织机构下的用户表
          onSelect([newOrgID]);
          // setExpandedKeys([`${newOrgID}`]);
          notification.success({
            message: '提交成功',
            duration: 2,
          });
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });
  };

  // 提交-批量更改机构
  const submitChangeOrgs = () =>
    addToOrgs(userIDs, orgIDs, newOrgID)
      .then(res => {
        if (res.code === 0) {
          setChangeOrgVisible(false);
          // 跳转到新组织机构下的用户表
          const temp = orgIDs.split(',');
          // 批量更改机构成功后设置老的orgIDs为全部是newOrgID的数组，并转字符串
          setOrgIDs(temp.map(() => newOrgID).toString());
          onSelect([newOrgID]);
          notification.success({
            message: '提交成功',
            duration: 2,
          });
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });

  // 提交-冻结用户
  // const submitFreezeUser = () => {
  //   let state = '';
  //   if (currentUser.state === '0' || currentUser.state === null) {
  //     state = '1';
  //   } else {
  //     state = '0';
  //   }
  //   // postSetUserState(currentUser.userID, state)
  //   //   .then(res => {
  //   //     if (res.success) {
  //   //       setFreezeUserVisible(false);
  //   //       // 重新获取用户表
  //   //       // eslint-disable-next-line no-unused-expressions
  //   //       currentSelectOrg === '-1'
  //   //         ? submitSearchUser()
  //   //         : onSelect([currentSelectOrg]);
  //   //       notification.success({
  //   //         message: '提交成功',
  //   //         duration: 2,
  //   //       });
  //   //     } else {
  //   //       notification.error({
  //   //         message: '提交失败',
  //   //         description: res.message,
  //   //       });
  //   //     }
  //   //   })
  //   //   .catch(err => {
  //   //     setTableLoading(false);
  //   //     message.error(err);
  //   //   });
  //   UserStateOUNew({ ouid: currentUser.userID, state })
  //     .then(res => {
  //       if (res.code === 0) {
  //         // setFreezeUserVisible(false);
  //         // 重新获取用户表
  //         // eslint-disable-next-line no-unused-expressions
  //         currentSelectOrg === '-1'
  //           ? submitSearchUser()
  //           : onSelect([currentSelectOrg]);
  //         notification.success({
  //           message: '提交成功',
  //           duration: 2,
  //         });
  //       } else {
  //         notification.error({
  //           message: '提交失败',
  //           description: res.msg,
  //         });
  //       }
  //     })
  //     .catch(err => {
  //       setTableLoading(false);
  //       message.error(err);
  //     });
  // };
  // 提交-删除用户
  const submitDeleteUser = () => {
    DeleteUserNew({
      userID: currentUser.userID,
      ouID: currentUser.OUID,
    })
      .then(res => {
        if (res.code === 0) {
          notification.success({
            message: '提交成功',
            duration: 2,
          });
          // eslint-disable-next-line no-unused-expressions
          currentSelectOrg === '-1' ? submitSearchUser() : onSelect([currentSelectOrg]);
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      })
      .catch(err => {
        setTableLoading(false);
        message.error(err);
      });
  };
  // 提交-批量删除用户
  const submitDeleteUsers = () => {
    console.log(userIDs);
    console.log(keepDataList);
    console.log(userIDs.split(','));
    let data = [];
    keepDataList.length > 0 &&
      keepDataList.map(i => {
        let aa = userIDs.split(',').indexOf(i);
        console.log(aa);
        if (aa !== -1) {
          data.push(aa);
        }
      });
    console.log(data);
    if (data.length > 0) {
      notification.error({
        message: '操作失败',
        description: '选中项包含不可删除的用户panda或admin',
      });
    } else {
      multiDeleteUsers(userIDs)
        .then(res => {
          if (res.code === 0) {
            setDeleteUserVisible(false);
            notification.success({
              message: '提交成功',
              duration: 2,
            });
            // 重新获取用户表,查找用户时currentSelectOrg为'-1'，无需跳转
            // eslint-disable-next-line no-unused-expressions
            currentSelectOrg === '-1' ? submitSearchUser() : onSelect([currentSelectOrg]);
          } else {
            notification.error({
              message: '提交失败',
              description: res.msg,
            });
          }
        })
        .catch(err => {
          setTableLoading(false);
          message.error(err);
        });
    }
  };
  // 重置默认第一个
  const handleReset = () => {
    GetOUTreeNew({ selectOU: -1 })
      .then(newres => {
        if (newres.code === 0) {
          let res = newres.data;
          setTreeLoading(false);
          setSearchWord('');
          setFilteredValue([]);
          // 第一次加载，默认选择第一个组织
          onSelect([res[0].id], false);
        } else {
          setTreeLoading(false);
          notification.error({
            message: '获取失败',
            // eslint-disable-next-line no-undef
            description: res.message,
          });
        }
      })
      .catch(err => {
        setTreeLoading(false);
        message.error(err);
      });
  };
  const onChangeInput = filters => {
    setFilteredValue(filters.OUName);
  };

  // 更改机构范围
  const submitExtent = (extent, areaName, flags) => {
    setTreeLoading(true);
    console.log(extent);
    console.log(areaName);
    console.log(flags);
    console.log(currentSelectOrg1);
    if (flags === 0) {
      setTreeLoading(false);
      notification.warn({
        message: '提交失败',
        description: '请框选范围',
      });
    } else if (extent) {
      setOrgArea({
        OUID: currentSelectOrg1,
        areaName,
        extent,
      }).then(res => {
        if (res.msg === '') {
          setTreeLoading(false);
          setEditOrgExtentVisible(false);
          setSaveExtentFlag(saveExtentFlag + 1);
          message.success('机构范围设置成功!');
        } else {
          setTreeLoading(false);
          setEditOrgExtentVisible(false);
          message.warn(res.Message);
        }
      });
    }
  };
  // 返回拖拽完毕后的信息
  const loop = (datas, key, parentID, callback) => {
    for (let i = 0; i < datas.length; i++) {
      if (datas[i].id === key) {
        return callback(datas[i], i, datas, parentID);
      }
      if (datas[i].children) {
        loop(datas[i].children, key, datas[i].id, callback);
      }
    }
  };
  // 树的拖拽
  const handleDrop = infos => {
    console.log(infos);
    const dropKey = infos.node.key;
    const dragKey = infos.dragNode.key;
    const dropPos = infos.node.pos.split('-');
    const dropPosition = infos.dropPosition - Number(dropPos[dropPos.length - 1]);

    const datas = JSON.parse(JSON.stringify(treeData));
    console.log(dropKey, 'dropKey');
    console.log(dragKey, 'dragKey');
    // 找到拖拽的元素
    let dragObj;
    let dropObj;
    let parId;
    let dragList;
    // 保存拖拽到的节点信息
    loop(datas, dropKey, -1, item => {
      dropObj = item;
    });
    // 保存节点信息并删除节点
    loop(datas, dragKey, -1, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });
    // 将节点插入到正确的位置
    if (!infos.dropToGap) {
      console.log('33333333333');
      dropObj.children = dropObj.children || [];
      // 在哪里插入,示例添加到头部，可以是随意位置
      dropObj.children.unshift(dragObj);
      parId = dropObj.id;
      dragList = dropObj.children.map(val => val.id);
    } else {
      let ar;
      let i;
      loop(datas, dropKey, -1, (item, index, arr, parentID) => {
        ar = arr;
        i = index;
        parId = parentID;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
      dragList = ar.map(ele => ele.id);
    }
    DragGroup({
      dragGroupType: 2,
      groupId: dragKey.toString(),
      groupList: dragList.map(item => item.toString()),
      parentId: parId.toString(),
    }).then(res => {
      if (res.code === 0) {
        updateTrees();
      } else {
        message.error(res.msg);
      }
    });
  };
  const addChange = e => {
    e.domEvent.stopPropagation();
  };

  /** ***操作按钮**** */
  // 机构操作
  const orgButtonMenu = (
    <Menu onClick={e => addChange(e)}>
      <Menu.Item key="1" onClick={addUser} icon={<UserAddOutlined style={{ marginTop: '5px' }} />}>
        添加用户
      </Menu.Item>
    </Menu>
  );
  const orgButtonMenu1 = (
    <Menu onClick={e => addChange(e)}>
      <Menu.Item
        key="2"
        onClick={addSubOrg}
        icon={<ClusterOutlined style={{ marginTop: '5px' }} />}
      >
        添加下级机构
      </Menu.Item>
      <Menu.Item key="3" onClick={editOrg} icon={<EditOutlined style={{ marginTop: '5px' }} />}>
        编辑当前机构
      </Menu.Item>
      <Menu.Item key="4" onClick={deleteOrg} icon={<DeleteOutlined style={{ marginTop: '5px' }} />}>
        删除当前机构
      </Menu.Item>
      {/* <Menu.Item
        key="5"
        onClick={EditOrgScope}
        icon={<BorderlessTableOutlined style={{ marginTop: '5px' }} />}
      >
        编辑机构范围
      </Menu.Item> */}
    </Menu>
  );
  // 用户批量操作
  const userButtonMenu = (
    <Menu>
      <Menu.Item key="1" onClick={relateRoles} icon={<IdcardOutlined />}>
        批量关联角色
      </Menu.Item>
      <Menu.Item key="2" onClick={changeOrgs} icon={<ApartmentOutlined />}>
        批量更改机构
      </Menu.Item>
      <Menu.Item key="3" onClick={deleteUsers} icon={<DeleteOutlined />}>
        批量删除用户
      </Menu.Item>
    </Menu>
  );

  const kee = () => {
    setUserVisible(false);
  };

  return (
    <PageContainer className={styles.userManageContainer}>
      <div className={styles.contentContainer}>
        {/* 左侧机构树 */}
        <Spin spinning={treeLoading} tip="loading...">
          <Card
            style={{ overflowY: 'hidden', height: '100%' }}
            className={classnames({
              [styles.orgContainer]: true,
              [styles.orgContainerHide]: !treeVisible,
            })}
          >
            <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
              <div style={{ display: 'flex' }}>
                <span
                  style={{
                    fontSize: '15px ',
                    fontWeight: 'bold',
                    marginLeft: '15px',
                  }}
                >
                  机构列表
                </span>
                <Tooltip title="添加顶级机构">
                  <PlusSquareFilled
                    onClick={() => addOrg()}
                    style={{
                      color: '#1890FF',
                      fontSize: '25px',
                      verticalAlign: 'middle',
                      marginLeft: '64%',
                    }}
                  />
                </Tooltip>
              </div>
              <hr style={{ width: '95%', color: '#eeecec', marginLeft: '15px' }} />
              {treeData.length > 0 && (
                <div style={{ height: '100%', overflowY: 'scroll' }}>
                  <Tree
                    showIcon="true"
                    blockNode
                    autoExpandParent
                    onSelect={onSelect}
                    treeData={treeData.map(t => mapTree(t))}
                    draggable
                    onDrop={handleDrop}
                    selectedKeys={[menuID]}
                    keepTree={keepTree}
                    expandedKeys={expendKey}
                  />
                </div>
              )}
            </div>
            <div className={styles.switcher}>
              {treeVisible && (
                <Tooltip title="隐藏机构列表">
                  <DoubleLeftOutlined onClick={() => setTreeVisible(false)} />
                </Tooltip>
              )}
              {!treeVisible && (
                <Tooltip title="显示机构列表">
                  <DoubleRightOutlined onClick={() => setTreeVisible(true)} />
                </Tooltip>
              )}
            </div>
          </Card>
        </Spin>

        {/* 右侧用户表 */}
        <div
          ref={userContainer}
          className={classnames({
            [styles.userContainer]: true,
          })}
        >
          <div style={{ height: '50px' }}>
            <span
              className={styles.title}
              title={`${orgTitle}（已选${selectedRowKeys.length}/共${tableLength}人）`}
            >
              {orgTitle}（已选{selectedRowKeys.length}/共{tableLength}人）
            </span>
            <span style={{ float: 'right', margin: '10px' }}>
              <Search
                style={{ width: 260, marginRight: '15px' }}
                placeholder="搜索登录名/用户姓名/手机号"
                onSearch={submitSearchUser}
                onChange={e => handleSearch(e)}
                enterButton
                value={searchWord}
              />

              <Button style={{ marginRight: '15px' }} icon={<SyncOutlined />} onClick={handleReset}>
                重置
              </Button>

              <Dropdown overlay={userButtonMenu} disabled={multiOperate}>
                <Button type={multiOperateButtonType}>
                  用户批量操作 <DownOutlined />
                </Button>
              </Dropdown>
            </span>
          </div>
          {userContainer.current && (
            <Table
              // style={{ height: 'calc(100% -50px)' }}
              rowSelection={{
                type: 'checkbox',
                ...rowSelection,
              }}
              rowClassName={setRowClassName}
              size="small"
              rowKey={record => record.userID}
              locale={zhCN}
              bordered
              columns={columns}
              dataSource={tableData}
              loading={tableLoading}
              scroll={{
                x: 'max-content',
                y: `calc(${userContainer.current.clientHeight}px - 150px)`,
              }}
              // scroll={{ x: 'max-content' }}
              pagination={{
                showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 20,
                showQuickJumper: true,
                showSizeChanger: true,
              }}
              onRow={record => ({
                onDoubleClick: () => {
                  editUser(record);
                },
              })}
              onChange={onChangeInput}
            />
          )}
        </div>

        {/* Modal弹框 */}
        {/* 添加用户 */}
        <AddUserModal
          visible={userVisible}
          orgID={orgID}
          orgTitle1={orgTitle1}
          onCancel={kee}
          updateTrees1={updateTrees1}
          siteList={siteList}
          onSelect={onSelect}
        />
        {/* 添加下级机构 */}
        <AddSubOrgModal
          visible={addOrgVisible}
          orgTitle1={orgTitle1}
          orgID={orgID}
          onCancel={() => setAddOrgVisible(false)}
          onSelect={onSelect}
          updateTrees1={updateTrees1}
        />
        {/* 编辑机构 */}
        <EditOrgModal
          visible={editOrgVisible}
          orgID={orgID}
          orgTitle1={orgTitle1}
          description={description}
          onCancel={() => setEditOrgVisible(false)}
          updateTrees={updateTrees}
        />
        {/* 删除机构 */}
        <DeleteOrgModal
          title="删除机构"
          visible={deleteOrgVisible}
          orgTitle={orgTitle1}
          orgID={orgID}
          updateTrees={updateTrees}
          onCancel={() => setDeleteOrgVisible(false)}
        />
        {/* 关联角色 */}
        <RelateRoleModal
          currentUser={currentUser}
          userIDs={userIDs}
          currentSelectOrg={currentSelectOrg}
          visible={roleVisible}
          rolelist={rolelist}
          multiRoleList={multiRoleList}
          multistationList={multistationList}
          mult={mult}
          loading={loading}
          stationlist={stationlist}
          multiRelateRoles={multiRelateRoles}
          onSelect={onSelect}
          onCancel={() => {
            setRoleVisible(false);
            setMultiRelateRoles(false);
          }}
        />
        {/* 更改机构 */}
        <Modal
          title="更改机构"
          visible={changeOrgVisible}
          onOk={multiChangeOrgs ? submitChangeOrgs : submitChangeOrg}
          maskClosable={false}
          onCancel={() => {
            setChangeOrgVisible(false);
            setMultiChangeOrgs(false);
          }}
          okText="确认"
          cancelText="取消"
          width="500px"
        >
          {/* <span>请选择要更改的目标机构：</span> */}
          <Search
            style={{ width: 260, marginBottom: '10px' }}
            placeholder="请输入机构名称"
            onSearch={submitSearch}
            onChange={e => handleSearchOrg(e)}
            enterButton
            value={searchWordOrg}
          />
          <div style={{ height: '500px', overflowY: 'scroll' }}>
            {changeOrgVisible && treeDataCopy.length > 0 && (
              <Tree
                showIcon="true"
                showLine={{ showLeafIcon: false }}
                // defaultExpandAll
                // 未切换时原先的节点，注意要转字符串
                selectedKeys={[`${currentSelectOldOrg}`]}
                onSelect={value => {
                  setNewOrgID(value[0]);
                  // 切换后选中的节点
                  setCurrentSelectOldOrg(value[0]);
                }}
                expandedKeys={expendKeyOrg}
                treeData={treeDataCopy.map(t => mapTree1(t))}
              />
            )}
          </div>
        </Modal>
        {/* 修改密码 */}
        <ChangePasswordModal
          visible={passwordVisible}
          currentUser={currentUser}
          submitSearchUser={submitSearchUser}
          currentSelectOrg={currentSelectOrg}
          onSelect={onSelect}
          onCancel={() => setPasswordVisible(false)}
        />
        {/* 编辑用户 */}
        <EditUserModal
          visible={editUserVisible}
          currentUser={currentUser}
          submitSearchUser={submitSearchUser}
          currentSelectOrg={currentSelectOrg}
          onSelect={onSelect}
          onCancel={() => setEditUserVisible(false)}
        />
        {/* 冻结用户 */}
        {/* <Modal
          title="请确认"
          visible={freezeUserVisible}
          onOk={submitFreezeUser}
          onCancel={() => setFreezeUserVisible(false)}
          okText="确认"
          cancelText="取消"
        >
          <p>
            即将{+currentUser.state ? '激活' : '冻结'}用户{' '}
            <span className={styles.redText}>
              {voca.stripTags(currentUser.loginName)}
            </span>
            ，是否确认
            {+currentUser.state ? '激活' : '冻结'}？
          </p>
        </Modal> */}
        {/* 多选删除用户 */}
        <Modal
          title="确认删除用户"
          visible={deleteUserVisible}
          onOk={multiDelete ? submitDeleteUsers : submitDeleteUser}
          maskClosable={false}
          onCancel={() => {
            setDeleteUserVisible(false);
            setMultiDelete(false);
          }}
          okText="确认"
          cancelText="取消"
        >
          <p>将删除多个用户, 是否确认删除？</p>
        </Modal>
        {/* <MapScopeEditModal
          title={id}
          mapId={createGuid()}
          visible={editOrgExtentVisible}
          stationId={currentSelectOrg1}
          onCancel={() => setEditOrgExtentVisible(false)}
          confirmModal={submitExtent}
          distinct={currentOrgDistinct}
          extent={currentOrgArea}
        /> */}
        {/* <AuthModal
          visible={authUserVisible}
          currentUser={currentUser}
          onCancel={() => setAuthUserVisible(false)}
        /> */}
      </div>
    </PageContainer>
    // <DraggleLayout
    //     containerWidth={550}
    //     containerHeight={220}
    //     min={50}
    //     max={500}
    //     initLeftWidth={100}
    //     onWidthChange={w => setWidth(w)}
    //     handler={
    //       <div
    //         style={{
    //           width: 4,
    //           height: '100%',
    //           background: 'rgb(77, 81, 100)',
    //         }}
    //       />
    //     }
    //   >
    //     <div
    //       style={{
    //         backgroundColor: `rgb(36, 205, 208)`,
    //         color: `#fff`,
    //         height: '100%',
    //         display: 'flex',
    //         alignItems: 'center',
    //         justifyContent: 'center',
    //       }}
    //     >
    //       left
    //     </div>
    //     <div
    //       style={{
    //         backgroundColor: `rgb(116, 140, 253)`,
    //         color: `#fff`,
    //         height: '100%',
    //         display: 'flex',
    //         alignItems: 'center',
    //         justifyContent: 'center',
    //       }}
    //     >
    //       right
    //     </div>
    //   </DraggleLayout>
  );
};

export default UserManage;
