/**
 * 综合查询功能
 */
import React, { Component } from "react";
import { Input, Space, Pagination, Modal } from 'antd';
import { getPersonList, getDomainInfo, getDomainList, getAttendance, attendanceGetTypeData } from '@services/api';
import styles from "./index.less";
import { connect } from "dva";
import eventCenter from "@common/events";
import PersonItem from "../SearchListTab/PersonMessage/PersonItem";
import classNames from 'classnames';
import ComponyItem from '@gis/components/ComponyItem';
import { isEmpty } from '@utils/utils';
import $modal from '@utils/modal';
import AttendanceItem from '@gis/components/AttendanceItem';
import { recordAdd, recordBack, recordRemove } from '@common/recordHistory';
import packUpImg from '@assets/images/prevention/pack-up.png';
import packDownImg from '@assets/images/prevention/pack-down.png';
import { getCompanyList, showAttendList, showCompanyPointInfo } from '@gis/biz';


const SEARCH_TABS = [{
  'name': '搜公司',
  'icon': require('@assets/images/prevention/security-company.png'),
  'type': 'company'
},{
  'name': '保安员',
  'icon': require('@assets/images/prevention/security-personnel.png'),
  'type': 'personnel'
},{
  'name': '驻勤点',
  'icon': require('@assets/images/prevention/attendance-points.png'),
  'type': 'points'
},{
  'name': '搜地址',
  'icon': require('@assets/images/prevention/search-address.png'),
  'type': 'address'
}];

@connect((state) => ({
  //地图数据
  mapStyle: state.command.mapStyle,
  pictureMarkersList: state.command.pictureMarkersList
}))
export default class ComprehensiveSearch extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowType: false,
      searchType: 'address',
      dataSource: [],
      searchValue: '',
      addressID: 'comprehensive_search_address'
    };
    this.pageSize = 10;
    this.pageNumber = 1;
    this.initSearch = true;
    this.placeSearch = '';
  }
  componentDidMount() {
    this.initAutocomplete();
    const that = this;
    eventCenter.addListener('showComprehensiveSearch', (result)=>{
      setTimeout(()=>{
        that.initSearch = false;
        if (result.type == 'address') {
          eventCenter.emit('addPictueMarks', {
            data: {
              data: result.data,
            },
            type: 'searchAddress'
          });
        } else {
          that.setState({
            dataSource: result.data,
            searchType: result.type
          });
        }
      }, 2000)
    });
  }
  onSearchInput=(e)=>{
    console.log('Change:', e.target.value);
    this.setState({
      searchValue: e.target.value
    })
  }
  onSearch=()=>{
    const { searchValue } = this.state;
    if (isEmpty(searchValue)) {
      // return $modal('请输入内容');
      return;
    }
    eventCenter.emit('clearMapTag');
    // 初始化右侧数据模块
    eventCenter.emit('initRightDataModule');
    eventCenter.emit('clearMapModal', 'ComponeyInfo');
    eventCenter.emit('clearMapModal', 'AttendInfo');
    console.log('onSearch', searchValue);
    const keyWord = searchValue;
    const { searchType } = this.state;
    switch (searchType) {
      case 'company':
        this._getSecurityCompanyList(keyWord);
        break;
      case 'personnel':
        this._getPersonList(keyWord);
        break;
      case 'points':
        this._getAttendance(keyWord);
        break;
    }
  }
  // 获取驻勤点列表
  _getAttendance=(keyWord)=>{
    const that = this;
    showAttendList({
      keyWord: keyWord,
      success: function(data){
        if(data.length > 0){
          that.setState({
            dataSource: data,
          });
          recordAdd({
            from: 'ComprehensiveSearch',
            to: 'AttendInfo',
            fromData: data,
            toID: 'points'
          });
        } else {
          Modal.warning({
            title: '在数据权限范围内，无对应的搜索内容！',
            okText: '我知道了'
          });
        }

        // let param = {
        //   from : 'search',
        //   isTop: true,
        //   type : 'attendance',
        //   data : data
        // };
        // that.props.dispatch({
        //   type: "command/changeBackStepInfo",
        //   payload: param,
        // });
      }
    })
  }
  // 获取保安公司列表
  _getSecurityCompanyList=(keyWord)=>{
    const that = this;
    getCompanyList({
      keyWord,
      success: function(data){
        if (data.length > 0) {
          that.setState({
            dataSource: data,
          });
          recordAdd({
            from: 'ComprehensiveSearch',
            to: 'CreateComponeyInfoWindow',
            fromData: data,
            toID: 'company'
          });
        } else {
          Modal.warning({
            title: '在数据权限范围内，无对应的搜索内容！',
            okText: '我知道了'
          });
        }

        // let param = {
        //   from : 'search',
        //   isTop: true,
        //   type : 'compony',
        //   data : datas
        // };
        // this.props.dispatch({
        //   type: "command/changeBackStepInfo",
        //   payload: param,
        // });
      }
    })
  }
  // 获取保安人员列表
  _getPersonList(keyWord){
    getPersonList({
      _currpage:this.pageNumber,
      lines:this.pageSize,
    },{
      search_smName: keyWord
    }).then(res=>{
      console.log(res)
      if(res.data.total == 0 || res.data.data.length == 0){
        return Modal.warning({
          title: '在数据权限范围内，无对应的搜索内容！',
          okText: '我知道了'
        });
      }
      let result = res.data.data.map((item) => {
        item.perId = item.id
        delete item.id
        item.name = item.securityName ? item.securityName : item.principalName
        delete item.securityName
        delete item.principalName
        let lnglatData =item.location? JSON.parse(item.location):''
        if (lnglatData) {
          item.lnglat =lnglatData? [lnglatData.longitude,lnglatData.latitude]:''
          item.longitude = lnglatData.longitude;
          item.latitude = lnglatData.latitude;
          item.time = '';
        }
        // item.lnglat = [118.051982,24.607542]
        delete item.location
        item.idCardNo = item.documentID ? item.documentID : item.principalIdCardNo
        delete item.documentID
        delete item.principalIdCardNo
        item.mobilePhone = item.phone ? item.phone : item.principalPhoneNo
        delete item.phone
        delete item.principalPhoneNo
        return item
      })
      this.props.dispatch({
        type: "command/setPersonSelectIndex",
        payload: null,
      });
      this.props.dispatch({
        type: "command/clearInfoWindow",
        payload: true,
      });
      this.setState({
        dataSource: result,
        total: res.data.total,
        loadingText: result.length > 0 ? "加载完成" : "暂无数据",
      });
      recordAdd({
        from: 'ComprehensiveSearch',
        to: 'CreateTrajectoryInfoWindow',
        fromData: result,
        toID: 'person'
      });
      console.log(result)
      this.props.dispatch({
        type: "command/fetchPersonList",
        payload: {
          list: result,
        },
      });
      console.log('securityResource', result);
      eventCenter.emit('addPictueMarks', {
        data: {
          data: result,
        },
        type: 'securityResource'
      });
      let param = {
        from : 'search',
        isTop: true,
        type : 'person',
        data : result
      };
      this.props.dispatch({
        type: "command/changeBackStepInfo",
        payload: param,
      });
    })
  }
  onShowType=(status)=>{
    console.log('onShowType', status);
    if (!this.initSearch && status != 'refresh') {
      return;
    }
    this.initSearch = false;
    this.setState({
      isShowType: !this.state.isShowType
    });
  }
  initAutocomplete=()=>{
    const that = this;
    that.placeSearch = null;
    var map = this.props._thisGIS.state.map;

    AMap.plugin('AMap.Autocomplete', function(){
      var auto = new AMap.Autocomplete({
        input: that.state.addressID,
        output: that.state.addressID + "_list"
      });
      that.placeSearch = new AMap.PlaceSearch({
        map: map,
        type: '汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施',
        extensions: 'all'
      });
      AMap.event.addListener(auto, "select", (e)=>{
        console.log('onAutoSelect', e);
        that.placeSearch.setCity(e.poi.adcode);
        that.placeSearch.search(e.poi.name, (status, result) => {
          eventCenter.emit('clearMapTag', 'searchAddress');
          // 搜索成功时，result即是对应的匹配数据
          if (status === "complete" && result.poiList.count > 0) {
            let pois = result.poiList.pois
            let markerData = [];
            for (const key in pois) {
              let poi = pois[key];
              console.log('placeSearch-poi', poi);
              let info = {
                latitude: poi.location.lat,
                longitude: poi.location.lng,
                address: poi.pname + poi.cityname + poi.adname + poi.address,
                phone: poi.tel,
                id: poi.id,
                name: poi.name
              }
              markerData.push(info);
            }
            if (that.placeSearch.render && that.placeSearch.render.markerList) {
              that.placeSearch.render.markerList.clear();
            }
            setTimeout(()=>{
              eventCenter.emit('addPictueMarks', {
                data: {
                  data: markerData,
                },
                type: 'searchAddress'
              });
              recordAdd({
                from: 'ComprehensiveSearch',
                to: 'Search',
                fromData: markerData,
                toID: 'address'
              });
            }, 700)
          }
        });  //关键字查询查询
      })
    })
  }
  onChangeType=(searchType)=>{
    // 清除搜索结果的标记
    if (this.placeSearch.render) {
      this.placeSearch.render.markerList.clear();
    }
    this.setState({
      searchType,
      searchValue: '',
      dataSource: [],
      isShowType: false
    })
    eventCenter.emit('clearMapTag');
    switch (searchType) {
      // case 'company':
      //   this._getSecurityCompanyList("");
      //   break;
      // case 'personnel':
      //   this._getPersonList("");
      //   break;
      // case 'points':
      //   this._getAttendance("");
      //   break;
      case 'address':
        this.initAutocomplete();
        break;
    }
  }
  onChangeAttendance=(item)=>{
    console.log('onChangeAttendance');
    this.props.dispatch({
      type: 'command/setSelectAttendInfo',
      payload: {}
    })
    let param = item
    eventCenter.emit('initRightDataModule');
    eventCenter.emit('addPictueMarks', {
      data: {
        data: [param],
      },
      type: 'attendancePoint'
    });
    this.props.dispatch({
      type: 'command/setSelectComponeyInfo',
      payload: {}
    })
    this.setState({
      searchValue: item.taskName
    });
  }
  onChangeCompony(item){
    const that = this.that;
    console.log('onChangeCompony', that);
    showCompanyPointInfo({
      doMainId: item.selectComponeyId,
      success: function(info){
        let data = { data: [info] };
        // TAG: 根据需求 368。点击打开公司办公地点定位，并打开公司信息弹框
        // event 发送器: eventCenter.emit("事件名称", 参数列表);
        // 这样做的好处是，爷传孙，不需要父级组件做承载
        eventCenter.emit('addPictueMarks', {
          data,
          type: "securityCompany"
        });

        that.setState({
          searchValue: info.companyName
        });
      }
    })
  }
  onChangePerson=(item)=>{
    console.log('onChangePerson', item);
    const that = this;
    that.setState({
      searchValue: item.name
    })
  }
  render() {
    const { layerSatatus, mapStyle, layoutAuthority } = this.props
    const { isShowType, dataSource, searchHeight, loadingText, total, searchType, searchValue, addressID } = this.state;
    const clsSearch = classNames(styles[`${searchType}_list`]);
    const searchNames = SEARCH_TABS.filter(item => item.type == searchType);
    const searchName = (!isEmpty(searchNames[0]['name'])?searchNames[0]['name']: "")
    console.log('ComprehensiveSearch-state', this.state, searchNames);
    return (
      <div className={styles[mapStyle]}>
        <div className={styles.search_content}>
          <div className={styles.search_input} onClick={this.onShowType.bind(this)}>
            {
              !this.initSearch ? <div className={styles.search_name} onClick={this.onShowType.bind(this, 'refresh')}>
                {searchName}
                <img className={styles.search_icon} src={ isShowType ? packUpImg : packDownImg } />
              </div> : null
            }
            {
              searchType == 'address' ?
              <Input
                bordered={false}
                allowClear={true}
                className={styles.input_i}
                id={addressID}
                autoComplete={false}
                autoComplete={"off"}
                onChange={this.onSearchInput}
                onPressEnter={this.onSearch}
                value={searchValue}
              />: <Input
                style={{ display: "none" }}
                bordered={false}
                allowClear={true}
                className={styles.input_i}
                id={addressID}
                autoComplete={false}
                autoComplete={"off"}
                onChange={this.onSearchInput}
                onPressEnter={this.onSearch}
                value={searchValue}
              />
            }
            {
              searchType != 'address' ?
              <Input
                bordered={false}
                allowClear={true}
                className={styles.input_i}
                id="comprehensive_search"
                autoComplete={false}
                autoComplete={"off"}
                onChange={this.onSearchInput}
                onPressEnter={this.onSearch}
                value={searchValue}
              /> : null
            }
            <div className={styles.search_btn} onClick={this.onSearch}>搜索</div>
          </div>
          { isShowType ? <div className={styles.type_body}>
            {
              SEARCH_TABS.map((e)=>{
                const clsName = classNames(styles.type_item, e.type == searchType ? styles.item_checked : '');
                return <div className={clsName} onClick={this.onChangeType.bind(this, e.type)}>
                  <img className={styles.type_img} src={e.icon}  />
                  <div className={styles.type_name}>{e.name}</div>
                </div>
              })
            }
          </div> : null}
          {
            searchType == 'address' ? <div class="address_list" id={addressID + "_list"}></div> : <div style={{ display: "none" }} class="address_list" id={addressID + "_list"}></div>
          }
          {dataSource.length > 0 ? <div className={clsSearch}>
            {
              searchType == 'personnel' ?
              <div
                class="search-list_command search-list"
                style={{ maxHeight: searchHeight, overflow: "auto" }}
                id="personnel_list"
              >
                <PersonItem
                  data={dataSource}
                  onClick={this.onChangePerson}
                  loadingText={loadingText}
                />
                <Pagination
                  total={total}
                  size="small"
                  onChange={(pageNumber) => {
                    this._getPersonList(pageNumber);
                  }}
                  defaultPageSize={this.pageSize}
                  current={this.pageNumber}
                  style={{
                    display:
                      total > this.pageSize
                        ? "block"
                        : "none",
                    textAlign: 'center'
                  }}
                />
              </div> : null
            }
            {
              searchType == 'company' ?
              <div className={styles.list_content}>
                {dataSource && dataSource.map((item, i)=>{
                  return <ComponyItem item={item} that={this} onChangeCompony={this.onChangeCompony} />
                })}
              </div> : null
            }
            {
              searchType == 'points' ?
              <div className={styles.list_content}>
                {dataSource && dataSource.map((item, i)=>{
                  return <AttendanceItem item={item} onChangeAttendance={this.onChangeAttendance} />
                })}
              </div> : null
            }
          </div> : null}
        </div>
      </div>
    );
  }
}
