/**
 * 搜索周边的功能
 */
import React, { Component } from "react";
import { connect } from "dva";
import styles from './index.less';
import { Input, Checkbox, Row, Col, Button, message } from 'antd';
import { getSearchInformation,getPoliceSearchInformation, getRangeData } from '@services/api';
import eventCenter from "@common/events"; // 引入 EventEmitter
import { recordAdd, recordBack, recordRemove, recordTo } from '@common/recordHistory';

@connect((state) => ({
  searchAround: state.command.searchAround,
}))
export default class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      range: 400,
      checkdata: [],
      securityManData: {
        data: []
      },//搜索出来的保安员数据
      situationData: [],//动态感知的数据
      circle: null
    };
  }
  componentDidMount() {
    this._onChangeRange()
    const that = this;
    // 清除周边搜索弹框 & 画的圈
    eventCenter.addListener('clearSearchCircle', (result)=>{
      that.clearAll();
      that.props.onClose && that.props.onClose(false)
    })
  }
  onChange(e) {
    eventCenter.emit('clearMapTag', 'searchAddress');
    let checkId = null
    if (e.length > this.state.checkdata.length) {
      //增加
      checkId = e[e.length - 1]
      switch (checkId) {
        case 'A':
          if (this.state.securityManData.data.length > 0) {
            // this.props.addPictueMarks(this.state.securityManData, 'securityResource', {
            //   where: 'searchAround',
            //   type: 'A'
            // });
            eventCenter.emit('addPictueMarks', {
              data: this.state.securityManData,
              type: 'securityResource',
              where: {
                where: 'searchAround',
                type: 'securitySearch'
              }
            });
          } else {
            message.warning("保安员暂无数据...")
          }
          break;
        case "B":
          if (this.state.situationData.length > 0) {
            this.state.situationData.map(item => {
              console.log(item)
              // this.props.addPictueMarks(item, 'perception', {
              //   where: 'searchAround',
              //   type: 'B'
              // });
              eventCenter.emit('addPictueMarks', {
                data: item,
                type: 'perception',
                where: {
                  where: 'searchAround',
                  type: 'awarenessSearch'
                }
              });
            })
          } else {
            message.warning("动态感知设备暂无数据...")
          }
          break;
      }
    } else {
      //减少
      checkId = this.state.checkdata.filter(i1 => !e.find(i2 => i1 == i2))[0]
      const { searchAround } = this.props
      switch (checkId) {
        case 'A':
          if (searchAround.securitySearch.length > 0) {
            let data = {
              data: searchAround.securitySearch
            }
            // this.props.reducePictueMarks(data, 'securityResource', {
            //   where: 'searchAround',
            //   type: 'A'
            // });
            eventCenter.emit('reducePictueMarks', {
              data,
              type: 'securityResource',
              where: {
                where: 'searchAround',
                type: 'securitySearch'
              }
            })
          }
          break;
        case "B":
          if (searchAround.awarenessSearch.length > 0) {
            let data = {
              data: searchAround.awarenessSearch
            }
            eventCenter.emit('reducePictueMarks', {
              data,
              type: 'perception',
              where: {
                where: 'searchAround',
                type: 'awarenessSearch'
              }
            })
            // this.props.reducePictueMarks(data, 'perception', {
            //   where: 'searchAround',
            //   type: 'B'
            // });
          }
          break;
      }
    }
    this.setState({
      checkdata: e
    })
  }
  _onChangeRange() {
    //如果范围改变，要先把之前的点清掉，以避免重复，并且去掉圆圈
    this.clearAll()
    this.aPictureSearch()
    // if(this.props._thisGIS.state.layerSatatus==="aPicture"){
    //   this.aPictureSearch()
    // }else{
    //   this.policeSearch()
    // }
  }
  aPictureSearch() {
    const { lnglat, _thisGIS } = this.props
    console.log(lnglat)
    const { range } = this.state
    getRangeData({},{
      latitude: lnglat.latitude,
      longitude: lnglat.longitude,
      range: this.state.range
    }).then(res => {
      console.log('getRangeData', res);
      //画圈
      var circle = new AMap.Circle({
        center: new AMap.LngLat(lnglat.longitude, lnglat.latitude),  // 圆心位置
        radius: range, // 圆半径
        fillColor: '#0e70ff',   // 圆形填充颜色
        fillOpacity: 0.3, // 圆形填充透明度，取值范围[0,1]，0表示完全透明，1表示不透明。默认为0.9
        strokeColor: '#0E70FF', // 描边颜色
        strokeWeight: 1, // 描边宽度
      });
      this.state.circle && _thisGIS.state.map.remove(this.state.circle);
      _thisGIS.state.map.add(circle);
      // 缩放地图到合适的视野级别
      _thisGIS.state.map.setFitView([circle])
      this.setState({
        circle
      })
      let securityManData = res.data && res.data.securityManData
      let situationData = res.data && res.data.situationData
      if (securityManData.length > 0) {
        securityManData = securityManData.map(item => {
          const location = item.item_lonlatjson && JSON.parse(item.item_lonlatjson)
          return {
            perId: item.item_userid,
            ID: item.item_userid,
            domainid: item.domainid,
            companyName: item.item_companyname,
            ATTENDANCESITENAME: item.item_attendancesitename,
            ATTENDANCESITEID: item.item_attendancesiteid,
            DEPTNAME: item.item_deptname,
            name: item.item_securityname,
            mobilePhone: item.item_phone,
            longitude: (location && location.longitude) || '',
            latitude: (location && location.latitude) || ''
          }
        })
        let data = {}
        data.data = securityManData
        this.setState({
          securityManData: data
        })
        this.props.dispatch({
          type: "command/fetchSearchAroundList",
          payload: {
            list: securityManData,
          },
        });
        if (this.state.checkdata.indexOf("A") > -1) {
          // this.props.addPictueMarks(data, 'securityResource', {
          //   where: 'searchAround',
          //   type: 'A'
          // });
          eventCenter.emit('addPictueMarks', {
            data: data,
            type: 'securityResource',
            where: {
              where: 'searchAround',
              type: 'securitySearch'
            }
          });
        }
      } else {
        if (this.state.checkdata.indexOf("A") > -1) {
          message.warning("保安员暂无数据...")
        }
      }
      let data = {}
      let situationList = []
      if (situationData.length > 0) {
        situationData.map(item => {
          data.name = item.item_categoryname
          data.mapIcon = item.item_categoryicon && JSON.parse(item.item_categoryicon)[0] && JSON.parse(item.item_categoryicon)[0].path
          data.data = [{
            position: item.item_placename,
            userName: item.item_username,
            phone: item.item_phone,
            equipmentName: item.item_equipmentname,
            equipmentId: item.item_equipmentid,
            company: item.item_company,
            type: item.item_type,
            status: item.item_status,
            definition: item.item_definition,
            heightPosition: item.item_heightposition,
            belong: '',//无
            PRINCIPALNAME: '',
            PRINCIPALPHONENO: '',
            ATTENDANCESITENAME: '',
            ATTENDANCESITEADDRESS: '',
            ATTENDANCESITEFULLADDRESS: '',
            PERFORMRANGE: '',
            OFFICEPOLICEADDRESS: '',
            CONTRACTSTATE: '',
            SERVEOBJECTNAME: '',
            ATTENDANCESITECONTENT: '',
            latitude: item.item_latitude,
            longitude: item.item_longitude
          }]
          situationList.push(data)
          if (this.state.checkdata.indexOf("B") > -1) {
            // this.props.addPictueMarks(data, 'perception', {
            //   where: 'searchAround',
            //   type: 'B'
            // });
            eventCenter.emit('addPictueMarks', {
              data: data,
              type: 'perception',
              where: {
                where: 'searchAround',
                type: 'awarenessSearch'
              }
            });
          }
        })
        this.setState({
          situationData: situationList
        })
      } else {
        if (this.state.checkdata.indexOf("B") > -1) {
          message.warning("动态感知设备暂无数据...")
        }
      }
    })
  }
  policeSearch() {
    const { lnglat, _thisGIS } = this.props
    console.log(lnglat)
    const { range } = this.state
    getPoliceSearchInformation({
      _currpage: 1,
      lines: 1
    }, {
      appId: "__ZLuP7RGirprZZ6SCdiX",
      containTitle: "警保联动搜索地点周围信息接口",
      field: "",
      opentarget: "detail",
      position: `{\"latitude\":${lnglat.latitude},\"longitude\":${lnglat.longitude}}`,
      range: `${this.state.range}`,
      viewId: "__alnvhRO3LL5hO0vBgb1",
    }).then(res => {
      console.log(res)
      //画圈
      var circle = new AMap.Circle({
        center: new AMap.LngLat(lnglat.longitude, lnglat.latitude),  // 圆心位置
        radius: range, // 圆半径
        // fillColor: '#0e70ff',   // 圆形填充颜色
        // fillOpacity: 3, // 圆形填充透明度，取值范围[0,1]，0表示完全透明，1表示不透明。默认为0.9
        strokeColor: '#0E70FF', // 描边颜色
        strokeWeight: 1, // 描边宽度
      });
      _thisGIS.state.map.add(circle);
      // 缩放地图到合适的视野级别
      _thisGIS.state.map.setFitView([circle])
      this.setState({
        circle
      })
      let securityManData = res.data.data[0] && JSON.parse(res.data.data[0].securityManData)
      console.log(securityManData)
      let situationData = res.data.data[0] && JSON.parse(res.data.data[0].situationData)
      console.log(situationData)
      if (securityManData.length > 0) {
        securityManData = securityManData.map(item => {
          const location = item.item_lonlatjson && JSON.parse(item.item_lonlatjson)
          return {
            DEPTNAME: item.item_deptname,
            name: item.item_securityname,
            mobilePhone: item.item_phone,
            longitude: (location && location.longitude) || '',
            latitude: (location && location.latitude) || ''
          }
        })
        let data = {}
        data.data = securityManData
        this.setState({
          securityManData: data
        })
        if (this.state.checkdata.indexOf("A") > -1) {
          // this.props.addPictueMarks(data, 'securityResource', {
          //   where: 'searchAround',
          //   type: 'A'
          // });
          eventCenter.emit('addPictueMarks', {
            data: data,
            type: 'securityResource',
            where: {
              where: 'searchAround',
              type: 'securitySearch'
            }
          });
        }
      } else {
        if (this.state.checkdata.indexOf("A") > -1) {
          message.warning("保安员暂无数据...")
        }
      }
      let data = {}
      let situationList = []
      if (situationData.length > 0) {
        situationData.map(item => {
          data.name = item.item_categoryname
          data.mapIcon = item.item_categoryicon && JSON.parse(item.item_categoryicon)[0] && JSON.parse(item.item_categoryicon)[0].path
          data.data = [{
            position: item.item_placename,
            userName: item.item_username,
            phone: item.item_phone,
            equipmentName: item.item_equipmentname,
            equipmentId: item.item_equipmentid,
            company: item.item_company,
            type: item.item_type,
            status: item.item_status,
            definition: item.item_definition,
            heightPosition: item.item_heightposition,
            belong: '',//无
            PRINCIPALNAME: '',
            PRINCIPALPHONENO: '',
            ATTENDANCESITENAME: '',
            ATTENDANCESITEADDRESS: '',
            ATTENDANCESITEFULLADDRESS: '',
            PERFORMRANGE: '',
            OFFICEPOLICEADDRESS: '',
            CONTRACTSTATE: '',
            SERVEOBJECTNAME: '',
            ATTENDANCESITECONTENT: '',
            latitude: item.item_latitude,
            longitude: item.item_longitude
          }]
          situationList.push(data)
          if (this.state.checkdata.indexOf("B") > -1) {
            // this.props.addPictueMarks(data, 'perception', {
            //   where: 'searchAround',
            //   type: 'B'
            // });
            eventCenter.emit('addPictueMarks', {
              data: data,
              type: 'perception',
              where: {
                where: 'searchAround',
                type: 'awarenessSearch'
              }
            });
          }
        })
        this.setState({
          situationData: situationList
        })
      } else {
        if (this.state.checkdata.indexOf("B") > -1) {
          message.warning("动态感知设备暂无数据...")
        }
      }
    }).catch(err=>{
      console.log(err)
    })
  }
  //清掉所有周边搜索打点的值,并且把圆圈去掉
  clearAll() {
    const { searchAround, _thisGIS } = this.props
    const { circle } = this.state
    //先把之前的圆圈去掉
    if (circle) {
      _thisGIS.state.map.remove(circle);
      setTimeout(() => {
        _thisGIS.state.map.remove(circle);
      }, 700);
    }
    if (searchAround.securitySearch.length > 0) {
      // let data = {
      //   data: searchAround.securitySearch
      // }
      // this.props.reducePictueMarks(data, 'securityResource', {
      //   where: 'searchAround',
      //   type: 'A'
      // });
      eventCenter.emit('clearMapTag', 'securitySearch')
      // eventCenter.emit('reducePictueMarks', {
      //   data,
      //   type: 'securityResource',
      //   where: {
      //     where: 'searchAround',
      //     type: 'securitySearch'
      //   }
      // })
    }
    if (searchAround.awarenessSearch.length > 0) {
      // let data = {
      //   data: searchAround.awarenessSearch
      // }
      // this.props.reducePictueMarks(data, 'perception', {
      //   where: 'searchAround',
      //   type: 'B'
      // });
      eventCenter.emit('clearMapTag', 'awarenessSearch')
      // eventCenter.emit('reducePictueMarks', {
      //   data,
      //   type: 'perception',
      //   where: {
      //     where: 'searchAround',
      //     type: 'awarenessSearch'
      //   }
      // })
    }
  }
  onClose=()=>{
    const that = this;
    recordBack({
      from: 'Search',
      callback: (result)=>{
        if(result.from == "ComprehensiveSearch"){
          const data = JSON.parse(JSON.stringify(result));
          recordRemove({
            from: result.from,
            toID: result.toID
          })
          recordTo(data, that);
        }
      }
    });
    this.props.onClose && this.props.onClose(false)
    this.clearAll()
  }
  render() {
    const { range } = this.state
    return (
      <div className={styles.right_click_search}>
        <div><span className={styles.title}>周边搜索</span> <Input style={{ width: '100px' }} addonAfter="米" value={range}
          onChange={(e) => {
            this.setState({ range: e.target.value }, () => {
              this._onChangeRange()
            })
          }} /></div>
        <span className={styles.close} onClick={this.onClose.bind(this)}>x</span>
        <div>
          <Checkbox.Group style={{ width: '100%' }} onChange={(e) => { this.onChange(e) }}>
            <Row>
              <Col span={10}>
                <Checkbox value="A">保安员</Checkbox>
              </Col>
              <Col span={14}>
                <Checkbox value="B">动态感知设备</Checkbox>
              </Col>
            </Row>
          </Checkbox.Group>
        </div>
      </div>
    );
  }
}
