/**
 * 人员信息
 */
import React, { PureComponent } from "react";
import { Icon } from "antd";
import { connect } from "dva";
import { getEnterpriseList, passEnterpriseIDGetDepartList, passDepartIdGetDepartList, passDepartIdGetPersonList } from '../../../../../services/api';
import PersonItem from './PersonItem';
import styles from "../../Police/index.less";
@connect((state) => ({
  tab1Data: state.command.policeData.tab1,
  mapStyle: state.command.mapStyle
}))
export default class PersonList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      enterpriseList: [],//企业信息列表
      allHeight: null,
      currentTab: 1
    };
  }

  componentDidMount() {
    const allHeight = document.documentElement.clientHeight - 140 -16;
    this.setState({ allHeight });
    this._getEnterpriseList()
  }
  componentWillReceiveProps(nextProps) {
    const enterpriseList = JSON.parse(JSON.stringify(this.state.enterpriseList))
    if (this.state.currentTab != nextProps.clickTab) {
      enterpriseList.map((data, index) => {
        if (data.open) {
          data.open = false
          if (data.children.length > 0) {
            data.children.map(child => {
              this.close(child)
              this.closeSubordinateOpenStatus(child.children.departList)
            })
          }
        }
      })
      this.setState({ enterpriseList })
    }
  }
  //获取企业列表
  _getEnterpriseList(_currpage = 1) {
    getEnterpriseList({
      _currpage,
      lines: 10
    }, {
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__xzByH4ZZxj2gVJZv0G4",
      opentarget: "detail",
      containTitle: "企业信息接口",
    }).then(res => {
      this.setState({
        enterpriseList: this.state.enterpriseList.concat(res.data.data)
      })
      //如果没有加载完，需要再一次加载
      let { pageNumber, pageSize, total } = res.data
      if (total > pageNumber * pageSize) {
        this._getEnterpriseList(_currpage + 1)
      }
    })
  }
  //根据对应企业id的获取部门列表
  _passEnterpriseIDGetDepartList(_currpage = 1, enterpriseId, index) {
    passEnterpriseIDGetDepartList({
      _currpage: 1,
      lines: 10
    }, {
      did: enterpriseId,//企业id
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__MbFPvXeIwgTOEoodAVc",
      opentarget: "detail",
      containTitle: "部门信息接口",
      field: "",
    }).then(res => {
      //第一级的部门存储在企业列表信息下
      const { enterpriseList } = this.state
      const value = JSON.parse(JSON.stringify(enterpriseList))
      if (value[index].children) {
        value[index].children = value[index].children.concat(res.data.data)
      } else {
        value[index].children = res.data.data || []
      }
      this.setState({
        enterpriseList: value
      })
      //如果没有加载完，需要再一次加载
      let { pageNumber, pageSize, total } = res.data
      if (total > pageNumber * pageSize) {
        this._passEnterpriseIDGetDepartList(_currpage + 1, enterpriseId)
      }
    })
  }
  //获取部门和人员
  async _getDepartAndPerson(_currpage = 1, departID, place) {
    await this._passDepartIdGetDepartList(_currpage, departID, place)
    // await this._passDepartIdGetPersonList(_currpage, departID, place)
  }
  //根据部门id查询下级部门
  _passDepartIdGetDepartList(_currpage = 1, departID, place) {
    passDepartIdGetDepartList({
      _currpage,
      lines: 10
    }, {
      did: departID,
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__uPN8uNlIhDaGiEgKxnX",
      opentarget: "detail",
      containTitle: "根据部门id查询下级部门id",
    }).then(res => {
      let value
      if (this.state[departID]) {
        value = {
          parentId: departID,
          departList: this.state[departID].departList.concat(res.data.data),
          personList: [],
          open: true
        }
      } else {
        value = {
          parentId: departID,
          departList: res.data.data,
          personList: []
        }
      }
      this.setState({
        [departID]: value
      }, () => {
        //如果没有加载完，需要再一次加载
        let { pageNumber, pageSize, total } = res.data
        if (total > pageNumber * pageSize) {
          this._passDepartIdGetDepartList(_currpage + 1, departID,place)
        } else {
          //查询人员
          this._passDepartIdGetPersonList(_currpage, departID, place)
        }
      })
    })
  }
  //根据部门id查询保安员
  _passDepartIdGetPersonList(_currpage = 1, departID, place) {
    passDepartIdGetPersonList({
      _currpage,
      lines: 100
    }, {
      did: departID,
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__P1bb27ekxYoAiowqVv1",
      opentarget: "detail",
      containTitle: "部门ID查询保安员信息接口"
    }).then(res => {
      const data = res.data.data
      data.map((element, index) => {
        const location = element.position && JSON.parse(element.position)
        if (location) {
          data[index].longitude = location.longitude || ''
          data[index].latitude = location.latitude || ''
          data[index].name = element.securityName
        }
        data[index].mobilePhone = element.phone
      });
      let value = this.state[departID]
      if (!value) {
        value = {
          departList: [],
          personList: []
        }
      }
      value.personList = value.personList.concat(data)
      value.place = place
      //打点
      this.props.addPoliceMarks(data, place, 'tab1')//1指tab
      this.setState({
        [departID]: value
      }, () => {
        //如果没有加载完，需要再一次加载
        let { pageNumber, pageSize, total } = res.data
        if (total > pageNumber * pageSize) {
          this._passDepartIdGetPersonList(_currpage + 1, departID,place)
        } else if (place) {
          this.setValue(place, this.state[departID])
        }
      })
    })
  }
  //将取到的部门跟人员数据存储起来
  setValue(place, data) {
    const enterpriseList = JSON.parse(JSON.stringify(this.state.enterpriseList))
    var value
    if (place.length < 3) {
      for (var i = 0; i < place.length; i++) {
        if (i == 0) {
          value = enterpriseList[place[i]]
        } else {
          value = value.children[place[i]]
        }
      }
      value.children = {
        ...data
      }
    } else {
      for (var i = 0; i < place.length; i++) {
        if (i == 0) {
          value = enterpriseList[place[i]]
        } else if (i == 1) {
          value = value.children[place[i]]
        } else {
          value = value.children.departList[place[i]]
        }
      }
      value.children = {
        ...data
      }
    }
    this.setState({ enterpriseList })
  }
  //改变列表是否被展开状态
  switchOpenStatus(place) {
    //每次是打开的时候，需要存储打开列表的位置，为了后续切换tab的时候，将数据点清除
    if (!place) {
      return;
    }
    const enterpriseList = JSON.parse(JSON.stringify(this.state.enterpriseList))
    var value
    for (var i = 0; i < place.length; i++) {
      if (i == 0) {
        //第一级是企业，企业下没有保安员，不用存储数据
        value = enterpriseList[place[i]]
      } else if (i == 1) {
        value = value.children[place[i]]
      } else {
        value = value.children.departList[place[i]]
      }
    }
    value.open = !value.open
    if (place.length > 1) {
      switch (value.open) {
        case true://打点
          if (value.children && value.children.personList.length > 0) {
            this.props.addPoliceMarks(value.children.personList, place, 'tab1')
          }
          break;
        case false://关掉打点
          //关掉下级打点
          //自己也关掉
          const reduceData = this.props.tab1Data[place]
          if (reduceData) {
            this.props.reducePoliceMarks(reduceData, place, 'tab1')
          }
          //下级部门的人员以及open状态都要关掉
          if (value.children && value.children.departList.length > 0) {
            value = this.closeSubordinateOpenStatus(value.children.departList)
          }
          break;
      }
    } else if (value.open == false) {
      //企业自己不用关
      //下级部门的人员以及open状态都要关掉
      if (value.children.length > 0) {
        value.children.map(child => {
          this.close(child)
          child.children && this.closeSubordinateOpenStatus(child.children.departList)
        })
      }
    }
    this.setState({
      enterpriseList
    })
  }
  //关掉下级的open状态
  closeSubordinateOpenStatus(data) {
    data.map((item, index) => {
      if (item.children && item.children.departList.length > 0) {
        this.close(data[index])
        this.closeSubordinateOpenStatus(item.children.departList)
      } else {
        this.close(data[index])
      }
    })
    return data
  }
  close(data) {
    data.open = false
    if (data.children && data.children.place) {
      const placeIndex = data.children.place
      const reduceData = this.props.tab1Data[placeIndex]
      this.props.reducePoliceMarks(reduceData, placeIndex, 'tab1')
    }
  }
  //渲染部门跟保安员信息
  // 非第一级列表
  _renderDepartAndPerson(list) {
    const value = JSON.parse(JSON.stringify(list))
    if (list.children) {
      return (
        this._renderDepartAndPerson(list.children)
      )
    }
    return value.personList.concat(value.departList).map((perAndDep, index) => {
      const place = JSON.parse(JSON.stringify(list.place))
      place.push(index - value.personList.length)
      if (perAndDep.children) {
        return (
          <div key={perAndDep.id + index}>
            <div className={styles.depart} key={perAndDep.id} onClick={(e) => {
              e.stopPropagation()
              this.switchOpenStatus(place)
            }}>
              {this._renderTitle(perAndDep, place)}
              {perAndDep.open && this._renderDepartAndPerson(perAndDep.children)}
            </div>
          </div>
        )
      } else {
        return (
          <div key={perAndDep.id + index}>
            {
              perAndDep.securityName && this._renderPersonList(perAndDep, index, list.place)
            }
            {
              perAndDep.parentid && <div className={styles.depart} key={perAndDep.id} onClick={(e) => {
                e.stopPropagation()
                if (!perAndDep.children) {
                  //获取部门下的部门+部门下的保安员
                  this._getDepartAndPerson(1, perAndDep.id, place)
                }
                this.switchOpenStatus(place)
              }}>
                {this._renderTitle(perAndDep, place)}
              </div>
            }
          </div>
        )
      }
    })
  }
  //渲染保安员
  _renderPersonList(perAndDep, index, place) {
    return (
      <div onClick={(e) => e.stopPropagation()}>
        <PersonItem
          place={place}
          tab='tab1'
          _thisGIS={this.props._thisGIS}
          data={[perAndDep]}
          index={index}
        />
      </div>
    )
  }
  //渲染列表下的企业跟部门名称
  _renderTitle(value, place) {
    const { mapStyle } = this.props
    if (place.length == 1) {
      return <>
        <span className={styles.ellipsis} style={{ width: '230px' }}>
          {value.name}
        </span>
        <Icon className={styles.icon} type={value.open ? 'up' : 'down'} style={{ color: mapStyle == 'dark' ? '#fff' : '' }} />
      </>
    } else {
      return <>
        <span className={styles.ellipsis} style={{ color: value.open ? '#0E70FF' : '' }}>{value.name}</span>
        <Icon className={styles.icon} type={value.open ? 'up' : 'down'} style={{ color: value.open ? '#0E70FF' : mapStyle == 'dark' ? '#fff' : '' }} />
      </>
    }
  }
  render() {
    const { enterpriseList } = this.state
    const { mapStyle } = this.props
    return (
      <div className={styles[mapStyle]}>
        <div className={styles.personList} style={{ maxHeight: this.state.allHeight, overflow: 'auto' }}>
          {
            enterpriseList.length > 0 ? enterpriseList.map((list, index) => {
              return <div key={list.id + index}>
                {/* 企业节点 */}
                <div key={list.id + index} className='' onClick={(e) => {
                  e.stopPropagation()
                  if (!list.children) {
                    //获取部门列表节点
                    this._passEnterpriseIDGetDepartList(1, list.id, index)
                  }
                  this.switchOpenStatus([index])
                }}>
                  {/* 企业列表（企业下暂定没有保安员） */}
                  {this._renderTitle(list, [index])}
                  {/* 企业下第一级部门节点列表（部门+保安员） */}
                  <div>
                    {
                      list.open && list.children && list.children.map((departItem, depIndex) => {
                        return (
                          <div key={departItem.id + index}>
                            <div className={styles.depart} key={departItem.id} onClick={async (e) => {
                              e.stopPropagation()
                              if (!departItem.children) {
                                //获取部门下的部门+部门下的保安员
                                await this._getDepartAndPerson(1, departItem.id, [index, depIndex])
                              }
                              await this.switchOpenStatus([index, depIndex])
                            }}>
                              {this._renderTitle(departItem, [index, depIndex])}
                              {/* 非第一级部门节点 */}
                              {/* 部门的部门节点，以及部门下的保安人员节点 */}
                              <div>
                                {/* 循环渲染部门跟保安员 */}
                                {
                                  departItem.open && departItem.children && this._renderDepartAndPerson(departItem.children)
                                }
                              </div>
                            </div>
                          </div>
                        )
                      })
                    }
                  </div>
                </div>
              </div>
            }) : <span className={styles.detail}>暂无数据...</span>
          }
        </div>
      </div>
    );
  }
}
