import React from 'react';
import { map } from '../mapContext';
import { creatOverlayLayer, addImgToMap, typeSwitch } from '../method/base';
import { creatSingleMarker, creatSinglePoint } from '../method/creatMarker';
import { drawPolygonByPoint } from '../method/shapLayer';
import { searchRouteByMultiPoints } from '../method/searchRoute';
import { cloneDeep } from 'lodash';
import { message, Progress } from 'antd';
import { isEqual } from '@zenview/micro-utils';
const markerIndexArr = getMakerIndex();

@map
class AnimationLineLayer extends React.Component {
  constructor(props) {
    super(props);
    const { data, places, type } = this.props;
    this.state = {
      data: [],
      isDataChange: false,
      isMapHave: false,
      map: null,
      places: cloneDeep(places) || [],
      status: 'loading',
      pointArr: null,
    };
  }

  mapReady = (map) => {
    creatOverlayLayer({
      map: map,
      name: 'LineLayer',
      isCluster: false,
      callback: (layer) => {
        this.layer = layer;
        this.setState({ map: map, isMapHave: true });
      },
    });
  };

  static getDerivedStateFromProps(props, state) {
    if (props.data && !isEqual(props.data, state.data)) {
      return { isDataChange: true, data: props.data };
    }
    if (props.places && !isEqual(props.places, state.places)) {
      return { isDataChange: true, places: props.places };
    }
    return null;
  }

  componentDidUpdate() {
    if (this.state.isDataChange && this.state.isMapHave) {
      this.setState({ isDataChange: false, isMapHave: false });
      this.zoomToStart();
    }
  }

  zoomToStart = async () => {
    const { map, type } = this.props;
    const { data, places } = this.state;
    const { ZenMap } = window;
    if (!map || !this.layer) {
      return;
    }
    let points = Object.values(data);
    if (Array.isArray(points) && points.length > 0) {
      if (type && type === 'road') {
        await searchRouteByMultiPoints({
          //查路网路径
          points,
          map,
          lineCallBack: (lines) => {
            this.layer.addOverlay(lines);
            map.zoomToExtent(lines.getExtent(), 50); //获取路线范围，定位到该范围
          },
          successCallBack: (pointArr) => {
            this.setState({ status: 'over', pointArr });
          },
          errorCallback: (err) => {
            this.setState({ status: 'error' });
            message.warn(err);
          },
        });
      } else if (type && type === 'default') {
        let lineOpt = {
          color: 'blue', //颜色
          weight: 5, //宽度，以像素为单位
          opacity: 2, //透明度，取值范围0 - 1
          lineStyle: ZenMap.LINE_TYPE_SOLID, //样式
        };
        let pointsArr = points.map((v) => {
          return creatSinglePoint(v);
        });
        let line = new ZenMap.Geometry.Polyline(pointsArr, lineOpt);

        this.layer.addOverlay(line);
        map.zoomToExtent(line.getExtent(), 50); //获取路线范围，定位到该范围
      }
      this.createAnimationLines(points); //渲染轨迹点和路径
    } else {
      this.setState({ status: 'over' });
    }
    if (Array.isArray(places) && places.length > 0) {
      this.creatPlace(places); //渲染场所图标和场所轮廓
    }
  };

  getTrajectory = () => {
    const { pointArr } = this.state;
    return pointArr;
  };

  setPointCenter(cid) {
    //与eCharts点击关联
    const { data, map } = this.state;
    let target = data.find((v) => +v.cid === +cid);
    if (!target) {
      return;
    }
    const { position } = target;
    if (!position) {
      return;
    }
    let targetPoint = creatSinglePoint(target);

    map.setCenter(targetPoint, 17, { speed: 10 });
  }

  setPlaceCenter = (place) => {
    const { map } = this.props;
    let dataArr = typeSwitch(place.polyline);
    drawPolygonByPoint({
      pointList: dataArr[0],
      layer: this.layer,
      map,
      isRender: false,
      callback: (polygon) => {
        map.zoomToExtent(polygon.getExtent(), 50);
      },
    });
  };

  createAnimationLines = (points) => {
    //绘线
    const { map, getFormatData } = this.props;
    if (!map || !points || !this.layer) {
      return;
    }
    addImgToMap({
      map,
      imgArr: [['redPoint', '/micro-apps/micro-dep-librarys/images/zenMap/defaultImg.png']],
      callback: () => {
        points.forEach((point, index) => {
          //渲染经过点
          if (!point.lon || !point.lat) {
            return;
          }
          point.index = markerIndexArr[index];
          point.counts = point.list.length;
          creatSingleMarker({
            map: map,
            point,
            urlName: 'redPoint',
            iconSize: 1,
            layers: this.layer,
            labelName: point.name,
            context: markerIndexArr[index],
            callback: (marker) => {},
          });
        });
        getFormatData && getFormatData(points); //返回 eChart关联数据
      },
    });
  };

  creatPlace = (places) => {
    const { map } = this.props;
    if (!map || !places || !this.layer) {
      return;
    }
    addImgToMap({
      map,
      imgArr: [['foot', '/micro-apps/micro-dep-librarys/images/zenMap/lastImg.png']],
      callback: () => {
        places.forEach((place) => {
          place.lon = place.center.split(',')[0];
          place.lat = place.center.split(',')[1];
          creatSingleMarker({
            //渲染场所中心点
            map: map,
            point: place,
            urlName: 'foot',
            iconSize: 1,
            layers: this.layer,
            labelName: place.placeName,
            callback: (marker) => {},
          });
          if (place.polyline) {
            //渲染场所轮廓
            let dataArr = typeSwitch(place.polyline);
            drawPolygonByPoint({ pointList: dataArr[0], layer: this.layer, map });
          }
        });
      },
    });
  };

  render() {
    return (
      <>
        {/* <Progress status={this.state.status}></Progress> */}
      </> 
    );
  }
}
export default AnimationLineLayer;

function getMakerIndex() {
  let index = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z'.split(',');
  let arr = cloneDeep(index);
  let a = cloneDeep(index);
  let b = cloneDeep(index);
  a.forEach((v1) => {
    b.forEach((v2) => {
      arr.push(`${v1}${v2}`);
    });
  });
  return arr;
}
