/**
 * 驻勤点信息
 */
import React, { PureComponent } from "react";
import { Icon } from "antd";
import { connect } from "dva";
import { getEnterpriseList, passEnterpriseIDGetAttendanceList, getSecurityManByAttendanceId } from '@services/api';
import PersonItem from './PersonItem';
import styles from "../../Police/index.less";
@connect((state) => ({
  tab2Data: state.command.policeData.tab2,
  mapStyle: state.command.mapStyle
}))
export default class AttendanceList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      enterpriseList: [],//企业信息列表以及驻勤点信息
      allHeight: null,
      currentTab: 2
    };
  }

  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.attendanceList && data.attendanceList.length > 0) {
            data.attendanceList.map((item, itemIndex) => {
              if (item.open) {
                this.close(item,[index, itemIndex])
              }
            })
          }
        }
      })
      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的驻勤点列表
  _passEnterpriseIDGetAttendanceList(_currpage = 1, enterpriseId, index) {
    passEnterpriseIDGetAttendanceList({
      _currpage: 1,
      lines: 10
    }, {
      did: enterpriseId,
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__Mxf0ppgb6L8Hg6Va7Y5",
      opentarget: "detail",
      containTitle: "企业id查询驻勤点"
    }).then(res => {
      //第一级的部门存储在企业列表信息下
      const { enterpriseList } = this.state
      const value = JSON.parse(JSON.stringify(enterpriseList))
      if (value[index].attendanceList) {
        value[index].attendanceList = value[index].attendanceList.concat(res.data.data)
      } else {
        value[index].attendanceList = res.data.data || []
      }
      this.setState({
        enterpriseList: value
      })
      //如果没有加载完，需要再一次加载
      let { pageNumber, pageSize, total } = res.data
      if (total > pageNumber * pageSize) {
        this._passEnterpriseIDGetAttendanceList(_currpage + 1, enterpriseId)
      }
    })
  }

  //根据驻勤点id查询保安员列表
  _passAttendanceIdGetPersonList(_currpage = 1, departID, index, attenIndex) {
    getSecurityManByAttendanceId({
      attendanceId: departID
    }).then(res => {
      const data = res.data
      let result = data.map((item)=>{
        item.perId = item.item_userid
        delete item.item_userid
        item.name = item.item_securityname ? item.item_securityname : item.principalName
        delete item.item_securityname
        delete item.principalName
        let lnglatData =item.item_lonlatjson? JSON.parse(item.item_lonlatjson):''
        item.lnglat =lnglatData? [lnglatData.longitude,lnglatData.latitude]:''
        if (lnglatData) {
          item.longitude = lnglatData.longitude || ''
          item.latitude = lnglatData.latitude || ''
        }
        // item.lnglat = [118.051982,24.607542]
        delete item.item_lonlatjson
        item.idCardNo = item.item_documentid ? item.item_documentid : item.principalIdCardNo
        delete item.item_documentid
        delete item.principalIdCardNo
        item.mobilePhone = item.item_phone ? item.item_phone : item.principalPhoneNo
        delete item.item_phone
        delete item.principalPhoneNo
        return item
      })

      const { enterpriseList } = this.state
      const value = JSON.parse(JSON.stringify(enterpriseList))
      if (value[index].attendanceList[attenIndex].personList) {
        value[index].attendanceList[attenIndex].personList = value[index].attendanceList[attenIndex].personList.concat(result)
      } else {
        value[index].attendanceList[attenIndex].personList = result || []
      }
      //打点
      this.props.addPoliceMarks(result, [index, attenIndex], 'tab2')//1指tab
      this.setState({
        enterpriseList: value
      })
      //如果没有加载完，需要再一次加载
      let { pageNumber, pageSize, total } = res.data
      if (total > pageNumber * pageSize) {
        this._passAttendanceIdGetPersonList(_currpage + 1, departID)
      }
    })
  }
  //传入的
  switchOpenStatus(place) {
    if (!place) {
      retrun
    }
    const { enterpriseList } = this.state
    const value = JSON.parse(JSON.stringify(enterpriseList))
    if (place.length == 1) {
      value[place[0]].open = !value[place].open
      switch (value[place[0]].open) {
        case false:
          if (value[place[0]].attendanceList && value[place[0]].attendanceList.length > 0) {
            value[place[0]].attendanceList.map((item, index) => {
              if (item.open) {
                this.close(item,[place[0], index])
              }
            })
          }
          break;
        default:
          break;
      }
    } else {
      value[place[0]].attendanceList[place[1]].open = !value[place[0]].attendanceList[place[1]].open
      switch (value[place[0]].attendanceList[place[1]].open) {
        case true:
          if (value[place[0]].attendanceList[place[1]].personList) {
            this.props.addPoliceMarks(value[place[0]].attendanceList[place[1]].personList, place, 'tab2')
          }
          break;
        case false:
          const reduceData = this.props.tab2Data[place]
          this.props.reducePoliceMarks(reduceData, place, 'tab2')
          break;
      }
    }
    this.setState({
      enterpriseList: value
    })
  }
  close(item,place){
    item.open = false
    const reduceData = this.props.tab2Data[place]
    this.props.reducePoliceMarks(reduceData, place, 'tab2')
  }
  //渲染部门跟保安员信息
  _renderDepartAndPerson(personList, place) {
    return (
      <div style={{ marginLeft: '15px' }}>
        <PersonItem
          place={place}
          tab='tab2'
          _thisGIS={this.props._thisGIS}
          data={personList}
        />
      </div>
    )
  }
  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}>
                  <div onClick={() => {
                    if (!list.attendanceList) {
                      //获取部门列表节点
                      this._passEnterpriseIDGetAttendanceList(1, list.id, index)
                    }
                    this.switchOpenStatus([index])
                  }}>
                    <span className={styles.ellipsis} style={{ width: '230px' }}>
                      {list.name}
                    </span>
                    <Icon className={styles.icon} type={list.open ? 'up' : 'down'} style={{ color: mapStyle == 'dark' ? '#fff' : '' }} />
                  </div>
                  {/* 第一级部门节点列表 */}
                  {
                    list.open && <div>
                      {
                        list.attendanceList && list.attendanceList.map((attendanceItem, attenIndex) => {
                          return (
                            <div key={attendanceItem.id + index}>
                              <div className={styles.depart} key={attendanceItem.id} onClick={(e) => {
                                //获取驻勤点下的保安员
                                if (!attendanceItem.personList) {
                                  this._passAttendanceIdGetPersonList(1, attendanceItem.id, index, attenIndex)
                                }
                                this.switchOpenStatus([index, attenIndex])
                              }}>
                                <span className={styles.ellipsis} style={{ width: 240 - 15 }} style={{ color: attendanceItem.open ? '#0E70FF' : '' }}>{attendanceItem.attendanceSitename}</span>
                                <Icon className={styles.icon} type={attendanceItem.open ? 'up' : 'down'} style={{ color: attendanceItem.open ? '#0E70FF' : mapStyle == 'dark' ? '#fff' : '' }} />
                              </div>
                              {/* 部门的部门节点，以及部门下的保安人员节点 */}
                              <div>
                                {
                                  attendanceItem.open && this._renderDepartAndPerson(attendanceItem.personList, [index, attenIndex])
                                }
                              </div>
                            </div>
                          )
                        })
                      }
                    </div>
                  }
                </div>
              </div>
            }) : <span className={styles.detail}>暂无数据...</span>
          }
        </div>
      </div>
    );
  }
}
