/* eslint-disable eqeqeq */
import React, { useState, useEffect } 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,
} 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,
} from '@/services/userCenter/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 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 [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 setRowClassName = record =>
    record.userID === selectColor.userID ? styles.clickRowStyle : '';
  // 用户表列名
  const columns = [
    {
      title: '登录名',
      dataIndex: 'loginName',
      key: 'loginName',
      width: 150,
      // fixed: 'left',
      render: item => searchStyle(item),
    },
    {
      title: '用户姓名',
      dataIndex: 'userName',
      key: 'userName',
      width: 150,
      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: 250,
      align: 'center',
      render: record => (
        <Space size="middle">
          <Tooltip title="关联角色">
            <IdcardOutlined
              onClick={() => relateRole(record)}
              style={{ fontSize: '20px', 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) && (
            <>
              {/* {     console.log(record.state,'record.state')} */}
              <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>
            </>
          )}
          {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)}
                >
                  <UserOutlined
                    style={{ fontSize: '16px', color: '#1890ff' }}
                  />
                </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>
          <Tooltip title="删除用户">
            <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>
          </Tooltip>
        </Space>
      ),
    },
  ];
  // 模糊查询匹配的样式
  const searchStyle = 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 rowSelection = {
    selectedRowKeys,
    onChange: (RowKeys, 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.text}</span>
          <span className={styles.tip1}>
            <Tooltip title="" className={styles.fs1}>
              <Dropdown overlay={orgButtonMenu}>
                <PlusOutlined
                  style={{ marginLeft: 20 }}
                  onClick={e => e.stopPropagation()}
                  onMouseEnter={e => {
                    setOrgID(org);
                    setOrgTitle1(org.text);
                    console.log(org);
                  }}
                />
              </Dropdown>
            </Tooltip>

            <Dropdown overlay={orgButtonMenu1}>
              <EllipsisOutlined
                style={{ marginLeft: 10, fontSize: '20px' }}
                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);
          // 第一次加载，默认选择第一个组织
          if (treeState) {
            onSelect([res[0].id], false);
            setTreeState(false);
          }
        } else {
          setTreeLoading(false);
          notification.error({
            message: '获取失败',
            // eslint-disable-next-line no-undef
            description: res.message,
          });
        }
      })
      .catch(err => {
        setTreeLoading(false);
        message.error(err);
      });
  };

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

  // 点击树节点，获取当前机构下所有用户
  const onSelect = (props, e) => {
    console.log(e);
    console.log(props);
    console.log(props[0]);
    console.log(props[0].id);
    if (props[0].id !== undefined) {
      props[0] = props[0].id;
    }
    setKeep1(props);
    console.log(keep1);
    setTableLoading(true);
    if (e) {
      setOrgTitle(e.node.title.props.children[0].props.children);
    }
    if (!props[0]) {
      setCurrentSelectOrg(currentSelectOrg);
      setCurrentSelectOrg1(currentSelectOrg);
    } else {
      setCurrentSelectOrg(props[0]);
      setCurrentSelectOrg1(props[0]);
    }
    // orgAreas.map((item)=>{

    //     if(item.OUID == props[0]){
    //       setCurrentOrgArea(item.Extent)
    //       setCurrentOrgDistinct(item.AreaName)
    //     }
    // })
    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]) {
      // eslint-disable-next-line no-console
      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);
            // 返回用户表数据结构处理，扁平化
            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);
            // notification.error({
            //   message: '获取失败',
            //   description: res.msg,
            // });
          }
        })
        .catch(err => {
          setTableLoading(false);
          message.error(err);
        });
    } else {
      setTableLoading(false);
    }
  };

  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);
    // 删除后默认选择第一个组织
    setTreeState(true);
  };
  // 编辑机构范围
  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 => {
    // 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 = () => {
    // getUserByKey(searchWord)
    //   .then(res => {
    //     if (res.success) {
    //       setSelectedRowKeys([]); // 重置选中用户数
    //       setCurrentOrgOperate(true); // 禁止当前机构操作
    //       setMultiOperate(true); // 禁用批量操作
    //       setOrgTitle('全部机构搜索结果'); // 设置表头
    //       setCurrentSelectOrg('-1'); // 清空选中机构
    //       setTableData(res.root);
    //       setTableLength(res.root.length);
    //     } else {
    //       notification.error({
    //         message: '提交失败',
    //         description: res.message,
    //       });
    //     }
    //   })
    //   .catch(err => {
    //     message.error(err);
    //   });
    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);
    // getUserRelationList(currentUser.userID)
    //   .then(res => {
    //     setLoading(false);
    //     if (res.success) {
    //       const { roleList, stationList } = res;
    //       setRolelist(roleList);
    //       setStationlist(stationList);
    //     } else {
    //       notification.error({
    //         message: '提交失败',
    //         description: res.message,
    //       });
    //     }
    //   })
    //   .catch(err => {
    //     setLoading(false);
    //     setTableLoading(false);
    //     message.error(err);
    //   });
    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);
    // getUserRelationList('')
    //   .then(res => {
    //     setLoading(false);
    //     if (res.roleList && res.roleList.length > 0) {
    //       const { roleList, stationList } = res;
    //       setRolelist(roleList);
    //       setStationlist(stationList);
    //     } else {
    //       notification.error({
    //         message: '提交失败',
    //         description: res.message,
    //       });
    //     }
    //   })
    //   .catch(err => {
    //     setLoading(false);
    //     setTableLoading(false);
    //     message.error(err);
    //   });
    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 => {
    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 = () => {
    // postDeleteUser(currentUser.userID)
    //   .then(res => {
    //     if (res.success) {
    //       setDeleteUserVisible(false);
    //       notification.success({
    //         message: '提交成功',
    //         duration: 2,
    //       });
    //       // eslint-disable-next-line no-unused-expressions
    //       currentSelectOrg === '-1'
    //         ? submitSearchUser()
    //         : onSelect([currentSelectOrg]);
    //     } else {
    //       notification.error({
    //         message: '提交失败',
    //         description: res.message,
    //       });
    //     }
    //   })
    //   .catch(err => {
    //     setTableLoading(false);
    //     message.error(err);
    //   });
    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 = () => {
    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, flag) => {
    setTreeLoading(true);
    console.log(extent);
    console.log(areaName);
    console.log(flag);
    console.log(currentSelectOrg1);
    if (flag === 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 addChange = e => {
    e.domEvent.stopPropagation();
  };
  /** ***操作按钮**** */
  // 机构操作
  const orgButtonMenu = (
    <Menu onClick={e => addChange(e)}>
      <Menu.Item key="1" onClick={addUser} icon={<UserAddOutlined />}>
        添加用户
      </Menu.Item>
      <Menu.Item key="2" onClick={addSubOrg} icon={<UsergroupAddOutlined />}>
        添加下级机构
      </Menu.Item>
    </Menu>
  );
  const orgButtonMenu1 = (
    <Menu onClick={e => addChange(e)}>
      <Menu.Item key="3" onClick={editOrg} icon={<EditOutlined />}>
        编辑当前机构
      </Menu.Item>
      <Menu.Item key="4" onClick={deleteOrg} icon={<DeleteOutlined />}>
        删除当前机构
      </Menu.Item>
      <Menu.Item
        key="5"
        onClick={EditOrgScope}
        icon={<BorderlessTableOutlined />}
      >
        编辑机构范围
      </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' }}
            className={classnames({
              [styles.orgContainer]: true,
              [styles.orgContainerHide]: !treeVisible,
            })}
          >
            <div>
              <span
                style={{
                  fontSize: '15px ',
                  fontWeight: 'bold',
                  marginLeft: '15px',
                }}
              >
                机构列表
              </span>
              <Tooltip title="添加顶级机构">
                <PlusSquareFilled
                  onClick={() => addOrg()}
                  style={{
                    color: '#1890FF',
                    fontSize: '25px',
                    verticalAlign: 'middle',
                    marginLeft: '67%',
                  }}
                />
              </Tooltip>
              <hr
                style={{ width: '95%', color: '#eeecec', marginLeft: '15px' }}
              />
              {treeData.length > 0 && (
                <Tree
                  showIcon="true"
                  // showLine={{ showLeafIcon: false }}
                  blockNode
                  autoExpandParent
                  // expandedKeys={[currentSelectOrg]}
                  // defaultExpandAll
                  selectedKeys={[currentSelectOrg]}
                  onSelect={onSelect}
                  height={
                    treeData.length && treeData.length > 30
                      ? treeData.length * 18 + 50
                      : 1000
                  }
                  treeData={treeData.map(t => mapTree(t))}
                />
              )}
            </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
          className={classnames({
            [styles.userContainer]: true,
            [styles.userContainerHide]: !treeVisible,
          })}
        >
          <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 }}
                placeholder="搜索登录名/用户姓名/手机号"
                onSearch={submitSearchUser}
                onChange={e => handleSearch(e)}
                enterButton
                value={searchWord}
              />

              <Button icon={<SyncOutlined />} onClick={handleReset}>
                重置
              </Button>

              <Dropdown overlay={userButtonMenu} disabled={multiOperate}>
                <Button type={multiOperateButtonType}>
                  用户批量操作 <DownOutlined />
                </Button>
              </Dropdown>
            </span>
          </div>
          <Table
            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(100vh - 210px)' }}
            // scroll={{ x: 'max-content' }}
            pagination={{
              showTotal: (total, range) =>
                `第${range[0]}-${range[1]} 条/共 ${total} 条`,
              pageSizeOptions: [10, 20, 50, 100],
              defaultPageSize: 20,
              showQuickJumper: true,
              showSizeChanger: true,
            }}
            onChange={onChangeInput}
          />
        </div>

        {/* Modal弹框 */}
        {/* 添加用户 */}
        <AddUserModal
          title={`在${orgTitle1}下添加用户`}
          visible={userVisible}
          orgID={orgID}
          onCancel={kee}
          onSelect={() => onSelect([orgID])}
        />
        {/* 添加下级机构 */}
        <AddSubOrgModal
          title={orgID === '-1' ? '添加顶级机构' : `在${orgTitle1}下添加机构`}
          visible={addOrgVisible}
          orgID={orgID}
          onCancel={() => setAddOrgVisible(false)}
          // onSelect={onSelect}
          updateTrees={updateTrees}
        />
        {/* 编辑机构 */}
        <EditOrgModal
          title={`编辑${orgTitle1}`}
          visible={editOrgVisible}
          orgID={orgID}
          orgTitle={orgTitle1}
          description={description}
          onCancel={() => setEditOrgVisible(false)}
          // onSelect={onSelect}
          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}
          onCancel={() => {
            setChangeOrgVisible(false);
            setMultiChangeOrgs(false);
          }}
          okText="确认"
          cancelText="取消"
          width="500px"
        >
          <span>请选择要更改的目标机构：</span>
          {changeOrgVisible && treeDataCopy.length > 0 && (
            <Tree
              showIcon="true"
              showLine={{ showLeafIcon: false }}
              // defaultExpandAll
              // 未切换时原先的节点，注意要转字符串
              selectedKeys={[`${currentSelectOldOrg}`]}
              onSelect={value => {
                setNewOrgID(value[0]);
                // 切换后选中的节点
                setCurrentSelectOldOrg(value[0]);
              }}
              treeData={treeDataCopy.map(t => mapTree1(t))}
            />
          )}
        </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}
          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;
