import React from 'react';
import PropTypes from 'prop-types';

import {
  message
} from "antd";

/*
 * 高德案例
 * http://lbs.amap.com/api/javascript-api/example/amap-ui-pathsimplifier/simple-demo
 */

class PAMapPath extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      ifInit: false,//是否初始化过
    }
  }

  static propTypes = {
    paths: PropTypes.arrayOf(PropTypes.array),//坐标集合
    pathName: PropTypes.string,//路径名字
    loop: PropTypes.bool, //循环播放
    speed: PropTypes.number,//巡航速度，单位千米/小时
    style: PropTypes.object
  }

  static defaultProps = {
    style: {
      width: '100%',
      height: '100%'
    },
    loop: true,
    pathName: "",

  }
  componentDidMount = () => {
    this.loadMap();
  }

  componentWillReceiveProps = (nextProps) => {
    const { ifInit } = this.state;
    //转化为字符串，易于比对
    const changeStr = (obj) => {
      const { paths = [], pathName = "", loop = "", speed = "" } = obj;
      return paths + pathName + loop + speed + ""
    }

    const thisPropsStr = changeStr(this.props);
    const nextPropsStr = changeStr(nextProps);

    if (thisPropsStr === nextPropsStr) {
      return;
    }

    if (!ifInit) {
      this.loadMap();
      return;
    }

    if (ifInit && nextProps.paths.length > 0) {
      this.setPath(nextProps);
    } else {
      this.loadMap();
    }

  }


  //加载相关依赖
  loadMap = () => {
    const base = document.createElement("base");
    base.href = "//webapi.amap.com/ui/1.0/ui/misc/PathSimplifier/examples/";
    document.body.appendChild(base);

    const script = document.createElement("script");
    script.src = "http://webapi.amap.com/maps?v=1.4.4&key=9066916e054aa3083a6f081a2a9f9d7a";
    document.body.appendChild(script);

    const script2 = document.createElement("script");
    script2.src = "//webapi.amap.com/ui/1.0/main.js?v=1.0.11";

    document.body.appendChild(script2);

    this.loading();
  }

  //重复判断 是否加载完成。最多5秒提示超时
  loading = () => {
    let _this = this;

    function nextStep() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve("AMap" in window && "AMapUI" in window);
        }, 500);
      });
    }

    async function ajaxMap() {
      let ifComplete = false;
      let ifLoading = false;
      for (var i = 0; i < 10; i++) {

        if (!ifComplete) {
          ifComplete = await nextStep();
        }
        else {
          if (ifComplete && !ifLoading) {
            ifLoading = true;
            _this.initMap();
          }
          if (!ifLoading && i >= 10) {
            message.error("网络超时")
          }
        }
      }
    }

    ajaxMap();
  }

  initMap = () => {
    //创建地图
    var map = new AMap.Map('container', {
      zoom: 10,
      // center: [lng, lat]
    });

    AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], (PathSimplifier, $) => {

      if (!PathSimplifier.supportCanvas) {
        alert('当前环境不支持 Canvas！');
        return;
      }

      const { paths } = this.props;

      //如果 没有设置路径，则不构建 曲线
      if (!paths) {
        return;
      }
      this.pathSimplifierIns = new PathSimplifier({
        zIndex: 100,
        //autoSetFitView:false,
        map: map, //所属的地图实例

        getPath: function (pathData, pathIndex) {

          return pathData.path;
        },
        getHoverTitle: function (pathData, pathIndex, pointIndex) {

          if (pointIndex >= 0) {
            //point
            return pathData.name + '，点：' + pointIndex + '/' + pathData.path.length;
          }
          //鼠标悬停时候展示的信息，暂时隐藏
          const pathTip = pathData.name + '，点数量' + pathData.path.length;
          return "";
        },
        renderOptions: {

          renderAllPointsIfNumberBelow: 100 //绘制路线节点，如不需要可设置为-1
        }
      });
      this.setPath();
    });
  }

  //设置轨迹线路
  setPath = (nextProps = { ...this.props }) => {
    if (!this.state.ifInit) {
      this.setState({ ifInit: true });
    }

    let { pathSimplifierIns, navg } = this;

    let { paths, pathName, loop, speed } = nextProps;

    if (!speed) {
      speed = this.countSpeed(paths);
    }
    //设置数据
    pathSimplifierIns.setData([{
      name: pathName,
      path: paths
    }]);
    //对第一条线路（即索引 0）创建一个巡航器
    navg = pathSimplifierIns.createPathNavigator(0, {
      loop, //循环播放
      speed //巡航速度，单位千米/小时
    });
    navg.start();
  }

  //粗略计算轨迹播放速度
  countSpeed = (arr) => {
    const len = arr.length;
    if (len === 0 || len === 1) {
      return 0
    }

    let [x1, y1] = arr[0];
    let [x2, y2] = arr[arr.length - 1];

    x1 = x1 * 10000;
    y1 = y1 * 10000;
    x2 = x2 * 10000;
    y2 = y2 * 10000;

    const diff = Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2));


    if (diff < 10) {
      return diff * 100;
    }

    if (diff < 100) {
      return diff * 80;
    }
    if (diff < 1000) {
      return diff * 70;
    }
    if (diff < 10000) {
      return diff * 35;
    }
    if (diff < 100000) {
      return diff * 10;
    }
    if (diff >= 100000) {
      return diff * 3;
    }

  }

  /******************************相关事件******************************/

  /******************************render******************************/

  render() {
    const { style } = this.props;
    return (
      <div id="container" style={style}></div>
    );
  }
}


export default PAMapPath

