import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { BaseMap, Marker, Polyline, Circle } from 'amos-amap';
import { _picURI, _mapCenter } from './../../../consts/urlConsts';
import imgStatic from './../../../consts/imgStatic';
import mapData from './../../../_mock/mapData';
import { getIcon } from './conf';
import { up } from './conf';
import { utils } from 'amos-tool';
import { outMap } from './../../../consts/urlConsts';
const mapIcon = imgStatic.mapIcon;
const showZoom = 5;

const mapConfig = {
  zoom: showZoom,
  resizeEnable: true,
  zoomEnable: true,
  // plugins: ['Scale', 'MapType', 'OverView', 'ControlBar'],
  plugins: ['Scale'],
  zooms: [showZoom, showZoom],
  expandZoomRange: true,
  doubleClickZoom: false,
  showIndoorMap: false, //隐藏地图自带的室内地图图层
  features: ['bg', 'road', 'point'] //隐藏默认楼块
};

const layers = [
  new window.AMap.TileLayer({
    getTileUrl(x, y, z) {
      return `${_picURI}china/amap/${z}/${x}/${y}.png`;
    },
    zIndex: 0
  })
];

const statusEnum = { '2': '告警', '3': '高风险' };


/**
 * 地图首页
 *
 * @class BasicMap
 * @extends {Basic}
 */
class BasicMap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mapCenter: _mapCenter,
      lineStyle: { strokeColor: '#1B950D', fillColor: '#1B950D', strokeWeight: '2' },
      alarmList: [],
      visible: false,
      selectData: {}
    };
  }

  componentDidMount(){
    this.initData();
  }

  initData = () => {
    let temp = [];
    mapData.map(item => {
      if (item.status !== 1){
        temp.push(item);
      }
    });
    temp.reverse(up);
    this.setState({
      alarmList: temp
    });
  }

  initMap = () => {
    window.map.on('click', function(e) {
      document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
    });
  };

  onClick = (e) =>{
    let visibleList = e.aliasName;
    let num = 0;
    let temp = {};
    mapData.map(item => {
      if (visibleList.includes(item.name)){
        num = num + 1;
        item.title = true;
        if (num === 1 ){
          temp = item;
        }
      } else {
        item.title = false;
      }
    });
    this.setState({
      visible: true,
      selectData: temp
    });
    setTimeout(()=>{
      this.setState({
        visible: false
      });
    },500);
  }

  renderAliasLine = (e) => {
    let { selectData } = this.state;
    let divStyle = {
      marginTop: '-11px',
      transform: `rotate(${selectData.gradient}deg)`
    };

    if (selectData.gradient <= 0){
      divStyle.marginTop = '-50px';
    }
    if (selectData.position === 'right'){
      divStyle.right = '0px';
    }

    if (selectData.pathName){
      return (
        <Marker key={selectData.id} zIndex={1} position={{ longitude: selectData.lng, latitude: selectData.lat }}>
          <div className={`content-alias`} style={divStyle}>
            <img src={mapIcon.alias_line} style={{ width: `${selectData.width}px`, height: `${selectData.height}px` }}></img>
            <img src={mapIcon.alias_title} className='alias-title'></img>
            <span style={{ width: `${selectData.width}px` }}>{selectData.pathName}</span>
          </div>
        </Marker>
      );
    }
  }

  /**
   * 设置末端marker
   *
   * @memberof BasicMap
   */
  setBodyMarker = () => {
    let { aliasName } = this.state;
    return (mapData || []).map((item, index) => {
      if (item.type === 'center') {
        return (<Marker key={item.id} zIndex={1} position={{ longitude: item.lng, latitude: item.lat }}>
          <div className={`marker-center`}>
            <div className='title'>
              <span>{item.name}</span>
              <img src={mapIcon.endmost_title_2} />
            </div>
            <img src={getIcon(item.type, item.status)}></img>
          </div>
        </Marker>);
      } else {
        return (<Marker key={item.id} zIndex={1} position={{ longitude: item.lng, latitude: item.lat }}>
          <div className={`marker-icon`}>
            { item.title && <div className='title'>
              <span>{item.name}</span>
              <img src={getIcon(item.type, 'title_' + item.status)} />
            </div>}
            <img src={getIcon(item.type, item.status)} onClick={() => this.onClick(item)}></img>
          </div>
        </Marker>);
      }
    });
  };

  /**
   * 设置连线
   *
   * @memberof BasicMap
   */
  setBodyLine = () => {
    let { lineStyle } = this.state;
    return (mapData || []).map((item, index) => {
      if (item) {
        return ( <Polyline
          key={item.id}
          zIndex={11}
          path={item.path}
          style={lineStyle}
          extData={item}
        />);
      }
    });
  };

  buildAlarm = () => {
    let { alarmList } = this.state;
    return (alarmList || []).map((item, index) => {
      if (item) {
        return (<div className={`row-${item.status}`} key={index}>
          <span>{item.name}</span>
          <span className='right'>{statusEnum[item.status]}</span>
        </div>);
      }
    });
  }

  buildExplain = () => {
    return (
      <div className='content-explain'>
        <div className='row'>
          <div className='fault'></div>
          <span>高风险</span>
        </div>
        <div className='row'>
          <div className='alarm'></div>
          <span>告警</span>
        </div>
        <div className='row'>
          <div className='normal'></div>
          <span>安全</span>
        </div>
      </div>
    );
  }

  setInstanceToGlobal = inst => {
    this.map = inst;
    window.map = inst;
    //this.initMap();
  };

  render() {
    const events = {
      created: this.setInstanceToGlobal
    };
    if (outMap) {
      mapConfig.layers = layers;
    }

    let { mapCenter, visible } = this.state;
    return (
      <div className="map-root">
        <div className='content-alarm'>
          {this.buildAlarm()}
        </div>
        {visible && <div className='loading'>
           <img src={mapIcon.loading}></img>
           <span>数据更新完毕！</span>
        </div>}
        <div className='map'>
          <BaseMap events={events}
            useAMapUI
            center={mapCenter}
            {...mapConfig}
            dragEnable={false}
          >
            {this.setBodyMarker()}
            {this.setBodyLine()}
            {this.renderAliasLine()}
          </BaseMap>
        </div>
        {this.buildExplain()}
        {/* <div className="input-card">
          <div>
            <input type="text" id="lnglat"></input>
          </div>
        </div> */}
      </div>
    );
  }
}

BasicMap.propTypes = {
};

export default BasicMap;
