import React from 'react';
import ReactDOM from 'react-dom';
import { map } from '../mapContext';
import { creatOverlayLayer, addImgToMap } from '../method/base';
import { creatSingleMarker, creatSinglePoint } from '../method/creatMarker';
import { creatInfo } from '../method/info';
import { searchRouteByMultiPoints } from '../method/searchRoute';
import { cloneDeep } from 'lodash';
import { message } from 'antd';
import ImageView from '../../../components/ImageView';
import { isEqual } from '@zenview/micro-utils';
const markerIndexArr = getMakerIndex();

@map
class AnimationLineLayer extends React.Component {
  constructor(props) {
    super(props);
    this.popupDom = document.createElement('div');
    this.popupDom.className = 'animationLine-popup-layout-content';
    this.state = {
      data: [],
      isDataChange: false,
      isMapReady: false,
      map: null,
      currentIndex: 0,
    };
  }

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

  componentWillUnmount() {
    const { map } = this.state;
    this.animatieonLine.removeEventListener('afterStep');
    map.destroyMap();
  }

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

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

  zoomToStart = () => {
    const { map } = this.state;
    if (!map) {
      return;
    }
    if (Array.isArray(this.state.data) && this.state.data.length > 0) {
      let headerPoint = creatSinglePoint(this.state.data[0]);
      this.searchRoute(this.state.data, headerPoint);
      this.setState({ currentUrl: this.state.data[0].imageUrl });
      map.setCenter(headerPoint, 12, {
        speed: 10,
        callback: () => {
          this.createAnimationLines(this.state.data, headerPoint);
        },
      });
    }
  };

  searchRoute = (points, headerPoint) => {
    const { map } = this.state;
    const { type } = this.props;
    if (!map || !points) {
      return;
    }
    addImgToMap({
      map,
      imgArr: [['foot', '/micro-apps/micro-dep-librarys/images/zenMap/lastImg.png']],
      callback: () => {
        // let headMarker = creatSingleMarker({ map: map, point: points[0], urlName: 'foot', iconSize: 1.2, layers: this.layer, labelName: points[0].deviceName }); //轨迹头部marker
        creatInfo(map, headerPoint, this.popupDom, null, (info) => {
          this.info = info;
        });
        let dom = document.createElement('img');
        dom.src = '/micro-apps/micro-dep-librarys/images/zenMap/lastImg.png';
        dom.addEventListener('click', () => {
          this.info.isOpen() ? this.info.hide() : this.info.show();
        });
        if (type === 'default') {
          this.creatAnimationLine(points, dom, true);
        } else if (type === 'road') {
          // 路网-动画
          searchRouteByMultiPoints({
            points,
            map,
            successCallBack: (pointsArr) => {
              this.creatAnimationLine(points, dom, pointsArr);
            },
            errorCallback: (err) => {
              message.warn(err);
            },
          });
        }
      },
    });
  };

  creatAnimationLine = (points, dom, pointsArr) => {
    const { MapPlatForm } = window;
    const { map } = this.state;
    if (!map || !points) {
      return;
    }

    var animationLine = new MapPlatForm.Base.AnimationLine(map, pointsArr, {
      renderFirst: true,
      headerMarker: {
        element: dom,
      },
      weight: 5,
      color: '#ff5d5d',
    });
    this.animatieonLine = animationLine;
    if (!animationLine) {
      return;
    }
    animationLine.setSpeed(this.props.speed);
    animationLine.trace();
    setTimeout(function () {
      animationLine.restart();
    }, 2000);
    let pointArr = cloneDeep(points);
    pointArr[0].arrIndex = 0;
    // animationLine.addEventListener("ZenMap.ANIMATION_EVENT_START",()=>{
    animationLine.addEventListener('afterStep', (current) => {
      this.changeInfoPosition(current.point);
      if (current.point.topIndex) {
        let getPoints = points.filter((v) => +v.lon === +current.point.lon && +v.lat === +current.point.lat);
        if (getPoints.length > 1) {
          getPoints.forEach((v) => {
            pointArr[v.topIndex].arrIndex = current.pointIndex;
          });
        }
        pointArr[current.point.topIndex].arrIndex = current.pointIndex;
        this.props.changeIndexCallback(current.point.topIndex);
        if (current.point.topIndex === points.length - 1) {
          this.props.setIsPlay(true)
          this.props.changeIndexCallback(0);
        }
        this.setState({ currentUrl: current.point.imageUrl, currentIndex: current.point.topIndex });
      }
    });
    // })
    this.props.setListIndex(pointArr);
    this.props.getAnimationLine(animationLine);
  };

  changeImgVisible = () => {
    if (this.info) {
      this.info.isOpen() ? this.info.hide() : this.info.show();
    }
  };

  changeInfoPosition = (point) => {
    const { ZenMap } = window;

    // this.info.setOffset (array offset)
    this.info.setPosition(new ZenMap.Geometry.Point(point.lon, point.lat));
  };

  createAnimationLines = (points, headerPoint) => {
    //动画线，isMultiple：多条 !isMultiple：一条
    const { map } = this.state;
    if (!map || !points) {
      return;
    }
    addImgToMap({
      map,
      imgArr: [
        ['redPoint', '/micro-apps/micro-dep-librarys/images/zenMap/defaultImg.png'],
        ['foot', '/micro-apps/micro-dep-librarys/images/zenMap/lastImg.png'],
      ],
      callback: () => {
        points.forEach((point, index) => {
          //渲染经过点
          if (!point.latitude || !point.longitude) {
            return;
          }
          point.lon = point.longitude;
          point.lat = point.latitude;
          point.topIndex = index;
          creatSingleMarker({
            map: map,
            point,
            urlName: 'redPoint',
            iconSize: 1,
            layers: this.layer,
            labelName: point.deviceName,
            context: markerIndexArr[index],
            callback: (marker) => {},
          });
        });
      },
    });
  };

  render() {
    const { currentUrl, currentIndex } = this.state;
    return <>{ReactDOM.createPortal(<ImageView src={currentUrl} onClick={(e) => this.props.onClick(currentIndex)}></ImageView>, this.popupDom)}</>;
  }
}
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;
}
