import React from 'react';
import ReactDOM from 'react-dom';
import isEmpty from 'lodash/isEmpty';
import {Icon} from 'antd';
import { WeaMap } from 'ecCom';
import { Polyline, Marker, InfoWindow } from 'react-amap';
import '../style/map.less';

let mapInstance;
const iconCls = {
  '0': 'markerRBg',
  '1': 'markerYBg'
}
const colors = ["#0072E3", "#BE77FF", "#FFD306", "#02DF82", "#D94600", "#AE0000", "#5CADAD", "#AE57A4", "#613030 ", "#D9006C"];
const cLength = colors.length;
const content =  i => `<div class='markerContent ${iconCls[0]}'>${i + 1}</div>`;
const createDetailTemplete = c => {
  const {crm = [], pics = []} = c;
  let picDom = '',crmDom = '';
  pics.map(pic => picDom += `<div class='mb5-img'><img src=${pic} border="0" width="65" height="64"/></div>`);
  crm.map(d => crmDom += `<div class='crm-text-elli'>${d}</div>`);

  return `<div class="hrm-map-detail">
  <i class="cursor-pointer icon-coms-Clear" onclick='return closeHrmMapInfoWindow();'></i>
  <div class="mb5">
    <span class="mr10">${c.name}</span>
    <span class="gray mb5">${c.time}</span>
    <span class="signTitle">${c.signTitle}</span>
  </div>
  <div class='info-wrap'>
  ${c.information?`<div class="mb5 m-information">${c.information}</div>`:''}
  ${c.pics?`<div class="mb5">
    ${picDom}
  </div>`:''}
  ${crm && crm.length > 0 ? 
    `
    <div class='mb5' style="display: flex">
      <i class="icon-coms-currency-Customer" style="margin-right: 10px; color: #999;font-size:14.3px"></i>
      <div style="flex: 1, width: '98%'">
      ${crmDom}
      </div>
    </div>
    ` : ''}
  <div class="gray" style="display: flex">
    <i class="icon-coms-position" style="margin-right: 10px; color: #999; font-size:13.3px"></i>
    <div class='location'>
    ${c.title}
    </div> 
  </div>
</div>
</div>`
}

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      markers: [],
      polylines: [],
      infoWindow: {
        visible: false,
        isCustom: true
      },
      showMap: false
    }
  }

  componentDidMount() {
    window.closeHrmMapInfoWindow = this.closeInfoWindow;
    this.initMap();
  }

  componentWillReceiveProps(nextProps){
    this.initMap(nextProps);
  }

  closeInfoWindow = () => {
    this.setState({
      infoWindow: {
        ...this.state.infoWindow,
        visible: false
      }
    })
  }

  initMap = (nextProps) => {
    this.setState({showMap: false});
   
    let _props = nextProps || this.props;
    const {config, mult} = _props;
    
    if(isEmpty(config) || (mult && config.length == 0))
      return;
    this.setState({infoWindow: {...this.state.infoWindow, visible: false}});
    this.addMarker(_props);
  }

  addMarker = (nextProps) => {
    let _props = nextProps || this.props;
    const { config, mult } = _props
    let markers = [];
    let polylines = [];
    if(mult){
      config.map((c, i) => {
        let path = [];
        c.items.reverse().map((item, j) => {
          const markerProps = {
            title: item.title,
            content: content(j),
            position: {
              longitude: item.x,
              latitude: item.y
            },
            events: {
              click: (e) => {
                this.setState({
                  infoWindow: {
                    ...this.state.infoWindow,
                    content:createDetailTemplete(item),
                    position: {
                      longitude: item.x,
                      latitude: item.y
                    },
                    visible: true
                  }
                })
              }
            }
          }
          path.push(markerProps.position);
          markers.push(<Marker ecId={`${this && this.props && this.props.ecId || ''}_Marker@jhtbtu@${j}`} {...markerProps} />)
        });
        const polylineProps = {
          path,
          style: {
            strokeColor: colors[i % cLength],
            strokeOpacity: 1,
            strokeWeight: 2,
            strokeStyle: "solid"
          }
        }
        polylines.push(<Polyline ecId={`${this && this.props && this.props.ecId || ''}_Polyline@xitg2a@${i}`} {...polylineProps} />)
      })
    }else{
      const markerProps = {
        title: config.title,
        content: content(0),
        position: {
          longitude: config.x,
          latitude: config.y
        },
        events: {
          click: (e) => {
            this.setState({
              infoWindow: {
                ...this.state.infoWindow,
                content:createDetailTemplete(config),
                position: {
                  longitude: config.x,
                  latitude: config.y
                },
                visible: true
              }
            })
          }
        }
      }
      markers.push(<Marker ecId={`${this && this.props && this.props.ecId || ''}_Marker@osq030@1`} {...markerProps} />)
    }
    this.setState({markers, polylines, showMap: true});
  }
  
  setFitView = () => {
    setTimeout(() => {
      mapInstance && mapInstance.setFitView();
    }, 0)
  }

  setMapInstance = (instanace) => {
    if(instanace.CLASS_NAME === 'AMap.Map'){
      mapInstance = instanace;
    }
  }

  render() {
    const mapEvt = {
      created: instanace => this.setMapInstance(instanace),
      complete: () => this.setFitView()
    }
    const mapProps = {
      zoom: 14,
      resizeEnable: true,
      plugins: [
        'Scale', {
          name: 'ToolBar',
          options: {
            locate: false
          },
        }
      ],
      events: mapEvt
    }
    return (
      <div className='wea-hrm-map' style={{width: '100%', height: '100%'}}>
        {
          this.state.showMap &&
        <WeaMap ecId={`${this && this.props && this.props.ecId || ''}_WeaMap@y92jjs`} {...mapProps}>
          {this.state.markers}
          {this.state.polylines}
          {
            this.state.infoWindow.visible &&
            <InfoWindow ecId={`${this && this.props && this.props.ecId || ''}_InfoWindow@2da6iw`} {...this.state.infoWindow}/>
          }
        </WeaMap>
        }
      </div>
    );
  }
}

Main.propTypes = {
  position: React.PropTypes.any, // 位置，可以是经纬度数组或LngLat实例
  title: React.PropTypes.string, // 提示文字
  zoom: React.PropTypes.number, // 缩放比例
};

Main.defaultProps = {
  zoom: 14,
};

export default Main;
