/**
 * 一张图数据展示
 * 此页面用于一张图以及警保联动
 * param：layerSatatus
 * 如果没有此layerSatatus参数，需要正常显示所有功能
 */
import React, { Component } from "react";
import { Checkbox, Row, Col } from 'antd';
import { getClassification, attendanceGetTypeData, perceptionGetTypeData, getSecurityResourcesList,getSecurityCompanyList, getDomainList } from '@services/api';
import styles from "./index.less";
import { connect } from "dva";
import eventCenter from "@common/events";
const store = require('store');
import { recordAdd, recordRemove } from '@common/recordHistory';
import { getCompanyList } from '@gis/biz';
import CityCascader from '@gis/components/CityCascader';
import { data as typeData } from "@constants/TypeData";

@connect((state) => ({
  //地图数据
  pictureMarkersList: state.command.pictureMarkersList,
  mapStyle: state.command.mapStyle,
  layoutAuthority: state.command.layoutAuthority,
}))
export default class APictureData extends Component {
  constructor(props) {
    super(props);
    this.state = {
      securityResource: {//保安资源
        typeList: [],//列表数据
        checkdata: [],//上一次选中的复选框
      },
      securityCompanyData: {//保安公司资源
        typeList: [],//列表数据
        checkdata: [],//上一次选中的复选框
      },
      perception: {//态势感知
        typeList: [],//列表数据
        checkdata: [],//上一次选中的复选框
      },
      attendance: {//驻勤点
        typeList: [],//列表数据
        checkdata: [],//上一次选中的复选框
      },
      //一张图所有数据
      pictureList: {
        //保安资源的数据
        //态势感知的数据
        perception: [],
        //驻勤点的数据
        attendance: [],
      },
      // height: null, //保安员资源列表的最大高度
      allHeight: null,
      hasOneCompany: false, // 根据需求 460, 接口处拿到的保安公司只有一家企业时，就需要在隐藏保安公司入口
      securityResourceChecked: false,
      securityCompanyChecked: false
    };
  }
  componentDidMount() {
    const allHeight = document.documentElement.clientHeight - 9 - 340 - 46 - 16;
    const that = this;
    this.setState({ allHeight });
    //默认情况下需加载所有数据
    this.getSecurityCompanyList();
    if (!this.props.layerSatatus) {
      this.getSecurityResourcesList()
    }
    this.getClassification()
    this.props.dispatch({
      type: 'command/setSelectComponyList',
      payload:  []
    })
    eventCenter.addListener('showAPictureData', (result)=>{
      console.log('showAPictureData', result);
      that.propsOption('add', {
        data: result.typeList,
      }, result.type)
      // TAG: 根据需求 368, 勾选保安服务公司时，打开公司列表浮层
      if (result.type == 'securityCompany') {
        that.props.dispatch({
          type: 'command/setSelectComponyList',
          payload:  result.typeList
        })
        let selectComponyList = JSON.parse(JSON.stringify(result.typeList)) // 解引用
        let param = {
          from : 'componyList',
          data : selectComponyList
        };
        recordAdd({
          from: 'APictureData',
          to: 'CreateComponeyInfoWindow',
          fromData: result.typeList,
          toID: result.type
        });
      } else {
        recordAdd({
          from: 'APictureData',
          to: 'CreateTrajectoryInfoWindow',
          fromData: result.typeList,
          toID: result.type
        });
      }
      if (result.type == 'securityCompany') {
        that.setState({
          securityCompanyChecked: true
        })
      } else {
        that.setState({
          securityResourceChecked: true
        })
      }
    })

    eventCenter.addListener('APictureChecked', (result)=>{
      let json = {};
      json[result.type] = result.checked;
      that.setState(json)
    })
  }
  //获取保安员列表数据
  getSecurityResourcesList(_currpage = 1) {
    getSecurityResourcesList({
      _currpage,
      lines: 1000
    }, {
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__FBwWBm18eyoRndv9tIP",
      opentarget: "detail",
      containTitle: "保安资源接口",
    }).then(res => {
      let typeList = []
      if (res.data.data.length > 0) {
        let data = res.data.data
        data.forEach((element, index) => {
          let location = element.location && JSON.parse(element.location)
          // location = {longitude:"118.051982",latitude:"24.607542"}
          if (location) {
            data[index].longitude = location.longitude || ''
            data[index].latitude = location.latitude || ''
            data[index].time = location.time || ''
          }
          data[index].name = element.securityName
          data[index].mobilePhone = element.phone
        });
        typeList = this.state.securityResource.typeList.concat(res.data.data)
        this.setState({
          securityResource: {
            ...this.state.securityResource,
            typeList
          }
        })
      }
      //如果没有加载完，需要再一次加载
      let { pageNumber, pageSize, total } = res.data
      if (total > pageNumber * pageSize) {
        this.getSecurityResourcesList(_currpage + 1)
      } else {
        this.props.dispatch({
          type: "command/setSecurityResourceData",
          payload: {
            dataList: typeList
          },
        });
      }
    })
  }
  // 获取保安公司列表
  getSecurityCompanyList=()=>{
    let typeList = []
    const that = this;
    getCompanyList({
      hasMark: false,
      success:function(res){
        if (res.length == 1) {
          return that.setState({
            hasOneCompany: true
          })
        }
        typeList = that.state.securityCompanyData.typeList.concat(res)
        that.setState({
          securityCompanyData: {
            ...that.state.securityCompanyData,
            typeList
          }
        })
      }
    })
  }
  //获取驻勤点/现场态势分类（目前最长20）
  getClassification() {
    if (!this.props.layerSatatus) {
      //现场态势
      getClassification({
        _currpage: 1,
        lines: 20
      }, {
        appId: "__ZLuP7RGirprZZ6SCdiX",
        viewId: "__yhhLbXvCrdnsejsjY8G",
        opentarget: "detail",
        containTitle: "分类列表",
        categoryParentName: "现场态势",
      }).then(res => {
        let data = res.data.data
        data = data.map((item) => {
          return {
            ...item,
            iconSrc: item.iconSrc && JSON.parse(item.iconSrc)[0] && JSON.parse(item.iconSrc)[0].path,
            mapIcon: item.MAPICON && JSON.parse(item.MAPICON)[0] && JSON.parse(item.MAPICON)[0].path,
            darkIconSrc: item.darkIconSrc && JSON.parse(item.darkIconSrc)[0] && JSON.parse(item.darkIconSrc)[0].path,
          }
        })
        this.setState({
          perception: {
            ...this.state.perception,
            typeList: data
          }
        })
      })
    }
    //驻勤点
    getClassification({
      _currpage: 1,
      lines: 20
    }, {
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__yhhLbXvCrdnsejsjY8G",
      opentarget: "detail",
      containTitle: "分类列表",
      categoryParentName: "驻勤点",
    }).then(res => {
      let data = res.data.data
      data = data.map((item) => {
        return {
          ...item,
          iconSrc: item.iconSrc && JSON.parse(item.iconSrc)[0] && JSON.parse(item.iconSrc)[0].path,
          mapIcon: item.MAPICON && JSON.parse(item.MAPICON)[0] && JSON.parse(item.MAPICON)[0].path,
          darkIconSrc: item.darkIconSrc && JSON.parse(item.darkIconSrc)[0] && JSON.parse(item.darkIconSrc)[0].path,
        }
      })
      this.setState({
        attendance: {
          ...this.state.perception,
          typeList: data
        }
      })
    })
  }
  //态势感知根据分类获取分类数据
  perceptionGetTypeData(_currpage = 1, categoryName, optionType, mapIcon) {
    perceptionGetTypeData({
      _currpage,
      lines: 100
    }, {
      categoryName,
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__gnF6tfEwBQwo6IrdMrK",
      opentarget: "detail",
      containTitle: "现场态势接口",
    }).then(res => {
      let data = this.state.pictureList.perception
      let index = data.findIndex((item) => {
        return item.name === categoryName
      })
      if (index > -1) {
        res.data.data.length > 0 ? data[index].data.push(res.data.data) : ''
      } else {
        data.push({
          name: categoryName,
          data: res.data.data,
        })
      }
      this.setState({
        pictureList: {
          ...this.state.pictureList,
          perception: data
        }
      }, () => {
        this.propsOption(optionType, {
          name: categoryName,
          data: res.data.data,
          mapIcon
        }, 'perception')
      })
      //如果没有加载完，需要再一次加载
      let { pageNumber, pageSize, total } = res.data
      if (total > pageNumber * pageSize) {
        this.perceptionGetTypeData(_currpage + 1, categoryName, optionType, mapIcon)
      }
    })
  }
  //驻勤点根据分类获取分类数据
  attendanceGetTypeData(_currpage = 1, categoryName, optionType, mapIcon) {
    attendanceGetTypeData({
      _currpage: 1,
      lines: 20
    }, {
      categoryName,
      appId: "__ZLuP7RGirprZZ6SCdiX",
      viewId: "__YxVuFY8k0tZjSoJWNS4",
      opentarget: "detail",
      containTitle: "驻勤点接口",
    }).then(res => {
      let data = this.state.pictureList.attendance
      let index = data.findIndex((item) => {
        return item.name === categoryName
      })

      let result = [];
      res.data.data.map((item)=>{
        // 对数据字段重新组装
        let rJson = item;
        rJson.selectAttendId = item.id
        rJson.attendName = item.ATTENDANCESITENAME
        // rJson.componey = item.companyName,
        rJson.name = item.PRINCIPALNAME
        rJson.phone = item.PRINCIPALPHONENO
        rJson.address = item.ATTENDANCESITEADDRESS
        rJson.addressDetail = item.ATTENDANCESITEFULLADDRESS
        rJson.scope = item.PERFORMRANGE
        rJson.org = item.OFFICEPOLICEADDRESS
        rJson.obj = item.SERVEOBJECTNAME
        rJson.contract = item.CONTRACTSTATE

        // 如果没有符合的图标，默认设置
        let current = typeData.length - 1;
        typeData.map((e, index)=>{
          if (e.key == item.ATTENDANCESITETYPE) {
            current = index;
          }
        })
        rJson.markerIcon = typeData[current].markerIcon;
        rJson.clickMarkerIcon = typeData[current].clickMarkerIcon;

        result.push(rJson);

      })

      if (index > -1) {
        result.length > 0 ? data[index].data.push(result) : ''
      } else {
        data.push({
          name: categoryName,
          data: result,
        })
      }
      this.setState({
        pictureList: {
          ...this.state.pictureList,
          attendance: data
        }
      }, () => {
        this.propsOption(optionType, {
          name: categoryName,
          data: result,
          mapIcon
        }, 'attendance')
      })
      //如果没有加载完，需要再一次加载
      let { pageNumber, pageSize, total } = res.data
      if (total > pageNumber * pageSize) {
        this.attendanceGetTypeData(_currpage + 1, categoryName, optionType, mapIcon)
      }
    })
  }
  // 分类的点击事件
  onChangeList=(dataList, type, e)=>{
    let mapIcon = null
    let currentChecked = null
    let optionType = null //当前的操作类型
    /**
     * 如果当前选中的框长度大于之前的，证明是增加的
     * 反之是取消勾选
     */
    let has = ''
    /////////增加
    if (e.length > this.state[type].checkdata.length) {
      currentChecked = e[e.length - 1].categoryName
      mapIcon = e[e.length - 1].mapIcon
      optionType = 'add'
      switch (type) {
        //保安人员
        case 'securityResource':
          const location = JSON.parse(e[e.length - 1].location)
          this.propsOption(optionType, {
            data: [{
              ...e[e.length - 1],
              name: e[e.length - 1].securityName,
              mobilePhone: e[e.length - 1].phone,
              longitude: location && location.longitude,
              latitude: location && location.latitude,
            }],
            mapIcon: ''
          }, type)
          break;
        default:
          if (dataList.length > 0) {
            has = dataList.find(item => item.name == currentChecked)
          } else {
            has = ''
          }
          /**
          * 如果选中类型的定位数据已有存在，就直接返回值
          * 如果不存在，需要先去获取值，然后在存储
          * 目的：避免重复加载数据
          */
          if (has) {
            this.propsOption(optionType, {
              ...has,
              mapIcon
            }, type)
          } else {
            if (type == 'perception') {
              this.perceptionGetTypeData(1, currentChecked, optionType, mapIcon)
            } else if (type == 'attendance') {
              this.attendanceGetTypeData(1, currentChecked, optionType, mapIcon)
            }
            // 不推荐这种写法，代码可读性极差
            // let apiUrl = type + 'GetTypeData'
            // this[apiUrl](1, currentChecked, optionType, mapIcon)
          }
          break;
      }

    } else {
      /////减少
      let data = this.state[type].checkdata.filter(i1 => !e.find(i2 => i1 == i2))[0];
      currentChecked = data.categoryName
      mapIcon = data.mapIcon
      optionType = 'reduce'
      switch (type) {
        case 'securityResource':
          has = this.props.pictureMarkersList[type].find(item => item.name == data.ID)
          this.propsOption(optionType, {
            ...has,
            mapIcon: ''
          }, type)
          break;
        default:
          has = this.props.pictureMarkersList[type].find(item => item.name == currentChecked)
          this.propsOption(optionType, {
            ...has,
            mapIcon
          }, type)
          break;
      }
    }
    this.setState({
      [type]: {
        ...this.state[type],
        checkdata: e
      }
    });
  }
  /**
   * 渲染分类数据列表
   */
  renderList(dataList, type) {
    console.log('renderList', dataList, type);
    const { mapStyle } = this.props
    this.state[type].typeList = this.state[type].typeList.sort(function(a, b){
      // 升序显示
      return a.categoryName.length - b.categoryName.length
    })
    return (
      <Checkbox.Group onChange={this.onChangeList.bind(this, dataList, type)}>
        <Row>
          {
            this.state[type].typeList.length == 0 ? <div className={styles.detail}>暂无数据...</div> : this.state[type].typeList.map((item, index) => {
              return <span key={item.id + index}>
                {
                  type == 'securityResource' ?
                    <Checkbox value={item}>{item.pirture && <img src={item.pirture} />}<span className={styles.detail}>{item.securityName}</span></Checkbox>
                    : <Checkbox value={item}>
                      {mapStyle == 'dark' ? item.darkIconSrc && <img src={item.darkIconSrc} /> : item.iconSrc && <img src={item.iconSrc} />}
                      <span className={styles.detail}>{item.categoryName}</span></Checkbox>
                }
              </span>
            })
          }
        </Row>
      </Checkbox.Group>
    )
  }
  // 保安资源选择
  onChangeSecRes=(e)=>{
    console.log('onChange', e);
    if (e.target.checked) {
      e = e.target.value
      //增加
      this.propsOption('add', {
        data: e.typeList,
      }, e.type)
      // TAG: 根据需求 368, 勾选保安服务公司时，打开公司列表浮层
      if (e.type == 'securityCompany') {
        this.props.dispatch({
          type: 'command/setSelectComponyList',
          payload:  e.typeList
        })
        let selectComponyList = JSON.parse(JSON.stringify(e.typeList)) // 解引用
        let param = {
          from : 'componyList',
          data : selectComponyList
        };
        recordAdd({
          from: 'APictureData',
          to: 'CreateComponeyInfoWindow',
          fromData: e.typeList,
          toID: e.type
        });
      } else {
        recordAdd({
          from: 'APictureData',
          to: 'CreateTrajectoryInfoWindow',
          fromData: e.typeList,
          toID: e.type
        });
      }
      if (e.type == 'securityCompany') {
        this.setState({
          securityCompanyChecked: true
        })
      } else {
        this.setState({
          securityResourceChecked: true
        })
      }
    } else {
      e = e.target.value
      //减少
      let markSecurityResource = this.props.pictureMarkersList.securityResource
      if (markSecurityResource.length > 0) {
        this.propsOption('reduce', {
          data: markSecurityResource[0].data,
        }, e.type)
      }
      recordRemove({
        from: 'APictureData',
        toID: e.type
      })
      if (e.type == 'securityCompany') {
        this.setState({
          securityCompanyChecked: false
        })
        this.state.securityCompanyChecked = false;
        this.props.dispatch({
          type: 'command/setSelectAttendInfo',
          payload: {}
        })
        // 清除公司标记
        this.props.dispatch({
          type: 'command/setSelectComponyList',
          payload:  []
        })
        eventCenter.emit('clearMapModal', 'ComponeyInfo');
        eventCenter.emit('clearMapTag', 'securityCompany');
      } else {
        // 清除地图所有标记
        eventCenter.emit('clearMapModal', 'ComponeyInfo');
        eventCenter.emit('clearMapModal', 'AttendInfo');
        this.setState({
          securityResourceChecked: false
        })
        this.state.securityResourceChecked = false;
      }

      // TAG: 没有任何勾选时，则返回至最初的GIS地图页面
      if (!this.state.securityCompanyChecked && !this.state.securityResourceChecked) {
        let point = store.get('userPosition')
        console.log('userPosition', point);
        eventCenter.emit('gotoPosition', point);
      }
    }
  }

  /**
   * 渲染保安资源
   */
  renderSecResList() {
    const { hasOneCompany, securityResource, securityCompanyData, securityCompanyChecked, securityResourceChecked } = this.state;
    return (
      // <Checkbox.Group onChange={this.onChangeSecRes}>
        <Row>
          {
            securityResource.typeList.length == 0 ? <div className={styles.detail}>暂无数据...</div> :
              <div>
                <Checkbox checked={securityResourceChecked} value={{typeList: securityResource.typeList, type:'securityResource'}}  onChange={this.onChangeSecRes}>
                  <div style={{ padding: '0 8px 0 5px', display: 'inline' }} className={styles.detail}>
                    保安员
                  </div>
                </Checkbox>
                {
                  ! hasOneCompany ?
                  <Checkbox checked={securityCompanyChecked}  value={{typeList: securityCompanyData.typeList, type:'securityCompany'}} onChange={this.onChangeSecRes}>
                    <div style={{ padding: '0 8px 0 5px', display: 'inline' }} className={styles.detail}>保安服务公司</div>
                  </Checkbox> : null
                }
              </div>
          }
        </Row>
      // </Checkbox.Group>
    )
  }
  /**
   * 向上级传递打点数据
   * @param {*} optionType
   * @param {*} data
   * @param {*} type
   */
  propsOption(optionType, data, type) {
    console.log('propsOption', optionType, data, type);
    switch (optionType) {
      case 'add':
        // event 发送器: eventCenter.emit("事件名称", 参数列表);
        // 这样做的好处是，爷传孙，不需要父级组件做承载
        eventCenter.emit('addPictueMarks', {
          data,
          type
        });
        // this.props.addPictueMarks(data, type);
        break;
      case 'reduce':
        eventCenter.emit('reducePictueMarks', {
          data,
          type
        })
        // this.props.reducePictueMarks(data, type);
        break;
    }
  }
  render() {
    const { layerSatatus, mapStyle, layoutAuthority } = this.props
    return (
      <div className={styles[mapStyle]}>
        <div className={styles.apicture}>
          <div className={styles.title}>
            一张图数据展示
            {/* <img src={mapStyle == 'dark' ?
              require('../../../../assets/images/prevention/aPicture/setting-click.png') :
              require('../../../../assets/images/prevention/aPicture/setting.png')}
            /> */}
          </div>
          <div className={styles.content} style={{ height: this.state.allHeight, overflow: "auto" }}>
            {/* <div>
              <h1><img src={require('@assets/images/prevention/area-selection.png')} />区域选择</h1>
              <div className={styles.item}>
                <CityCascader onChange={this.onChangeCity.bind(this)} />
              </div>
            </div>
            <div className={styles.borderline}></div> */}
            {
              layoutAuthority.peoplePermissions ? <div>
                <h1><img src={require('@assets/images/prevention/aPicture/security.png')} />保安资源</h1>
                <div className={styles.item}>
                  {
                    this.renderSecResList()
                  }
                </div>
              </div> : ''
            }
            <div className={styles.borderline}></div>
            {
              layoutAuthority.hardWarePermissions ? <div>
                <h1><img src={require('@assets/images/prevention/aPicture/perception.png')} />态势感知</h1>
                <div className={styles.item}>
                  {
                    this.renderList(this.state.pictureList.perception, 'perception')
                  }
                </div>
              </div> : ''
            }
            <div className={styles.borderline}></div>
            {
              layoutAuthority.attendancePermissions ? <div>
                <h1><img src={require('@assets/images/prevention/aPicture/attendance.png')} />驻勤点</h1>
                <div className={styles.item}>
                  {
                    this.renderList(this.state.pictureList.attendance, 'attendance')
                  }
                </div>
              </div> : ''
            }
          </div>
        </div>
      </div>
    );
  }
}
