/* eslint-disable no-inner-declarations */
import React, { Component } from 'react';
import InfiniteScroll from 'react-infinite-scroller';
import moment from 'moment';
// import getDepartMockData from './departmentMockData';
import { connect } from 'dva';
import {
  Form,
  Input,
  Button,
  Icon,
  Breadcrumb,
  Table,
  Modal,
  Tree,
  notification,
  TreeSelect,
  message,
  Alert,
  Row,
  Col,
  List,
  Spin,
  DatePicker
} from 'antd';
import lodash from 'lodash';
import { gup } from '../../../utils/utils';
import AddDepartment from './AddDepartment';
import EditDepartment from './EditDepartment';
import AppDrawer from './AppDrawer';
import fImg from '../../../assets/images/frown.png';
import DepartSelect from '../../../components/user/DepartSelect';
const { TextArea } = Input;
// import GetPlanBook from './getPlanBook';
import './less/depart.less';
import {
  systemComDepartGetDepartTree,  //获取公司的组织架构数（含数据权限）新
  systemComDepartGetOrgPersonList,  //获取组织机构右边的人员列表（新）
  systemComDepartGetWebPerListByKeyword,  /**web通过姓名/手机号码/身份证搜索人员信息*/
  saveDepartAppAuthInfo, /**保存部门app通讯录权限设置信息*/

  systemComDepartPageTreeType,//部门人员分页功能（包含部门、人员）
  systemComDepartSave, //部门新增-添加子部
  systemComDepartDelete, //删除部门功能
  systemComDepartUpdateLeaveDate, //部门批量离职----误报错误有使用-----
  systemComDepartGetTreeDepart, //选择部门
  getTreeperBydepart, //选择人员
  systemComDepartAdjustDepart, //调整部门人员
  getOnlineInsBlbLink,
  enterpriseInsComInsGetOnlineInsBlbPreservationLink, //生成保全
  enterpriseInsComInsSaveBookScheme, //保存方案书
  // enterpriseInsComInsPromptInitEnterpriseIns, //是否需要保险提示
  enterpriseInsComInsGetOnlineInsPerList, //获取投保人员信息
} from '../../../services/api';

const { confirm } = Modal;
const { Search } = Input;
const { TreeNode, DirectoryTree } = Tree;

@connect(
  state => ({
    profile: state.profile,
    global: state.global
  })
)
@Form.create()

/**
 * 部门管理组件
 */
export default class DepartmentManagement extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      departTreeData: [],   //组织架构数据  接口获取
      treeData: [], // 不含disable
      rightListShow: false,  //组织架构右边是否展示，不展示显示遮罩层
      requestData: {
        departId: '',
        perID: ''
      },   //请求表格数据的参数（部门id和人员id）


      departName: '',  // 右边列表页的title展示
      loadMore: false,  //搜索人员列表没有更多了
      drawerShow: false, // 搜索人员列表的展示的显示隐藏
      perDrawerLoading: false, //搜索人员列表加载显示
      hasMore: true,  //搜索人员列表是否可以据悉加载
      perList: [], // 搜索人员列表数据
      searchData: {
        keyword: '',
        pageNumber: '1',
        pageSize: '10'
      },
      searchListTotal: 0,  //搜索列表的总数
      breadCrumbArr: [], // 面包屑

      perIds: '',
      dataSource: [],
      perTotal: 0,
      // modelInit: gup('model'),
      otherbook: gup('otherbook'),
      selectedRows: [], //选中的行
      selectedRowsLength: '',
      selectedRowKeys: [], //选中的行key
      AddDepartmentVisible: false,
      EditDepartmentVisible: false,
      selectDepartmentVisible: false,
      appDrawerVisible: false, //设置app通讯录
      getOnlineInsBlbVisible: false, // 保全model
      onlineInsBlbUrl: '', //获取相应保全的路径
      TipsVisible: false, //展开的离职提示
      TipsOKVisible: false, //确认离职提示
      batchQuitData: [], //批量离职成功数据
      searchValue: '',
      pos: '',
      dataList: [],
      expandedKeys: ["-1"],
      autoExpandParent: true,
      selectedKeys: ["-1"],
      newDepartId: '-1',
      // treeData: [
      //   //树
      //   { title: '', key: '', personCount: '' }
      // ],
      treeDataSearch: [{ title: '', key: '' }],
      /**
       * 抽屉需要
       */
      // placeholder: '请输入关键字',
      title: '', //当前标题
      departId: '-1', //部门id
      chidrens: [],
      tableData: [],
      //组织架构的分页
      pagenav: {
        current: 1,
        pageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: total => `总共 ${total} 条`,
        onShowSizeChange: (current, pageSize) => {
          const pagenav = Object.assign({}, this.state.pagenav);
          pagenav.current = current;
          pagenav.pageSize = pageSize;
          this.setState({ pagenav }, () => {
            this.__getOrgPersonList(this.state.requestData);
          });
        },
        onChange: (page, pageSize) => {
          const pagenav = Object.assign({}, this.state.pagenav);
          pagenav.current = page;
          pagenav.pageSize = pageSize;
          this.setState({ pagenav }, () => {
            this.__getOrgPersonList(this.state.requestData);
          });
        },
        total: 0
      },
      //第一个离职提示的分页
      tipPegenav: {
        current: 1,
        pageSize: 5,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: total => `总共 ${total} 条`,
        onShowSizeChange: (current, pageSize) => {
          const tipPegenav = Object.assign({}, this.state.tipPegenav);
          tipPegenav.current = current;
          tipPegenav.pageSize = pageSize;
          this.setState({ tipPegenav });
        },
        onChange: (page, pageSize) => {
          const tipPegenav = Object.assign({}, this.state.tipPegenav);
          tipPegenav.current = page;
          tipPegenav.pageSize = pageSize;
          this.setState({ tipPegenav });
        },
        total: 0
      },
      //有离职失败时候的提示的分页
      tipPegenav2: {
        current: 1,
        pageSize: 5,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: total => `总共 ${total} 条`,
        onShowSizeChange: (current, pageSize) => {
          const tipPegenav2 = Object.assign({}, this.state.tipPegenav2);
          tipPegenav2.current = current;
          tipPegenav2.pageSize = pageSize;
          this.setState({ tipPegenav2 });
        },
        onChange: (page, pageSize) => {
          const tipPegenav2 = Object.assign({}, this.state.tipPegenav2);
          tipPegenav2.current = page;
          tipPegenav2.pageSize = pageSize;
          this.setState({ tipPegenav2 });
        },
        total: 0
      },
      reducepeoplevisible: false,
      visible: false,
      insurancetipsvisible: false, //提示模板
      onlineUrl: '', //购买在线保险的url
      accessbookvisible: false, //获取方案书
      // isIns: '',
      // comName:"",//企业名称
      onlineInsPerDataSource: [],
      selectedRowKeysforOrder: '',
      reasonVisible: false, //离职原因弹窗
      outReason: '',  // 离职原因
      outReasonDate: '',  //选择的离职时间


      requestDate: moment()  //请求接口的时间用于控制离职时间
    };
  }
  componentDidMount() {
    // 获取到组织架构列表
    this.__getDepartTree(data => {
      const { departId } = this.props.profile;
      // 判断数据里是否存在对应的部门id (防止切换账号后找不到对应的部门id)
      let item = null;
      function valueInData(data) {
        for(let i = 0; i < data.length; i++) {
          if(data[i].departId == departId) {
            item = data[i];
            break;
          }else {
            if(data[i].childDepart) {
              valueInData(data[i].childDepart);
            }
          }
        }
      }
      // 初始化菜单栏
      const initMenu = item => {
        if(item) {
          if (item.isExistsDataAuth == 0) {
            // 显示阴影
            this.setState({
              rightListShow: true
            });
          } else {
            this.setState({
              rightListShow: false,
              departName: item.departName,
              selectedKeys: [item.departId],
              expandedKeys: [item.parentDepartId?item.parentDepartId: '-1'],
              requestData: {
                departId: item.departId,
                perID: ''
              }
            }, () => {
              this.__getOrgPersonList(this.state.requestData);
            });
          }
        }
      }
      valueInData(data);
      item = item || data[0];
      initMenu(item);
    });
  }
  /**递归部门数据
   * @param {部门数据} treeData 
   * @param {是否添加disable属性} 、通过treeData的isExistsDataAuth判断权限
   */
  recursionTreeData(treeData, hasDisable) {
    treeData = JSON.parse(JSON.stringify(treeData));
    // TreeSelect组件所需值： title， value, key, children disabled
    return treeData.map(item => {
      item.title = item.departName;
      item.key = item.departId;
      item.value = item.departId;

      if (hasDisable) {
        // "isExistsDataAuth": "1",  //权限 1有权限 0：没权限
        item.disabled = item.isExistsDataAuth == 0;
      } else {
        // 没有权限的部门名称后面新增人数
        item.title = `${item.departName}(${item.personCount})`;
      }
      // 不展示下级部门
      // if(idArr.some(id => id == item.departId)) return item;
      if (item.childDepart) {
        item.children = this.recursionTreeData(item.childDepart, hasDisable);
      }
      return item;
    });
  }
  /**不展示下级部门
   * @param {treeData} 部门数据 
   * @param {idArr} 不展示下级部门的id数组
   * @param {disabled} disabled
   * @param {isNext} 是否属于下级，如果是，直接disable
   */
  disableNext(treeData, idArr, disabled = false, isNext) {
    treeData = JSON.parse(JSON.stringify(treeData));
    return treeData.map(item => {
      if (disabled) {
        item.disabled = disabled;
      }
      if (item.children) {
        if (isNext) {
          item.children = this.disableNext(item.children, idArr, true, true);
        } else {
          if (idArr.some(id => id == item.departId)) {
            item.children = this.disableNext(item.children, idArr, true, true);
          }
          else {
            item.children = this.disableNext(item.children, idArr, false);
          }
        }
      }
      return item;
    });
  }
  __getDepartTree(cb) {
    // 获取到组织架构列表
    systemComDepartGetDepartTree().then(res => {
      // 初始化页面判断右边列表的展示
      if (res.data[0] && res.data[0].isExistsDataAuth == 0) {
        this.setState({
          rightListShow: true
        });
      }
      this.setState({
        departTreeData: this.recursionTreeData(res.data, true), //含有disable属性
        editTreeData: this.recursionTreeData(res.data, true),
        treeData: this.recursionTreeData(res.data)
      }, () => {
        cb && cb(res.data);
      });
    });
  }

  /**
   *LYQ 2019-07-17
   *获取列表数据 部门id和人员id只传一个
   * @param {
   *  departId,
   *  perId
   * } data
   * @memberof DepartmentManagement
   */
  __getOrgPersonList(data) {
    const POST_DATA = {
      pageSize: this.state.pagenav.pageSize,
      pageNumber: this.state.pagenav.current,
      ...data
    };
    systemComDepartGetOrgPersonList(POST_DATA).then(response => {
      const { pageNumber, pageSize } = response.data;
      const tableData = response.data.data.map((val, i) => {
        val.key = i;
        val.number = (pageNumber - 1) * pageSize + i + 1;
        return val;
      });
      const pagenav = Object.assign({}, this.state.pagenav);
      pagenav.total = response.data.total;
      this.setState({
        tableData,
        selectedRows: [],
        selectedRowKeys: [],
        pagenav,
        requestDate: response.date
      });
    });
  }

  // 搜索人员数据
  __getSearchPerList(cb) {
    const { keyword } = this.state.searchData;
    if (keyword.trim() == '') return;
    systemComDepartGetWebPerListByKeyword(this.state.searchData).then(res => {
      let loadMore = false;
      // 搜索列表的“没有更多了”的显示判断
      if (this.state.searchData.pageNumber >= res.data.totalPage) {
        if (res.data.data.length == 0) {
          loadMore = false;
        } else {
          loadMore = true;
        }
      } else {
        loadMore = false;
      }
      this.setState({
        loadMore,
        perList: [...this.state.perList, ...res.data.data],
        searchListTotal: res.data.total //搜索结果总数
      }, () => {
        cb && cb();
      });
    });
  }
  renderRightContainer() {
    return (
      <div className="department-demonstrate">
        <div className="demonstrate-head">
          <p className="title">
            <span>{this.state.departName ? this.state.departName : ''}</span>
            {this.state.requestData.departId === '-1' ||
              this.state.requestData.departId === undefined ? (
                ''
              ) : (
                <Button
                  // size="small"
                  onClick={() => {
                    this.setState({ EditDepartmentVisible: true });
                  }}
                >
                  编辑
            </Button>
              )}
            <Button
              onClick={() =>
                this.setState({ AddDepartmentVisible: true })
              }
            >
              <span>添加子部门</span>
            </Button>
            {
              this.state.requestData.departId != '-1' &&
              <Button
                onClick={() =>
                  // 更新appDrawer的departId并且展示
                  this.setState({
                    appDrawerVisible: true,
                    appDepartId: this.state.requestData.departId
                  })
                }
              >
                App通讯录设置
              </Button>
            }
          </p>
          {
            this.state.drawerShow && <span>{this.state.departName}</span>
          }
          {
            !this.state.drawerShow &&
            <Breadcrumb>{this.renderBread()}</Breadcrumb>
          }
        </div>
        <div className="demonstrate-line" />
        <div className="subordinate-departments">
          <div className="sub-title division-title">
            <i className="division" />
            <span>部门人员</span>
          </div>
          <div className="division-button">
            <Button
              onClick={() => {
                this.props.history.push(
                  '/PersonnelRecruitment/departmentmanagement/addMember'
                );
              }}
              type="primary"
              icon="plus"
            >
              添加成员
          </Button>
            <Button
              type="danger"
              ghost
              onClick={() => {
                if (this.state.selectedRows.length === 0) {
                  notification['error']({
                    message: '请选择人员'
                  });
                  return;
                }
                // this.withdrawnShowConfirm();
                this.setState({ reasonVisible: true });
              }}
            >
              批量离职
          </Button>
            <Button
              onClick={() => {
                if (this.state.selectedRows.length === 0) {
                  notification['error']({
                    message: '请选择人员'
                  });
                  return;
                }

                this.setState({ selectDepartmentVisible: true });
              }}
            >
              调整部门
          </Button>
            <Button
              onClick={() => {
                this.props.history.push(
                  '/PersonnelRecruitment/departmentmanagement/importexportNav'
                );
              }}
            >
              批量导入
          </Button>
            {/* <Button
              onClick={() => {
                this.props.history.push(
                  '/PersonnelRecruitment/departmentmanagement/resignationlist'
                );
              }}
              className="button-right"
            >
              离职记录
          </Button> */}
          </div>
          <div className="division-table">{this.renderDepartMan()}</div>
        </div>
      </div>
    );
  }
  handlereducepeopleOk = () => {
    this.setState({
      reducepeoplevisible: false,
      // 订单大于1，选择订单
      visible: true
    });
  };
  handlereducepeopleCancel = () => {
    this.setState({
      reducepeoplevisible: false
    });
  };
  // 选择订单
  showModal = () => {
    this.setState({
      visible: true
    });
  };
  handleOk = () => {
    this.setState({
      visible: false
    });
  };
  handleCancel = () => {
    this.setState({
      visible: false
    });
  };
  // 温馨提示
  showsurancetipsModal = () => {
    this.setState({
      insurancetipsvisible: true
    });
  };
  handlesuranceOk = e => {
    this.setState({
      insurancetipsvisible: false,
      accessbookvisible: true
    });
  };
  handleonline = e => {
    this.setState({
      insurancetipsvisible: false
    });
    window.open(this.state.onlineUrl);
  };
  handlesurancetipxCancel = e => {
    this.setState({
      insurancetipsvisible: false
      // insurancetipvisible:true,
    });
  };
  handlesurancetipCancel = e => {
    this.setState({
      // insurancetipvisible: false,
      insurancetipsvisible: false
    });
    this.props.history.push(
      // 跳转到1-4-4
      '/enterprise/company'
    );
  };
  // 获取方案书
  showaccessbookModal = () => {
    this.setState({
      accessbookvisible: true
    });
  };
  handlenextpeopleOk = e => {
    //获取方案书表单提交
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const obj = {
          contactper: values.contactper ? values.contactper : '',
          contactPhone: values.contactPhone ? values.contactPhone : '',
          comPerNum: values.comPerNum ? values.comPerNum : '',
          guaranteeAmountLow: values.guaranteeAmountLow
            ? values.guaranteeAmountLow
            : '',
          insAmountUp: values.insAmountUp ? values.insAmountUp : '',
          proCode: ''
        };
        enterpriseInsComInsSaveBookScheme(obj).then(
          res => {
            console.log('成功信息-方案书values', res);
            // message.success("保存成功！");
          },
          error => {
            message.error(error);
            console.log('错误信息-方案书values', error);
          }
        );
        this.props.re;
        this.setState({
          accessbookvisible: false
        });
      }
    });
  };
  handlereducepeopleCancel = e => {
    this.setState({
      accessbookvisible: false,
      insurancetipsvisible: false,
      reducepeoplevisible: false
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('表单提交中.........', values);
      }
    });
  };

  handleproductCancel = e => {
    this.setState({
      accessbookvisible: true
    });
  };
  showsurancetipModal = () => {
    this.setState({
      // insurancetipvisible: true,
    });
  };
  //在线购买保险的链接生成
  messageOnline = () => {
    getOnlineInsBlbLink({
      comId: this.props.global.companyInfo.comId
    }).then(data => {
      this.setState({
        onlineUrl: data.data
      });
    });
  };

  // 初始化温馨提示
  // getPrimotInt = () => {
  //   enterpriseInsComInsPromptInitEnterpriseIns({}).then(data => {
  //     console.log('是否初始化', data);
  //     this.setState({
  //       isIns: data.data.isIns
  //     });
  //     if (this.state.modelInit === 'init') {
  //       this.setState({
  //         insurancetipsvisible: true
  //       });
  //     }
  //   }, (err) => {
  //     console.log(err);
  //   });
  // };
  // 选择其他产品
  getotherbook = () => {
    if (this.state.otherbook === 'init') {
      this.setState({
        accessbookvisible: true
      });
    }
  };
  checkPhone = (rule, value, callback) => {
    if (value && !/^1[0-9]{10}$/.test(value)) {
      callback('请输入正确的手机号码！');
    } else {
      callback();
    }
  };
  checkpeoplenum = (rule, value, callback) => {
    if (value && !/^[0-9]*$/.test(value)) {
      callback('请输入数字！');
    } else {
      callback();
    }
  };
  // 温馨提示马上查看
  rightCheckClick = () => {
    this.props.history.push(`/insurancemanagement/enterpriseinsurance`);
  };
  //保存方案书
  // saveBookSchema = () => {
  //   enterpriseInsComInsSaveBookScheme({}).then(data => {
  //     // this.setState({
  //     //   onlineUrl: data.data
  //     // });
  //     setTimeout(() => {
  //       console.log("保存方案书",data);
  //     },500);
  //   });
  // };

  //保险选择
  renderTable = () => {
    const rowSelection = {
      type: 'radio',
      // selectedRowKeys: this.state.selectedRowKeys,
      // onChange: selectedRowKeys => {
      //   this.setState({ selectedRowKeys });
      // },
      selectedRowKeys: this.state.selectedRowKeysforOrder,
      onChange: (selectedRowKeys, selectedRows) => {
        // this.setState({ selectedRowKeysforOrder:selectedRowKeys });
        this.setState({ selectedRowKeysforOrder: selectedRows[0].blbOrderId });
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User' // Column configuration not to be checked
      })
    };
    const columns = [
      {
        title: '订单号',
        dataIndex: 'blbOrderId',
        key: 'blbOrderId'
      },
      {
        title: '保险产品',
        dataIndex: 'productName',
        key: 'productName'
      },
      {
        title: '投保总人数',
        dataIndex: 'perNum',
        key: 'perNum'
      },
      {
        title: '需保全人数',
        dataIndex: 'insPerCount',
        key: 'insPerCount'
      },
      {
        title: '购买时间',
        dataIndex: 'buyTime',
        key: 'buyTime'
      }
    ];

    return (
      <Table
        size="middle"
        width={800}
        rowSelection={rowSelection}
        columns={columns}
        pagination={false}
        rowKey={record => record.blbOrderId}
        // dataSource={this.state.dataSource}
        dataSource={this.state.onlineInsPerDataSource}
      />
    );
  };

  //保全链接生成
  enterpriseInsComInsGetOnlineInsBlbPreservationLink() {
    enterpriseInsComInsGetOnlineInsBlbPreservationLink({
      // orderId: this.state.selectedRowKeys,
      orderId: this.state.selectedRowKeysforOrder,
      perIds: this.state.perIds,
      reviseType: '2'
    })
      .then(res => {
        console.log(res, '保全链接生成-res');
        this.setState({
          visible: false,
          onlineInsBlbUrl: res.data
        });
        // window.open(res.data);
        // this.newwin.location.href = res.data;
      })
      .catch(err => console.log(err, '保全链接生成-err'));
  }

  /* 搜索----------------start */

  onChange = e => {
    const { value } = e.target;
    let { treeData } = this.state;
    const { treeDataSearch } = this.state;
    if (value.trim().length > 0) {
      //输入搜索的数据不是空
      treeData = treeDataSearch;
    }
    let expandedKeys = this.state.dataList
      .map(item => {
        if (item.title.indexOf(value) > -1) {
          return this.getParentKey(item.key, treeData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    if (value.trim().length === 0) {
      expandedKeys = [treeData[0].key];
    }
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true
    });
  };

  getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (this.getParentKey(key, node.children)) {
          parentKey = this.getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  generateList = data => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key, title } = node;
      this.state.dataList.push({ key, title }); //把部门名称跟人员名称合集
      if (node.children) {
        this.generateList(node.children, node.key);
      }
    }
  };


  //部门人员分页功能---（接口新增一个treeType）
  systemComDepartPageTreeType = (departId, treeType) => {
    systemComDepartPageTreeType({
      // pageSize: 5000,
      // pageNumber: 1,
      pageSize: this.state.pagenav.pageSize,
      pageNumber: this.state.pagenav.current,
      departId: departId || this.state.departId,
      treeType
    }).then(
      response => {
        const tableData = response.data.data.map((val, i) => {
          val.key = i;
          return val;
        });
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.total = response.data.total;
        this.setState({
          tableData,
          selectedRows: [],
          selectedRowKeys: [],
          pagenav
        });
      },
      err => {
        console.log(err, 'systemComDepartPage-err-部门人员分页功能s');
      }
    );
  };

  //部门新增-添加子部门
  systemComDepartSave = () => {
    systemComDepartSave({
      departName: '',
      perID: '',
      parentDepartId: ''
    }).then(
      () => {
        this.setState({ tableData: this.state.data });
      },
      err => {
        console.log(err, 'systemComDepartSave-err-部门更新--编辑保存');
      }
    );
  };

  //删除树结点
  splicTreeNode = () => {
    const { treeData } = this.state;
    const posArr = this.state.pos.split('-').slice(1);
    if (posArr.length === 2) {
      treeData[posArr[0]].children.splice(posArr[1], 1);
    }
    if (posArr.length === 3) {
      treeData[posArr[0]].children[posArr[1]].children.splice(posArr[2], 1);
    }
    if (posArr.length === 4) {
      treeData[posArr[0]].children[posArr[1]].children[
        posArr[2]
      ].children.splice(posArr[3], 1);
    }
    this.setState({
      treeData,
      title: treeData[0].title,
      pos: '0-0'
    });
  };

  //获取你节点
  getParentNode = () => {
    const { treeData } = this.state;
    const posArr = this.state.pos.split('-').slice(1);
    let parentNode = treeData[0];
    if (posArr.length === 3) {
      parentNode = treeData[posArr[0]].children[posArr[1]];
    }
    if (posArr.length === 4) {
      parentNode = treeData[posArr[0]].children[posArr[1]].children[posArr[2]];
    }
    return parentNode;
  };

  // 删除部门功能
  systemComDepartDelete = () => {
    systemComDepartDelete({ departId: this.state.requestData.departId }).then(
      response => {
        notification['success']({
          message: '删除部门成功'
        });
        this.setState({ EditDepartmentVisible: false, departId: '-1' });
        this.__getDepartTree(data => {
          // 初始化后判断右边列表的权限
          if (data[0]) {
            if (data[0].isExistsDataAuth == 0) {
              // 显示阴影
              this.setState({
                rightListShow: true
              });
            } else {
              this.setState({
                pos: '', //更新pos重置面包屑
                rightListShow: false,
                departName: data[0].departName,
                requestData: {
                  departId: data[0].departId,
                  perID: ''
                }
              }, () => {
                this.__getOrgPersonList(this.state.requestData);
              });
            }
          }
        });
        // this.splicTreeNode();
      },
      err => {
        console.log(err, 'systemComDepartDelete-err- 删除部门功能');
      }
    );
  };
  //生成当前树的位置
  generateTreeDataPosition = (treeData, pos) => {
    return treeData.map((val, i) => {
      const newObj = val;
      if (newObj.children && newObj.children.length > 0) {
        newObj.children = this.generateTreeDataPosition(
          newObj.children,
          `${pos}-${i}`
        );
      }
      newObj.pos = `${pos}-${i}`;
      return newObj;
    });
  };

  //过滤掉treeType='2'（人员）的对象
  filterTreeType = treeData => {
    return treeData.filter(val => {
      if (val.children && val.children.length > 0) {
        val.children = this.filterTreeType(val.children);
      }
      return val.treeType !== '2';
    });
  };

  //选择部门
  getTreeDepart = () => {
    systemComDepartGetTreeDepart({}).then(
      response => {
        let { data } = response;
        data = JSON.parse(
          JSON.stringify(data).replace(/\"children\":\[\]/g, '"isLeaf":true')
        );
        data = this.generateTreeDataPosition(data, '0');

        if (data.length > 0) {
          this.setState({
            treeData: data,
            chidrens: data[0].children,
            // title: `${data[0].title}(${data[0]['personCount']})`,//标题去掉统计数值
            title: `${data[0].title}`,
            departId: data[0].key,
            expandedKeys: [data[0].key],
            selectedKeys: [data[0].key]
          });
        }
      },
      err => {
        console.log(err, 'getTreeDepart-选择部门-err');
      }
    );
  };

  generaUserData = (data, keyvalue) => {
    return data.map(val => {
      if (val.clildren && val.clildren.length > 0) {
        val.clildren.filter(val1 => {
          if (val1.title.indexOf(keyvalue) !== -1) {
            return true;
          } else {
            return false;
          }
        });
        return val;
      }
      return val;
    });
  };

  //选择人员
  getTreeperBydepart = () => {
    getTreeperBydepart({}).then(
      response => {
        const data = JSON.parse(
          JSON.stringify(response.data).replace(
            /\"children\":\"\"/g,
            '"isLeaf":true'
          )
        );
        // 获取总人数
        function getPerTotal(array) {
          let total = 0;
          function recursion(array) {
            array.forEach(item => {
              // treeType为2的时候是人员
              if (item.treeType == '2') {
                total++;
              }
              if (item.children) {
                recursion(item.children);
              }
            });
          }
          recursion(array);
          return total;
        }
        this.setState({
          perTotal: getPerTotal(data)
        });
        const allData = this.generateTreeDataPosition(data, '0'); //这个数据里面包含人员跟部门
        this.generateList(allData);
        this.setState({
          treeDataSearch: allData
        });
        const publicData = JSON.parse(JSON.stringify(allData));
        const dataOnlyDepart = JSON.parse(
          //拆分出来只有部门的数据
          JSON.stringify(
            this.generateTreeDataPosition(this.filterTreeType(publicData), '0')
          ).replace(/\"children\":\[\]/g, '"isLeaf":true')
        );
        if (dataOnlyDepart.length > 0) {
          this.setState({
            treeData: dataOnlyDepart,
            chidrens: dataOnlyDepart[0].children,
            // title: `${data[0].title}(${data[0]['personCount']})`,//标题去掉统计数值
            title: `${dataOnlyDepart[0].title}`,
            // departId: dataOnlyDepart[0].key,
            // expandedKeys: [dataOnlyDepart[0].key],
            // selectedKeys: [dataOnlyDepart[0].key]
          });
        }
      },
      err => {
        console.log(err, 'getTreeperBydepart-选择人员-err');
      }
    );
  };
  //部门批量操作功能
  // systemComDepartBatchInsertDepart = () => {
  //   systemComDepartBatchInsertDepart({}).then(
  //     response => {
  //       console.log(
  //         response,
  //         'systemComDepartBatchInsertDepart-部门批量操作功能-response'
  //       );
  //     },
  //     err => {
  //       console.log(
  //         err,
  //         'systemComDepartBatchInsertDepart-部门批量操作功能-err'
  //       );
  //     }
  //   );
  // };
  //调整部门人员
  systemComDepartAdjustDepart = () => {
    const perIds = [];
    let oldDepartId = '';
    const { selectedRows, newDepartId } = this.state;
    selectedRows.forEach(item => {
      perIds.push(item.perId);
      oldDepartId = item.departId || '';
    });

    systemComDepartAdjustDepart({
      perIds: JSON.stringify(perIds),
      oldDepartId,
      newDepartId
    }).then(
      response => {
        console.log(
          response,
          'systemComDepartAdjustDepart-调整部门人员-response'
        );
        this.__getDepartTree();
        this.__getOrgPersonList(this.state.requestData);
      },
      err => {
        console.log(err, 'systemComDepartAdjustDepart-调整部门人员-err');
      }
    );
  };

  //部门批量离职
  systemComDepartUpdateLeaveDate = () => {
    const leaveDate = this.state.outReasonDate;
    if (leaveDate == "") return notification.error({
      message: '请选择日期'
    });
    const perIds = [];
    this.state.selectedRows.forEach(val => {
      perIds.push(val.perId);
    });
    this.setState({ perIds: perIds.join(',') });
    const leaveReason = this.state.outReason == '' ? '员工自动提交离职申请，现已解除劳动合同关系，系统离职处理' : this.state.outReason;
    systemComDepartUpdateLeaveDate({
      perIds: perIds.join(','),
      orgId: this.state.departId,
      leaveReason,
      leaveDate
    }).then(
      response => {
        // 2019-06-14 人员从组织架构离职时，减员弹窗去除（冠楠）
        // this.enterpriseInsComInsGetOnlineInsPerList(response.data);
        this.setState({
          batchQuitData: response.data,
          leaveReason: ''
        });
        //存在失败的数据
        if (response.data.failList.length > 0) {
          this.setState({
            TipsOKVisible: true
          });
          const tipPegenav2 = Object.assign({}, this.state.tipPegenav2);
          tipPegenav2.total = response.data;
        }
        //没有失败数据，且有成功数据  && （是服务公司或者自行招用保安单位）
        if (
          response.data.failCount === 0 && 
          response.data.successCount > 0 && (this.props.global.companyInfo.institutionType == '0102' ||
          this.props.global.companyInfo.institutionType == '0104')) {
          const sucCount = response.data.successCount;
          Modal.success({
            title: sucCount + '个员工全部离职成功！',
            content: '可在离职记录中查看离职成功的人员。',
            okText: '确定',
            onOk: () => {
              this.props.dispatch({
                type: 'insurance/showQuitModal',
                payload: {
                  title: '保险减员提示',
                  warningText: '*保险产品的新增、减员等操作可通过【人员投保管理】-【未投保】【已投保】选择相应人员进行保全增减操作！',
                  contentText: '存在在保的离职人员共count位,请及时对离职人员办理保险保全的减员操作，以降低保险成本！',
                  okCallBack: () => {
                    this.props.history.push('/insurancemanagement/insurance-management?tab=1');
                  }
                }
              });
            }
          });
        }
        this.setState({ selectedRows: [], selectedRowKeys: [] });
        // 重新渲染列表
        this.__getOrgPersonList(this.state.requestData);
        // this.getTreeperBydepart();
        // //删除记录存在失败的情况
        // if(response.data.fileCount > 0) {

        // }
      },
      err => {
        console.log(err, 'systemComDepartUpdateLeaveDate-部门批量离职-err');
      }
    );
  };

  //获取选择的人员是否有投保险
  enterpriseInsComInsGetOnlineInsPerList = batchQuitData => {
    const idCardNo = [];
    this.state.selectedRows.forEach(val => {
      idCardNo.push(val.idCardNo.toString());
    });
    enterpriseInsComInsGetOnlineInsPerList({
      idCardNoJson: JSON.stringify(idCardNo)
    }).then(
      response => {
        // 保险员减员提示
        //1、离职时，都有投保，但只有失败人员，没有成功人员，不显示减员弹框
        //2、离职成功并且有投保，才显示保险减员
        if (batchQuitData.failCount > 0 && batchQuitData.successCount === 0) {
          return;
        }
        if (batchQuitData.successCount > 0 && response.data.length > 0) {
          this.setState({
            reducepeoplevisible: true,
            onlineInsPerDataSource: response.data
          });
        }
      },
      err => {
        console.log(err);
      }
    );
  };

  // 递归展示树状组织架构
  renderTreeNodes = (data, parentkey, parentTitle) => {
    return data.map((item, index) => (
      <TreeNode
        departId={item.departId}
        isExistsDataAuth={item.isExistsDataAuth}
        key={`${parentkey}-${index}`}
        title={`${item.departName}(${item.personCount})`}
      >
        {
          (() => {
            if (item.childDepart.length > 0) {
              parentkey++;
              return this.renderTreeNodes(item.childDepart, parentkey);
            }
          })()
        }
      </TreeNode>)
    );
  };

  // 下级部门组别
  handleList = () => {
    if (this.state.chidrens !== '' && this.state.chidrens !== undefined) {
      return this.state.chidrens.map((val, i) => {
        if (val.treeType === '2') {
          return '';
        }
        return (
          <li
            onClick={() => {
              this.setState({
                chidrens:
                  val.children && val.children.length > 0 ? val.children : [],
                pos: val.pos,
                title: val.title,
                departId: val.key
              });
              this.systemComDepartPage(val.key);
            }}
            key={i}
          >
            <a>
              {val.title}({val.personCount ? val.personCount : 0})
              <Icon type="right" />
            </a>
          </li>
        );
      });
    }
  };

  //确定是否要删除部门
  showConfirm = () => {
    confirm({
      title: '提示',
      content: '是否确认删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        this.systemComDepartDelete();
      },
      onCancel() {
        console.log('Cancel');
      }
    });
  };
  //确定是否要离职
  withdrawnShowConfirm = () => {
    const mobiles = [];
    const name = [];
    const tipPegenav = Object.assign({}, this.state.tipPegenav);
    tipPegenav.total = this.state.selectedRows.length;
    this.state.selectedRows.forEach(val => {
      name.push(val.name);
      mobiles.push(val.mobilePhone);
    });
    this.setState({
      selectedRowsLength: this.state.selectedRows.length,
      reasonVisible: false
    });
    if (mobiles.length === 0) {
      notification['warning']({
        message: '请选择人员'
      });
      return;
    }
    this.setState({
      TipsVisible: true
    });
  };
  handleTipsOk = () => {
    this.systemComDepartUpdateLeaveDate();
    // this.enterpriseInsComInsGetOnlineInsPerList();
    this.setState({
      TipsVisible: false,
      reasonVisible: false
    });
    // // 保险员减员提示
    // //判断对应的人员有没有投保，没有投保就不显示保险减员
    // if (this.state.dataSource.length > 0 && this.state.batchQuitData.successCount !== 0) {
    //   this.setState({
    //     reducepeoplevisible: true,
    //   });
    // }
  };
  handleTipsCancel = () => {
    this.setState({
      TipsVisible: false,
      TipsOKVisible: false,
      reasonVisible: false
    });
  };
  //部门人员表格
  renderDepartMan = () => {
    // 表格选择设置
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRows, selectedRowKeys });
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User' // Column configuration not to be checked
      })
    };

    const columns = [
      {
        title: '序号',
        dataIndex: 'number',
        key: 'number',
        render: text => {
          text = parseInt(text, 10);
          return <span>{text}</span>;
        }
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        render: text => <div>{text}</div>
      },
      {
        title: '身份证',
        key: 'idCardNo',
        dataIndex: 'idCardNo',
        // render: text => text.replace(/(\d{4}).*(\d{3})/,'$1***********$2')
      },
      {
        title: '手机号',
        key: 'mobilePhone',
        dataIndex: 'mobilePhone',
        // render: text => text.replace(/(\d{3})\d{4}(\d{4})/,'$1****$2')
      },
      {
        title: '人员类别',
        key: 'perTypeName',
        dataIndex: 'perTypeName'
      },
      {
        title: '激活状态',
        key: 'isAppActive',
        render: (text, record) => (
          <div>
            <span
              className={
                record.isAppActive === '1' ? 'activated' : 'inactivated'
              }
            />
            <span className="status">
              {record.isAppActive === '1' ? '已激活' : '未激活'}
            </span>
          </div>
        )
      },
      {
        title: '认证状态',
        key: 'authStatus',
        render: (text, record) => (
          <div>
            <span
              className={record.authStatus === '1' ? 'activated' : 'inactivated'}
            />
            <span className="status">
              {(() => {
                let result = '';
                switch (record.authStatus) {
                  case '0':
                    result = '未认证';
                    break;
                  case '1':
                    result = '已认证';
                    break;
                  case '2':
                    result = '认证中';
                    break;
                  case '3':
                    result = '认证失败';
                    break;
                }
                return result;
              })()}
              {/* {record.authStatus === '1' ? '已认证' : '未认证'} */}
            </span>
          </div>
        )
      },
      {
        title: '操作',
        key: 'option',
        render: (text, record) => (
          <span
            style={{ color: '#108EE9', cursor: 'pointer' }}
            onClick={() => {
              this.props.history.push(
                `/PersonnelRecruitment/departmentmanagement/PersonnelInformationNav?perId=${record.perId}&authStatus=${record.authStatus}`
              );
            }}
          >
            修改
          </span>
        )
      }
    ];

    return (
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={this.state.tableData}
        pagination={this.state.pagenav}
      />
    );
  };

  //获取当前节点的子节点
  getPosChidrens = (target, data) => {
    return lodash.get(
      data,
      lodash.toPath(
        target
          .split('-')
          .slice(1)
          .map(p => `[${p}]`)
          .join('.children')
      )
    );
  };

  //保存编辑部门表单提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values, 'handleSubmit-values');
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  };

  getNodeDate = (treeData, index) => {
    const { pos } = this.state;
    let posArrs = pos.split('-');
    posArrs = posArrs.slice(1);
    for (let i = 0; i < index; i++) {
      if (i === 0) {
        return treeData[posArrs[i]];
      } else {
        return treeData[posArrs[i]];
      }
    }
  };
  getPosArray() {
    // 通过部门数据和当前所在位置获取面包屑
    const { departTreeData, pos } = this.state;
    const posArr = pos.split('-');
    posArr.shift();
    let parentArray = [];
    let posResult = [];
    // 通过pos获取到面包屑的数组
    posArr.forEach((key, index) => {
      if (index == 0) {
        if (departTreeData[key]) {
          // posResult.push(departTreeData[key].departName);
          posResult.push({
            departName: departTreeData[key].departName,
            departId: departTreeData[key].departId
          });
          parentArray = departTreeData[key].childDepart;
        }
      } else {
        if (parentArray[key]) {
          // posResult.push(parentArray[key].departName);
          posResult.push({
            departName: parentArray[key].departName,
            departId: parentArray[key].departId
          });
          parentArray = parentArray[key].childDepart;
        }
      }
    });
    if (posResult.length == 0 && this.state.departTreeData[0]) {
      // posResult.push(this.state.departName);
      posResult.push({
        departName: this.state.departTreeData[0].departName,
        departId: this.state.departTreeData[0].departId
      });
    }
    return posResult;
  }
  //面包屑
  renderBread = () => {
    // 通过部门数据和当前所在位置获取面包屑
    // const { departTreeData, pos } = this.state;
    // const posArr = pos.split('-');
    // posArr.shift();
    // let parentArray = [];
    // let posResult = [];
    // // 通过pos获取到面包屑的数组
    // posArr.forEach((key, index) => {
    //   if(index == 0) {
    //     if(departTreeData[key]) {
    //       posResult.push(departTreeData[key].departName);
    //       parentArray = departTreeData[key].childDepart;
    //     }
    //   }else {
    //     if(parentArray[key]) {
    //       posResult.push(parentArray[key].departName);
    //       parentArray = parentArray[key].childDepart;
    //     }
    //   }
    // });
    // if(posResult.length == 0) {
    //   posResult.push(this.state.departName);
    // }
    const posResult = this.getPosArray();
    return (
      posResult.map((item, index) => {
        return <Breadcrumb.Item key={index}>{item.departName}</Breadcrumb.Item>
      })
      // <Breadcrumb.Item
      //   onClick={() => {
      //   }}
      // >
      //   {i === posArrs.length - 1 ? nodeData.title : <a>{nodeData.title}</a>}
      // </Breadcrumb.Item>
    );
  };

  render() {
    const { treeDataSearch, departTreeData, searchValue } = this.state;
    if (searchValue.trim().length > 0) {
      departTreeData = treeDataSearch;
    }
    const TipsColumns = [
      {
        title: '姓名',
        dataIndex: 'name',
        render: text => <div>{text}</div>
      },
      {
        title: '手机号',
        dataIndex: 'mobilePhone'
      },
      {
        title: '所属组织',
        render: (text, record) => <span>{record.orgName ? record.orgName : this.state.departName}</span>
      }
    ];
    const TipsOkColumns = [
      {
        title: '姓名',
        dataIndex: 'name',
        render: text => <div>{text}</div>
      },
      {
        title: '手机号',
        dataIndex: 'mobilePhone'
      },
      {
        title: '所属组织',
        dataIndex: 'orgName'
      },
      {
        title: '校验提示',
        dataIndex: 'errorMsg',
        render: (text, record) => (
          <span style={{ color: '#e71010' }}>{text}</span>
        )
      }
    ];
    return (
      <div className="DepartmentManagement">
        {this.props.global.companyInfo.authStatus === '1' ? (
          <div className="department-content">
            <div className="department-inquiry">
              <Search
                // size="large"
                // placeholder={this.state.placeholder}
                placeholder="搜索姓名/手机号/身份证"
                style={{ width: 200, height: 40 }}
                onChange={e => {
                  const { value } = e.target;
                  this.setState({
                    drawerShow: value !== '',
                    perList: []
                  });
                  if (value == '') {
                    // 等于空的时候通过pos找到对应的departId
                    const currentDepartID = this.getPosArray()[0] ? this.getPosArray()[this.getPosArray().length - 1].departId : this.state.departTreeData[0].departId;
                    this.setState({
                      departName: this.getPosArray()[0] ? this.getPosArray()[this.getPosArray().length - 1].departName : this.state.departTreeData[0].departName,
                      requestData: {
                        perID: '',
                        departId: currentDepartID
                      }
                    }, () => {
                      this.__getOrgPersonList(this.state.requestData);
                    });
                  } else {
                    this.setState({
                      searchData: {
                        keyword: value,
                        pageNumber: '1',
                        pageSize: '10'
                      }
                    }, () => {
                      this.__getSearchPerList();
                    });
                  }
                }}
                maxLength={20}
              />
              {/* <div className="depart-button">
              <Button
              style={{width: 180}}
                onClick={() => {
                  this.props.history.push(
                    "/PersonnelRecruitment/departmentmanagement/resignationlist"
                  );
                }}
                className="button-right"
              >
                离职记录
              </Button>
            </div> */}
              {
                // 部门展示
                !this.state.drawerShow && this.state.treeData.length > 0 &&
                <div className="depart-menu">
                  {/* 查询下级部门功能 */}
                  <DirectoryTree
                    treeData={this.state.treeData}
                    expandedKeys={this.state.expandedKeys}
                    autoExpandParent={this.state.autoExpandParent}
                    selectedKeys={this.state.selectedKeys}
                    onExpand={expandedKeys => {
                      this.setState({ expandedKeys });
                    }}
                    onSelect={(selectedKeys, e) => {
                      this.setState({ selectedKeys });
                      // 获取到对应部门的departId, isExistsDataAuth
                      // "isExistsDataAuth": "1",  //权限 1请求接口 0：不请求 加载阴影
                      const { departId, isExistsDataAuth, pos, departName } = e.node.props;
                      this.props.dispatch({
                        type: 'profile/changeDepartId',
                        departId
                      });
                      // console.log(this.props.saveDepartId,'this.props.dispatchthis.props.dispatch');
                      // this.props.saveDepartId({departId});
                      setTimeout(() => {
                        console.log(this.props.profile);
                      }, 1000);
                      this.setState({
                        editTreeData: this.disableNext(this.state.departTreeData, [departId])
                      });
                      if (isExistsDataAuth == 0) {
                        // 显示阴影
                        this.setState({
                          rightListShow: true
                        });
                      } else {//发起请求，更新列表
                        this.setState({
                          departName: departName,
                          pos,
                          rightListShow: false,
                          requestData: {
                            departId,
                            perID: ''
                          }
                        }, () => {
                          this.__getOrgPersonList(this.state.requestData);
                        });
                      }
                    }}
                  >
                    {/* {this.renderTreeNodes(departTreeData, 0)} */}
                  </DirectoryTree>
                </div>
              }


              {/* 人员列表 */}
              {
                this.state.drawerShow &&
                <div className={this.state.drawerShow ? 'depart_drawer_container' : 'depart_drawer_container depart_drawer_hide'}>
                  {/* <Alert message="只能检索权限范围内的人员信息。" type="warning" showIcon /> */}
                  <p style={{ color: '#ff9900' }}>注：只能检索权限范围内的人员信息。</p>
                  {
                    this.state.perList.length == 0 && <p>搜索无记录</p>
                  }
                  <InfiniteScroll
                    initialLoad={false}
                    pageStart={0}
                    loadMore={() => {
                      let { perList } = this.state;
                      this.setState({
                        perDrawerLoading: true
                      });
                      if (perList.length > this.state.searchListTotal) {
                        this.setState({
                          loadMore: true,
                          perDrawerLoading: false,
                          hasMore: false
                        });
                        return;
                      }
                      let { pageNumber } = this.state.searchData;
                      pageNumber++;
                      this.setState({
                        searchData: {
                          ...this.state.searchData,
                          pageNumber
                        }
                      });
                      this.__getSearchPerList(() => {
                        this.setState({
                          perDrawerLoading: false
                        });
                      });
                    }}
                    hasMore={!this.state.perDrawerLoading && this.state.hasMore}
                    useWindow={false}
                  >
                    <List
                      dataSource={this.state.perList}
                      renderItem={item => (
                        <List.Item
                          key={item.perId}
                          className="departmet_list"
                          style={{ cursor: 'pointer' }}
                          onClick={() => {
                            console.log(item.departName);
                            // 更新右边表格
                            const departId = item.departId;
                            const perID = item.perId;
                            this.setState({
                              rightListShow: false,
                              departId,
                              departName: item.departName ? item.departName : this.state.departTreeData[0].departName,
                              requestData: {
                                departId,
                                perID
                              },
                              pagenav: {
                                pageSize: '10',
                                current: 1
                              }
                            }, () => {
                              this.__getOrgPersonList(this.state.requestData);
                            });
                            // this.setState({
                            //   drawerShow: false
                            // });
                          }}
                        >
                          <List.Item.Meta
                            title={item.name}
                            description={(() => {
                              return (
                                <div style={{ fontSize: 13 }}>
                                  <span style={{ display: 'block' }} >{item.departName ? item.departName : this.state.departTreeData[0].departName}</span>
                                  <span style={{ display: 'block' }}>{item.idCardNo}</span>
                                  <span style={{ display: 'block' }}>{item.mobilePhone}</span>
                                </div>
                              );
                            })()}
                          />
                          {/* <div>{item.departName}</div> */}
                        </List.Item>
                      )}
                    >
                      {this.state.loading && (
                        <div className="demo-loading-container">
                          <Spin />
                        </div>
                      )}
                      {this.state.loadMore && (
                        <div
                          style={{
                            width: '100%',
                            textAlign: 'center'
                          }}
                        >
                          没有更多了
                    </div>
                      )}
                    </List>
                  </InfiniteScroll>
                </div>
              }
            </div>
            {
              // 右边显示部分
              (() => {
                // 是否限制阴影
                if (!this.state.rightListShow) {
                  return this.renderRightContainer();
                } else {
                  return (
                    <div className="department-demonstrate">
                      <div
                        style={{
                          width: '100%',
                          height: 600,
                          textAlign: 'center',
                          fontSize: 30,
                          display: 'table',
                          color: '#cdcdcd'
                        }}
                      >
                        <div style={{ display: 'table-cell', verticalAlign: 'middle' }}>
                          <img src={fImg} alt="" />
                          <p>您没有该部门的管理权限</p>
                        </div>
                      </div>
                    </div>
                  );
                }
              })()
            }
          </div>
        ) : (
            <div style={{ padding: 16 }}>
              <Alert
                message="您的信息尚未通过审核，暂未开通此功能，若有疑问请联系400-662-9696。"
                type="error"
              />
            </div>
          )}
          {
            this.state.selectDepartmentVisible && <Modal
              title="选择部门"
              visible={this.state.selectDepartmentVisible}
              onOk={() => {
                if (this.state.newDepartId === '') {
                  notification['error']({
                    message: '请选择新的部门'
                  });
                  return;
                }
                this.setState({ selectDepartmentVisible: false });
                this.systemComDepartAdjustDepart();
              }}
              onCancel={() => {
                this.setState({ selectDepartmentVisible: false });
              }}
            >
              <DepartSelect
                style={{ width: 300 }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择部门"
                treeDefaultExpandAll
                allowClear
                showSearch={true}
                showCheckedStrategy={'TreeSelect.SHOW_ALL'}
                onChange={value => {
                  this.setState({ newDepartId: value.indexOf('-1') == 0 ? '-1' : value.split('-')[0] });
                }}
              />
              {/* <TreeSelect
                // value={this.state.newDepartId}
                style={{ width: 300 }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={this.state.departTreeData}
                placeholder="请选择部门"
                treeDefaultExpandAll
                onChange={newDepartId => {
                  console.log(newDepartId, 'TreeSelect-newDepartId');
                  this.setState({ newDepartId });
                }}
              /> */}
            </Modal>
          }
        

        {/* 弹出添加子部门-抽屉 */}
        <AddDepartment
          treeData={this.state.departTreeData}
          // treeData={this.disableNext(this.state.departTreeData,[this.state.requestData.departId])}
          // departId={this.state.departId}
          open={this.state.AddDepartmentVisible}
          addSuccess={() => {
            this.__getDepartTree();
            this.__getOrgPersonList(this.state.requestData);
          }}
          ok={open => {
            this.setState({ AddDepartmentVisible: open });
          }}
        />
        {/* 弹出编辑部门-抽屉 */}
        <EditDepartment
          treeData={this.state.editTreeData}
          // treeData={this.disableNext(this.state.departTreeData, [this.state.requestData.departId])}
          departId={this.state.requestData.departId}
          open={this.state.EditDepartmentVisible}
          delete={this.showConfirm}
          editSuccess={departName => {
            // 更新组织架构和列表
            this.__getDepartTree(() => {
              // 更新title
              this.setState({
                departName
              });
              this.__getOrgPersonList(this.state.requestData);
            });
          }}
          ok={open => {
            this.setState({ EditDepartmentVisible: open });
          }}
        />

        {/* app设置 */}
        <AppDrawer
          visible={this.state.appDrawerVisible}
          treeData={this.state.departTreeData}
          departId={this.state.appDepartId}
          onCancel={() => {
            this.setState({
              appDrawerVisible: false
            });
          }}
          onOk={data => {
            if (data.limitSeeAppSwitch == 1 && !data.limitSeeAppType) return notification.error({
              message: '请选择类型'
            });
            // 开关为开启的时候判断是否有指定对应的部门
            if (
              data.limitSeeAppSwitch == 1 &&
              data.limitSeeAppType == '4' &&
              data.visibleDepartIds == ''
            ) return notification.error({
              message: '请选择指定部门'
            });
            saveDepartAppAuthInfo(data).then(res => {
              this.setState({
                appDrawerVisible: false
              });
            });
          }}
          onChange={visible => {
            this.setState({
              appDrawerVisible: visible
            })
          }}
        />

        {/* 保险员减员提示 */}
        <Modal
          className="reducepeople"
          title="保险减员提示"
          visible={this.state.reducepeoplevisible}
          onOk={this.handlereducepeopleOk}
          onCancel={this.handlereducepeopleCancel}
          footer={[
            <Button
              key="submit"
              type="primary"
              onClick={() => {
                this.setState({
                  reducepeoplevisible: false,
                  visible: true
                });
              }}
            >
              查看保险订单
            </Button>
          ]}
        >
          <div>
            <div>
              <Alert
                message="保险产品的增员、减员、替换等操作可通过【金融保险】-【保险订单】-选择有效订单的【保全】对保单中的人员增减操作！"
                type="warning"
                showIcon
              />
            </div>
            <p>
              {/* 本次离职人员共 {this.state.selectedRows.length} 位，[保险日期]已为其中 {this.state.dataSource.length}
               位员工购买过团意险产品[产品名称]（订单号：[订单编号]），企业可对离职人员办理保险保全的减员操作，以降低保险成本！ */}
              {/* 本次离职人员共 {this.state.selectedRowsLength} 位，其中已为 {this.state.dataSource.length}
               位员工购买过团意险保险产品，企业可对离职人员办理保险保全的减员操作，以降低保险成本！ */}
              本次离职人员共 {this.state.selectedRowsLength}{' '}
              位，其中有员工购买过团意险保险产品，企业可对离职人员办理保险保全的减员操作，以降低保险成本！
            </p>
          </div>
        </Modal>
        {/* 订单大于1时，选择订单 */}
        <Modal
          className="chooseorderlist"
          title="选择订单"
          visible={this.state.visible}
          onOk={() => {
            // if (!this.state.selectedRowKeys) {
            //   message.error('请选择订单');
            //   return null;
            // }
            if (!this.state.selectedRowKeysforOrder) {
              message.error('请选择订单');
              return null;
            } else {
              // this.newwin = window.open('about:blank');
              this.setState({
                visible: false,
                getOnlineInsBlbVisible: true
              });
              this.enterpriseInsComInsGetOnlineInsBlbPreservationLink();
            }
          }}
          onCancel={this.handleCancel}
        >
          <Alert
            message="当前企业所购买了多份团意险产品。请选择需要增员/减员的订单:"
            type="success"
            showIcon
          />
          {this.renderTable()}
        </Modal>
        {/* 初始化时保险弹窗 */}
        {/* <GetPlanBook
          okorcancel={(field, value) => {
            this.setState({ [field]: value });
          }}
          isIns={this.state.isIns}
          accessbookvisible={this.state.accessbookvisible}
          insurancetipsvisible={this.state.insurancetipsvisible}
        /> */}
        {/* 离职原因弹窗 */}
        <Modal
          title="填写离职原因"
          visible={this.state.reasonVisible}
          onOk={() => {
            const leaveDate = this.state.outReasonDate;
            if (leaveDate == "") return notification.error({
              message: '请选择日期'
            });
            this.withdrawnShowConfirm();
          }}
          onCancel={() => this.setState({ reasonVisible: false })}
        >
          <Row>
            <Col span={4}> <span style={{ color: 'red' }}>*</span>离职时间：</Col>
            <Col span={20}>
              <DatePicker
                value={this.state.outReasonDate == '' ? '' : moment(this.state.outReasonDate, 'YYYY-MM-DD')}
                format="YYYY-MM-DD"
                disabledDate={current => {
                  // return current && current > moment().endOf('day');
                  return (current && current < moment(this.state.requestDate).startOf('day')) || (current && current > moment(this.state.requestDate).endOf('day'));
                }}
                onChange={(date, dateString) => {
                  this.setState({
                    outReasonDate: dateString
                  });
                }}
              />
            </Col>
          </Row>
          <Row style={{ marginTop: 15 }}>
            <Col span={4}>离职原因：</Col>
            <Col span={20}>
              <TextArea
                maxlength={100}
                value={this.state.outReason}
                onChange={e => {
                  const outReason = e.target.value;
                  this.setState({
                    outReason
                  });
                }}
                placeholder="员工自动提交离职申请，现已解除劳动合同关系，系统离职处理。"
              ></TextArea>
            </Col>
          </Row>
          <Row>
            <Col span={4}></Col>
            <Col span={20}>
              <div style={{ color: "#ff9900", marginTop: 10 }}>
                <span>注：</span><br />
                <span>1、若不填写，则自动写入默认的离职原因；</span>
                <br />
                <span>2、批量离职时，离职原因共用。</span>
              </div>
            </Col>
          </Row>

        </Modal>
        <Modal
          title="确认离职人员"
          visible={this.state.TipsVisible}
          onOk={this.handleTipsOk}
          okText="确认离职"
          onCancel={this.handleTipsCancel}
        >
          <div>
            <span>
              1、离职后将取消关联的任务、考勤组，医社保记录中将自动移除离职人员，离职人员对应的劳动合同也将变更为终止；
              <br/>
              2、人员在线缴费的报名费用、保单信息需要请到相应管理页面人工处理。
            </span>
            <Table
              // rowSelection={rowSelection}
              columns={TipsColumns}
              dataSource={this.state.selectedRows}
              pagination={this.state.tipPegenav}
            />
          </div>
        </Modal>

        {/* 离职结果 */}
        <Modal
          title="离职提示"
          visible={this.state.TipsOKVisible}
          cancelButtonProps={
            {
              style: { display: 'none' }
            }
          }
          // onOk={this.handleTipsOk}
          width={700}
          okText="确定"
          onOk={this.handleTipsCancel}
          onCancel={this.handleTipsCancel}
        >
          <div>
            <span>
              {this.state.batchQuitData.successCount} 个员工离职成功，{' '}
              {this.state.batchQuitData.failCount}{' '}
              个员工离职失败，请核对。离职失败的员工请根据提示调整后再离职。离职成功的人员可在离职记录中查看。
            </span>
            <Table
              // rowSelection={rowSelection}
              columns={TipsOkColumns}
              dataSource={this.state.batchQuitData.failList}
              pagination={this.state.tipPegenav2}
            />
          </div>
        </Modal>
        <Modal
          // title="企业人员变动-员工离职，可在保单中减少相应的被保险人。"
          visible={this.state.getOnlineInsBlbVisible}
          onCancel={() =>
            this.setState({
              getOnlineInsBlbVisible: false
            })
          }
          width={1150}
          footer={[
            <Button
              // key="submit"
              type="primary"
              onClick={() => {
                this.setState({
                  getOnlineInsBlbVisible: false
                });
              }}
            >
              取消
            </Button>
          ]}
        >
          <iframe
            id="onlineBlbIframe"
            title="保全"
            src={this.state.onlineInsBlbUrl}
            frameBorder="0"
            width="100%"
            height="500px"
          />
        </Modal>
      </div>
    );
  }
}
