import React, { Component } from 'react';
import { BaseMap, Marker, InfoWindow, Circle, Polyline } from 'amos-amap';
import { UUID } from 'amos-tool';
import { calcDetailOffset } from './methods';
import { getTrack } from './../../../../services/2dService';
import AmosWebSocket from 'amos-websocket';
import SysWsURL from './../../../../consts/wsUrlConsts';

/**
 *  二维模块
 */
class TwoDimensionalMap extends Component {
  constructor(props) {
    super(props);
    const me = this;
    this.state = {
      oneLine: [],
      currentLinePath: [],
      'personTell': 0,
      'personCompany': '',
      linePaths: [],
      showInfo: false,
      currentStep: 0,
      personCenter: {},
      personPath: [],
      circleList: [],
      center: { longitude: 108.917419, latitude: 34.219139 },
      radius: 15,
      visible: true,
      style: { strokeColor: 'red', fillColor: 'red' },
      draggable: true,
      content: '',
      position: { longitude: 108.916088, latitude: 34.223146 },
      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: e.lnglat.lng, latitude: e.lnglat.lat };
        let frameSize = e.target.D.map.nJ;
        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: () => {}
    };
  }

  componentWillMount() {
    getTrack('/src/_mock/map/map.json',(linePaths,personTell,personCompany)=>{
      this.initData(linePaths);
      this.setState({ linePaths ,personTell, personCompany });
    });
  }
  componentDidMount() {
    //this.initData();
    this.forwardLoop();


  }

/**
   * 鼠标经过点的事件
   * @param {*} id
   * @param {*} position
   * @param {*} direction
   */
  getInfoWindow = (position, direction) => {
    let content = `<div class='map-marker-info-root'>
        <div >
          <span>电话:</span><span>${this.state.personTell}</span>
        </div>
        <div class='info-row-first-root'>
          <span>单位:</span><span>${this.state.personCompany}</span>
        </div>
    </div>`;

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

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

  /**
   *初始化数据
   */
  initData=(res)=>{
    const personCenter = res[0].path[0];
    const personPath = res[0].path;
    let circleList = [];
    circleList.push(res[0].path[0]);
    circleList.push(res[0].path[res[0].path.length - 1]);
    this.setState({ personCenter, personPath, circleList });
  }

  /**
   * 向前走循环
   */
  forwardLoop = () => {
    window.forwardStep = this.forwardStep;
    setInterval(function() {
      window.forwardStep();
    }, '2000');
  };
  /**
   * 向前走一步
   */
  forwardStep = () => {
    var oneLine = [];
    var { currentStep, personCenter, personPath,currentLinePath } = this.state;
    if (currentStep === personPath.length) {
      currentStep = 0;
      currentLinePath = [];
    }
    personCenter = personPath[currentStep];
    currentStep = currentStep + 1;
    if (personCenter){
      currentLinePath.push(personCenter);
    }
    oneLine = [<Polyline style={this.styleC} key={UUID.uuid('24')} path={this.state.currentLinePath} events={this.lineEvents} visible={this.state.visible} draggable={this.state.draggable} />];
    this.setState({ personCenter, currentStep,currentLinePath, oneLine });
  };

  /**
   *接收消息
   */
  handleData = data => {
    console.log('twoMap data',data);
  };


  /**
   * 地图坐标坐标转换
   */
  // transCoordinate =(personCenter)=>{
  //   var lnglat = new AMap.LngLat(personCenter.longitude, personCenter.latitude);
  //   var pixel = map.lngLatToContainer(lnglat);  // 获得 Pixel 对象
  // }
  /**
   * 控制组建是否显示
   */
  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;
  }

  render() {
    const { personCenter, circleList, 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
    };

    return (
      <div>
        <AmosWebSocket ref={node => this.aws = node} url={towMapUrl} onMessage={this.handleData} reconnect debug />
        <div style={styleD} id="testMap">
          <BaseMap plugins={['ToolBar']} center={this.state.center} zoom="13" useAMapUI="true" events={events}>
            {(circleList || []).map((item, index) => (
              <Circle
                key={UUID.uuid('16')}
                center={item}
                radius={this.state.radius}
                events={this.circleEvents}
                visible={this.state.visible}
                style={this.state.style}
                draggable={this.state.draggable}
              />
            ))}
            {/*{(linePaths || []).map((item, index) => {
              return (
                <Polyline
                  style={styleC}
                  key={UUID.uuid('32')}
                  path={currentLinePath}
                  events={this.lineEvents}
                  visible={this.state.visible}
                  draggable={this.state.draggable}
                />
              );
            })}*/}
            {
              this.renderLine()
            }
            {/*<Polyline style={styleC} path={currentLinePath} events={this.lineEvents} visible={this.state.visible} draggable={this.state.draggable} />*/}

            {/* {
            (linePaths || []).map((item, index) => {

              return (
                <CarMaker path={item.path} key={UUID.uuid(24)}></CarMaker>
              );
            })
          } */}
            <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;
