/**
 * 人员列表
 */
import React, { Component } from "react";
import { Icon, Radio, Checkbox, Tooltip, message } from "antd";
import { connect } from "dva";
import {
  getDepartmentData,
  getComPerLocationByKeyword,  //公共通过部门获取人员
  getHuaweiDepartPersonList, //华为会议 通过部门获取人员
  getTaskDepartPersonList, //助勤 通过部门获取人员
} from '../../../../../../services/api';
import $loading from '../../../../../../utils/loading';
import PersonItem from '../PersonItem';
import '../person.less';
@connect((state) => ({
  selectedId: state.command.personList.selectedId,
  tabIndex1: state.command.tabIndex.tabIndex1,
  tabIndex2: state.command.tabIndex.person.tabIndex2,
  addressList: state.command.personList.addressList
}))
export default class PersonList extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      tabKey1:'2',
      tabKey: "2",
      currentKey: null, //主要用于处理tab页面改变，不让重新请求数据
      navtree: [],  //层级数据
      personList: [], //当前的人员列表 (单选的情况)
      listParams: {  // 请求人员列表的参数
        pageNumber: 1,
        pageSize: 10
      },
      keywordList: [],  //关键字搜索列表
      keywordParams: {
        pageNumber: 1,
        pageSize: 10
      },
      keyword: '', //关键字
      departInfo: {
        // id: []
      }//缓存部门id的集合,key是部门id，value是一个数组，对应部门下的人员
    };
  }
  componentDidMount() {
    //---获取部门列表数据
    getDepartmentData().then(res => {
      // 设置导航数据
      this.setState({
        navtree: res.data
      }, () => {
        if (this.props.type == 'checkbox') {
          // this._getCurrentInfo();
        } else {
          this._getDepartUser();
        }
      });
    });
  }
  componentWillReceiveProps(nextProps) {
    if (
      nextProps.tabIndex2 == this.state.tabKey &&//当前点击第二层的tab页是自己
      this.props.addressList.length > 0 &&//通讯录的列表值不为空
      nextProps.tabIndex2 !== this.state.currentKey&&//过去的tab页不是自己（为了页面重复刷新）
      nextProps.tabIndex1==this.state.tabKey1//第一层的tab页是自己的父级
    ) {
      this.props.dispatch({
        type: "command/fetchPersonList",
        payload: {
          list: [
            ...this.props.addressList,
          ],
        },
      });
      this.setState({
        currentKey: nextProps.tabIndex2,
      });
    }
    if (nextProps.tabIndex2 != this.state.tabKey) {//当前页不是自己的
      this.setState({
        currentKey: null,
      });
    }
  }
  /* *****************ajax****************** */
  //--获取当前部门人员（分页）
  _getDepartUser = (loadMore) => {
    let { navtree, listParams, personList } = this.state;
    // 加载更多
    if (loadMore) {
      listParams.pageNumber++;
    } else {
      // 刷新列表
      listParams.pageNumber = 1;
      personList = [];
    }
    // 获取id
    const departId = navtree[navtree.length - 1].key;
    const requestParameters = { departId, ...listParams };
    // 获取接口
    let getFun = getComPerLocationByKeyword;
    if (this.props.fetchType == 'huawei') {
      // getFun = getHuaweiDepartPersonList;
    } else if (this.props.fetchType == 'task') {
      getFun = getTaskDepartPersonList;
    }
    getFun(requestParameters).then(res => {
      this.setState({
        personList: [...personList, ...res.data.data], //更新数据
        listParams,  //设置页面参数
        totalPage: res.data.totalPage
      });
      this.props.dispatch({
        type: "command/fetchPersonList",
        payload: {
          list: [...personList, ...res.data.data],
        },
      });
      this.props.dispatch({
        type: "command/fetchPersonAddressList",
        payload: {
          addressList: [...personList, ...res.data.data],
        },
      });
    });
  }
  // 传入部门id通过接口获取部门下的所有人
  _getPersonByDepartId = (departIds = []) => {
    // 获取接口方法
    let getFun = getComPerLocationByKeyword;
    if (this.props.fetchType == 'huawei') {
      getFun = getHuaweiDepartPersonList;
    } else if (this.props.fetchType == 'task') {
      getFun = getTaskDepartPersonList;
    }
    // 循环调用接口获取对应部门的数据
    const { departInfo } = this.state;
    departIds.forEach(departId => {
      if (!departInfo[departId]) {  //该部门数据没有被缓存
        // 获取对应部门的人员数据
        getFun({
          departId,
          pageNumber: 1,
          pageSize: 1000000
        }).then(res => {
          // 储存对应的部门数据
          departInfo[departId] = res.data.data;
          this.setState({ departInfo });
        });
      }
    });
  }
  /* *****************mothods****************** */
  // 获取当前部门下的人员和部门信息(多选部分页的情况)
  _getCurrentInfo = () => {
    const { navtree } = this.state;
    // 当前应当展示的部门数据
    const currentTree = (navtree[navtree.length - 1] && navtree[navtree.length - 1].children) || [];
    // 获取当前部门人员和当前子部门的人员
    const departIds = currentTree.map(({ key }) => key);
    departIds.push(navtree[navtree.length - 1].key);
    this._getPersonByDepartId(departIds);
  }

  // 部门被选中的值（多选）
  _getDepartValues = () => {
    const { navtree, departInfo } = this.state;
    const { value } = this.props;
    // 当前应当展示的部门数据
    const currentTree = (navtree[navtree.length - 1] && navtree[navtree.length - 1].children) || [];

    let selectedDeparts = [];
    currentTree.forEach(cItem => {
      let result = true;
      if (departInfo[cItem.key]) {
        result = true;
        if (departInfo[cItem.key].length > 0) {
          for (let i = 0; i < departInfo[cItem.key].length; i++) {
            if (!value.some(item => item.perId == departInfo[cItem.key][i].perId)) {
              result = false;
              break;
            }
          }
        } else {
          result = false;
        }
      } else {
        result = false;
      }
      result && selectedDeparts.push(cItem.key);
    });

    return selectedDeparts;
  }
  /* *****************render****************** */
  // 面包屑
  _renderNavBar = () => {
    const { navtree } = this.state;
    return (
      <div className="nav-partment" ref="navPartment" id="s">
        {navtree.map((val, index) => {
          if (navtree.length - 1 !== index) {
            return (
              <span
                key={index}
                onClick={() => {
                  this.setState({
                    navtree: this.state.navtree.slice(0, index + 1)
                  }, () => {
                    // 单选的情况重新加载当前人员列表
                    if (this.props.type != 'checkbox') {
                      this._getDepartUser()
                    }
                  });
                  this.clear()
                }}
                className="nav"
              >
                {val.title}
                <Icon type="right" />
              </span>
            );
          }
          return <span key={index}>{val.title}</span>;
        })}
      </div>
    );
  };
  //清空点击数据
  clear() {
    if (this.props.selectedId) {
      //清空人员的点击数据
      this.props.dispatch({
        type: "command/setPersonSelectIndex",
        payload: null,
      });
      this.props.dispatch({
        type: 'command/clearInfoWindow',
        payload: true
      })
    }
  }
  /* ---无搜索（展示部门信息） */
  _renderDepartment = () => {
    const { navtree } = this.state;
    // 当前应当展示的部门数据
    const currentTree = (navtree[navtree.length - 1] && navtree[navtree.length - 1].children) || [];
    // 多选的情况
    if (this.props.type == 'checkbox') {

      return (
        <Checkbox.Group
          value={this._getDepartValues()}
          onChange={values => {
            $loading.open('数据处理中...');
            let { departInfo } = this.state;
            // 获取当前部门列表未选中的项目
            const unSelected = currentTree.map(item => {
              if (values.indexOf(item.key) == '-1') {
                return item.key;
              }
            });
            // 删除未选中部门的下的所有人员
            unSelected.forEach(key => {
              if (departInfo[key]) {
                this.props.delDepart(departInfo[key] || []);
              }
            });
            // 新增选中部门下的人员
            values.forEach(key => {
              this.props.addDepart(departInfo[key] || []);
            });
            $loading.close();
          }}
        >
          {
            currentTree.map((val, index) => {
              return (
                <div className="department_item" key={index}>
                  <span
                    onClick={() => {
                      navtree.push(val);
                      this.setState({ navtree }, () => this._getCurrentInfo());
                    }}
                    className="lower"
                  >
                    <i className="lowever_icon" />
                    下级
                  </span>
                  <i className="department_icon" />
                  <Checkbox
                    key={index}
                    value={val.key}
                  >
                    <span>
                      {val.title}
                    </span>
                  </Checkbox>
                </div>

              );
            })
          }
        </Checkbox.Group>
      );
    }
    // 单选的情况
    return (
      currentTree.map((val, index) => {
        return (
          <div key={index} className="department_item">
            <span
              onClick={() => {
                this.clear()
                navtree.push(val);
                this.setState({ navtree }, () => this._getDepartUser());
              }}
              className="lower"
            >
              <i className="lowever_icon" />
              下级
            </span>
            <i className="department_icon" />
            <span className="department_name">
              {val.title}
            </span>

          </div>
        );
      })
    );
  };
  // 人员列表
  _renderPersonList = () => {
    // 单选的情况采用分页的方式
    const { personList, totalPage, listParams } = this.state;
    return (
      <div className="search-list_command">
        <Radio.Group
          onChange={e => {
            this.props.onSelect([e.target.value], this.state.personList);
          }}
          value={(() => {
            let { value } = this.props;
            if (value.length == 0) return '';
            const item = personList.find(listItem => listItem.perId == value[0].perId);
            return item ? JSON.stringify(item) : '';
          })()}
        >
          <PersonItem data={personList} />
        </Radio.Group>
        {
          totalPage > listParams.pageNumber &&
          <div style={{ textAlign: "center", color: "#0f71ff" }}>
            <a
              onClick={() => {
                this._getDepartUser(true);
              }}
            >
              点击加载更多...
              </a>
          </div>
        }
      </div>
    );
  }
  // 渲染整个组件
  render() {
    return (
      <div className="SelectUser_command" style={{ ...this.props.style }}>

        {/* 面包屑 */}
        {!this.state.keyword && this._renderNavBar()}
        {/* 渲染部门 */}
        {!this.state.keyword && this._renderDepartment()}
        {/* 人员列表 */}
        {!this.state.keyword && this._renderPersonList()}

      </div>
    );
  }
}


