import React, { Component } from 'react';
import { BaseMap, Marker, InfoWindow, Circle, Polyline } from 'amos-amap';
import { UUID } from 'amos-tool';
import { calcDetailOffset } from './methods';
import AmosWebSocket from 'amos-websocket';
import SysWsURL from './../../../../consts/wsUrlConsts';
import { _picURI, _mapCenter, _showZoom } from './../../../../consts/urlConsts';
import * as endConf from 'amos-processor/lib/config/endconf';
const AmosConfig = endConf.AmosConfig;
const outMap = AmosConfig.sysConf.outMap;

/**
 *  二维模块
 */
class TwoDimensionalMap extends Component {
  constructor(props) {
    super(props);
    const me = this;
    this.state = {
      oneCircle: [],  //地图点集
      startPoint: {}, // 起始点坐标
      oneLine: [],
      currentLinePath: [],
      person: {},
      linePaths: [],
      showInfo: false,
      currentStep: 0,
      personCenter: {},
      personPath: [],
      circleList: [],
      center: { longitude: 108.904761, latitude: 34.230161 },
      radius: 15,
      visible: true,
      style: { strokeColor: 'red', fillColor: 'red' },
      draggable: true,
      content: '',
      position: { longitude: 108.680913, latitude: 34.331397 },
      offset: ['10', '-13'],
      size: {
        width: 100,
        height: 15
      }
    };
    this.styleC = {
      strokeStyle: 'dashed',
      strokeColor: 'red'
    };
    this.markerEvents = {
      created: instance => {
        console.log('instance', instance);
        window.InfoWindow = instance;
      },
      mouseover: (e) => {
        let position = { longitude: this.state.personCenter.longitude, latitude: this.state.personCenter.latitude };
        let frameSize = e.target.D.map.nJ;
        if (!outMap) {
          frameSize = e.target.D.map.nJ;
        } else {
          frameSize = e.target.D.map.qM;
        }

        let markerPxPosition = e.pixel;
        this.getInfoWindow(
          position,
          calcDetailOffset(markerPxPosition, frameSize, {
            height: 176,
            width: 360
          })
        );
      },
      mouseout: () => {
        this.setState({ showInfo: false })
      },
      change: chan => { console.log('chan', chan); },
      move: mo => { console.log('mo', mo); }
    };
    /**
     * 原点初始化事件
     */
    this.circleEvents = {
      created: ins => { },
      click: () => { },
      mouseover: e => { },
      mouseout: e => { }
    };
    /**
     * 轨迹初始化事件
     */
    this.lineEvents = {
      created: ins => { },
      show: () => { },
      hide: () => { },
      click: () => { }
    };
    /**
     * 弹框初始化
     */
    this.windowEvents = {
      created: iw => { },
      open: () => { },
      close: () => {
        setTimeout(() => {
          me.setState({
            showInfo: false
          });
        }, '100');
      },
      change: () => { }
    };
  }

  /**
     * 鼠标经过点的事件
     */
  getInfoWindow = (position, direction) => {
    let content;
    let width = '150px';
    let { person } = this.state;
    if (person.telephone == null) {
      person.telephone = '';
    }
    // else if (person.telephone.search("/")){//判断手机和电话同时存在，重新设定infoWindow宽度
    //   width = '215px';
    // }
    content = `<div class='map-marker-info-root' style={ width: ${width} }>
        <div >
          <span>姓名:</span><span style='padding-left: 10px'>${person.userName}</span>
        </div>
        <div >
          <span>电话:</span><span style='padding-left: 10px'>${person.telephone}</span>
        </div>
        <div class='info-row-first-root'>
          <span>单位:</span><span style='padding-left: 10px'>${person.deptCompany}</span>
        </div>
    </div>`;

    this.updateInfoWindow(content, position, true, direction);
  };

  setInstanceToGlobal = inst => {
    this.map = inst;
    window.map = inst;
  };

  /**
   *接收消息
   */
  handleData = data => {
    console.log('twoMap data', data);
    let { personCenter, currentLinePath, startPoint, oneLine } = this.state;
    const person = data;
    const center = { longitude: data.longitude, latitude: data.latitude };
    currentLinePath.push(center);
    personCenter = center;
    startPoint = currentLinePath[0];
    oneLine = [<Polyline style={this.styleC} key={UUID.uuid('24')} path={this.state.currentLinePath} events={this.lineEvents} visible={this.state.visible} draggable={this.state.draggable} />];
    //oneCircle = [<Circle center={startPoint} key={UUID.uuid('16')} radius={this.state.radius} events={this.circleEvents} visible={this.state.visible} style={this.state.style} draggable={this.state.draggable} />];
    this.setState({ currentLinePath, person, personCenter, oneLine });
  };

  /**
   * 控制组建是否显示
   */
  toggleVisible() {
    this.setState({
      visible: !this.state.visible
    });
  }

  /**
   * 控制组建是否可移动
   */
  toggleDraggable() {
    this.setState({
      draggable: !this.state.draggable
    });
  }
  /**
   * 设置显示/关闭详情框
   */
  updateInfoWindow = (content, position, showWindow, direction) => {
    this.setState({ showInfo: showWindow, content, position, offset: direction });
  };
  /**
  * 渲染线
  */
  renderLine = () => {
    var { oneLine } = this.state;
    return oneLine;
  }

  /**
   * 渲染点
   */
  renderCircle = () => {
    var { oneCircle } = this.state;
    return oneCircle;
  }

  render() {
    const { personCenter, showInfo } = this.state;
    const events = {
      created: this.setInstanceToGlobal
    };
    const towMapUrl = SysWsURL.towMapURI;
    const styleA = {
      background: `url('/src/assets/map/person.png')`,
      backgroundSize: 'contain',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      width: '40px',
      height: '40px',
      color: '#000',
      textAlign: 'center',
      lineHeight: '40px',
      borderRadius: '20px'
    };
    const styleD = {
      width: document.body.offsetWidth,
      height: document.body.offsetHeight
    };

    let { twoDimensionalMapConfig } = this.props;

    return (
      <div>
        <AmosWebSocket ref={node => this.aws = node} url={towMapUrl} onMessage={this.handleData} reconnect debug />
        <div style={styleD} id="testMap">
          <BaseMap center={this.state.center} zoom="13" useAMapUI="true" events={events} {...twoDimensionalMapConfig}>
            {
              this.renderLine()
            }
            {/* {
              this.renderCircle()
            } */}
            {
              personCenter.hasOwnProperty('longitude') && <Marker position={personCenter} events={this.markerEvents}>
                <div style={styleA}></div>
              </Marker>
            }
            <InfoWindow
              isCustom
              content={this.state.content}
              visible={showInfo}
              size={this.state.size}
              position={this.state.position}
              offset={this.state.offset}
              showShadow
              events={this.windowEvents}
              autoMove={false}
              closeWhenClickMap="true"
            />
          </BaseMap>
        </div>

        <button
          onClick={() => {
            this.changeRadius();
          }}
        >
          Change Radius
        </button>
        <button
          onClick={() => {
            this.toggleVisible();
          }}
        >
          Toggle Visible
        </button>
        <button
          onClick={() => {
            this.toggleDraggable();
          }}
        >
          Toggle Draggable
        </button>
      </div>
    );
  }
}

export default TwoDimensionalMap;
