/**
 * 人员列表 @author Lyq
 */
import React, { Component } from "react";
import { Input, Icon, Radio, Checkbox } from "antd";

import {
  // getDepartmentData,
  systemComDepartGetDepartTree,
  getDepartPersonList,  //公共通过部门获取人员
  getPerListByKeyword,  //公共关键字获取人员
  getHuaweiDepartPersonList, //华为会议 通过部门获取人员
  getHuaweiPerListByKeyword, //华为会议 关键字获取人员
  getTaskDepartPersonList, //助勤 通过部门获取人员
  getTaskPerListByKeyword, //助勤 关键字获取人员
} from '../../../services/api';
import $loading from '../../../utils/loading';
const { Search } = Input;

export default class PersonList extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      navtree: [],  //层级数据
      personList: [], //当前的人员列表 (单选的情况)
      listParams: {  // 请求人员列表的参数
        pageNumber: 1,
        pageSize: 10
      },
      keywordList: [],  //关键字搜索列表
      keywordParams: {
        pageNumber: 1,
        pageSize: 10
      },
      keyword: '', //关键字
      departInfo: {
        // id: []
      }//缓存部门id的集合,key是部门id，value是一个数组，对应部门下的人员
    };
  }
  componentDidMount() {
    //---获取部门列表数据
    systemComDepartGetDepartTree().then(res => {
      // 设置导航数据
      this.setState({
        navtree: res.data
      }, () => {
        if (this.props.type == 'checkbox') {
          this._getCurrentInfo();//多选
        } else {
          this._getDepartUser();//单选
        }
      });
    });
  }
  componentWillReceiveProps(nextprops) {
  }
  /* *****************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].departId;
    //获取是否有权限
    const isExistsDataAuth = navtree[navtree.length - 1].isExistsDataAuth;
    const requestParameters = { departId, ...listParams };
    // 获取接口
    let getFun = getDepartPersonList;
    if (this.props.fetchType == 'huawei') {
      getFun = getHuaweiDepartPersonList;
    } else if (this.props.fetchType == 'task') {
      getFun = getTaskDepartPersonList;
    }
    //判断如果是驻勤模块的，需要判断有没有权限，若没有权限就不请求人员数据，直接返回没有权限
    if (this.props.fetchType == 'task' && isExistsDataAuth == '0') {
      this.setState({
        personList: ['noAuth'], //更新数据,没有权限可以查看该部门下的人员信息
        listParams,  //设置页面参数
        totalPage: 0
      });
    } else {
      getFun(requestParameters).then(res => {
        this.setState({
          personList: [...personList, ...res.data.data], //更新数据
          listParams,  //设置页面参数
          totalPage: res.data.totalPage
        });
      });
    }
  }
  // 传入部门id通过接口获取部门下的所有人
  _getPersonByDepartId = (departIds = []) => {
    // 获取接口方法
    let getFun = getDepartPersonList;
    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 });
        });
      }
    });
  }
  //--获取搜索人员
  _getKeywordUser = (loadMore) => {
    let { keyword, keywordParams, keywordList } = this.state;
    if (!keyword) return;
    // 加载更多
    if (loadMore) {
      keywordParams.pageNumber++;
    } else {
      // 刷新列表
      keywordParams.pageNumber = 1;
      keywordList = [];
    }

    const requestParameters = { keyword, ...keywordParams };
    // 获取接口
    let getFun = getPerListByKeyword;
    if (this.props.fetchType == 'huawei') {
      getFun = getHuaweiPerListByKeyword;
    } else if (this.props.fetchType == 'task') {
      getFun = getTaskPerListByKeyword;
    }
    getFun(requestParameters).then(res => {
      this.setState({
        keywordList: [...keywordList, ...res.data.data], //更新数据
        keywordParams,  //设置页面参数
        keywordTotalPage: res.data.totalPage
      });
    });
  }

  /* *****************mothods****************** */
  // 获取当前部门下的人员和部门信息(多选部分页的情况)
  _getCurrentInfo = () => {
    const { navtree } = this.state;
    // 当前应当展示的部门数据
    const currentTree = (navtree[navtree.length - 1] && navtree[navtree.length - 1].childDepart) || [];
    // 获取当前部门人员和当前子部门的人员
    // const departIds = currentTree.map(({ departId }) => departId);
    const departIds = []
    const { departInfo } = this.state;
    //如果是驻勤模块的，需要先判断是否有权限
    for (let r = 0; r < currentTree.length; r++) {
      switch (this.props.fetchType) {
        case 'task':
          if (currentTree[r].isExistsDataAuth == '1') {
            departIds.push(currentTree[r].departId)
          } else {
            departInfo[currentTree[r].departId] = 'noAuth'//更新数据,没有权限可以查看该部门下的人员信息
          }
          break;
        default:
          departIds.push(currentTree[r].departId)
      }
    }
    switch (this.props.fetchType) {
      case 'task':
        if (navtree[navtree.length - 1].isExistsDataAuth == '1') {
          departIds.push(navtree[navtree.length - 1].departId);
        } else {
          departInfo[navtree[navtree.length - 1].departId] = 'noAuth'//更新数据,没有权限可以查看该部门下的人员信息
        }
        break;
      default:
        departIds.push(navtree[navtree.length - 1].departId);
    }
    this.setState({ departInfo })
    this._getPersonByDepartId(departIds);
  }

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

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

    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()
                    }
                  });
                }}
                className="nav"
              >
                {val.departName}
                <Icon type="right" />
              </span>
            );
          }
          return <span key={index}>{val.departName}</span>;
        })}
      </div>
    );
  };
  /* ---无搜索（展示部门信息） */
  _renderDepartment = () => {
    const { navtree } = this.state;
    // 当前应当展示的部门数据
    const currentTree = (navtree[navtree.length - 1] && navtree[navtree.length - 1].childDepart) || [];
    // 多选的情况
    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.departId) == '-1') {
                return item.departId;
              }
            });
            // 删除未选中部门的下的所有人员
            unSelected.forEach(departId => {
              if (departInfo[departId]) {
                this.props.delDepart(departInfo[departId] != 'noAuth' ? departInfo[departId] || [] : []);
              }
            });
            // 新增选中部门下的人员
            values.forEach(departId => {
              this.props.addDepart(departInfo[departId] != 'noAuth' ? departInfo[departId] || [] : []);
            });
            $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.departId}
                    disabled={this.props.fetchType == 'task' && val.isExistsDataAuth == '0'}//驻勤模块，需要判断权限
                  >
                    <span>
                      {val.departName}
                    </span>
                  </Checkbox>
                </div>

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

          </div>
        );
      })
    );
  };
  // 人员列表
  _renderPersonList = () => {
    // 多选的情况（没有分页）直接读取缓存数据
    if (this.props.type == 'checkbox') {
      const { departInfo, navtree } = this.state;
      const currentDepartId = navtree[navtree.length - 1] ? navtree[navtree.length - 1].departId : '-1';
      const personList = departInfo[currentDepartId] || [];
      if (personList == 'noAuth') {
        return this._renderNoAuth()
      }
      return (
        <div>
          <Checkbox.Group
            onChange={value => {
              this.props.onSelect(value, personList);
            }}
            value={(() => {
              let { value } = this.props;
              //因为排序的问题，JSON.parse以后值不一样 从列表中找到值替换掉(保证有初始值的时候选择框能被选中)
              // value = value.map(item => JSON.stringify(item));
              return value.map(item => {
                item = personList.find(listItem => item.perId == listItem.perId) || item;
                return JSON.stringify(item);
              });
            })()}
          >
            {personList.map((val, index) => {
              return (
                <Checkbox
                  key={index}
                  className="radioStyle"
                  value={JSON.stringify(val)}
                >
                  <i className="usericon" />
                  {val.name}
                  {val.idCardNo ? "(" + val.idCardNo + ")" : ""}
                </Checkbox>
              );
            })}
          </Checkbox.Group>
          {/* <div style={{textAlign: 'center', fontSize: 12, marginTop: 10}}>没有更多了</div> */}
        </div>
      );
    }

    // 单选的情况采用分页的方式
    const { personList, totalPage, listParams } = this.state;
    if (personList[0] == 'noAuth') {
      return this._renderNoAuth()
    }
    return (
      <div>
        <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) : '';
          })()}
        >
          {personList.map((val, index) => {
            return (
              <Radio
                key={index}
                className="radioStyle"
                value={JSON.stringify(val)}
              >
                <i className="usericon" />
                {val.name}
                {val.idCardNo ? "(" + val.idCardNo + ")" : ""}
              </Radio>
            );
          })}
        </Radio.Group>
        {
          totalPage > listParams.pageNumber &&
          <div style={{ textAlign: "center", color: "#0f71ff" }}>
            <a
              onClick={() => {
                this._getDepartUser(true);
              }}
            >
              点击加载更多...
              </a>
          </div>
        }
      </div>
    );
  }
  // 搜索列表
  _renderKeywordList = () => {
    const { keywordList, keywordTotalPage, keywordParams } = this.state;
    let Group = Radio.Group;
    let GroupItem = Radio;
    if (this.props.type == 'checkbox') {
      Group = Checkbox.Group;
      GroupItem = Checkbox;
    }
    return (
      <div>
        <Group
          onChange={e => {
            let value = [];
            // checkbox返回的是一个数组
            if (this.props.type == 'checkbox') {
              value = e;
            } else {
              // radio返回的是一个目标对象
              value.push(e.target.value);
            }
            this.props.onSelect(value, this.state.keywordList);
          }}
          value={(() => {
            let { value } = this.props;
            //因为排序的问题，JSON.parse以后值不一样 从列表中找到值替换掉(保证有初始值的时候选择框能被选中)
            // value = value.map(item => JSON.stringify(item));
            value = value.map(item => {
              item = this.state.keywordList.find(listItem => item.perId == listItem.perId) || item;
              return JSON.stringify(item);
            });
            if (this.props.type != 'checkbox') {
              value = value[0];
              // value = JSON.stringify(value[0]);
            }
            return value;
          })()}
        >
          {keywordList.map((val, index) => {
            // if (val.treeType === '2') {
            return (
              <GroupItem
                key={index}
                style={{ display: val.show }}
                className="radioStyle"
                value={JSON.stringify(val)}
              >
                <i className="usericon" />
                {val.name}
                {val.idCardNo ? "(" + val.idCardNo + ")" : ""}
              </GroupItem>
            );
            // }
            // return '';
          })}
          <GroupItem
            style={{ display: "none" }}
            key="null"
            className="radioStyle"
            value="null"
          >
            无值
            </GroupItem>
        </Group>
        {
          keywordTotalPage > keywordParams.pageNumber &&
          <div style={{ textAlign: "center", color: "#0f71ff" }}>
            <a
              onClick={() => {
                this._getKeywordUser(true);
              }}
            >
              点击加载更多...
              </a>
          </div>
        }
      </div>
    );
  }
  //渲染没有权限的样式
  _renderNoAuth = () => {
    return <div className="noAuth">
      {/* <img src={require('../../../assets/images/frown.png')} /> */}
      <p>您没有查看该部门的权限</p>
    </div> 
  }
  // 渲染整个组件
  render() {
    return (
      <div className="SelectUser" style={{ ...this.props.style }}>
        <Search
          placeholder="搜索姓名/手机号/身份证"
          value={this.state.keyword}
          onChange={e => {
            this.setState({
              keyword: e.target.value
            }, () => {
              this._getKeywordUser();
            });
          }}
          onSearch={value => console.log(value)}
        />
        {/* 面包屑 */}
        {!this.state.keyword && this._renderNavBar()}
        {/* 渲染部门 */}
        {!this.state.keyword && this._renderDepartment()}
        {/* 人员列表 */}
        {!this.state.keyword && this._renderPersonList()}
        {/* 搜索列表 */}
        {this.state.keyword && this._renderKeywordList()}
      </div>
    );
  }
}


