import React from 'react'
import ReactDOM from 'react-dom'
import { map } from '../mapContext'
import { createIndexIcon } from '../utils/overlayer'
import { popupOptions } from '../utils/config'
import TrackPlayLayer from '../trackPlay'
import MapResetTools from './MapResetTools'
import TrajectoryTools from './TrajectoryTools'
import * as L from 'leaflet'
import _ from 'lodash'
import ImageView from '../../../components/ImageView'
import { isEqual } from '@zenview/micro-utils'
const 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;
}
const markerIndexArr = getMakerIndex()
const popupConfig = {
  ...popupOptions,
  offset: L.point(0, -26),
  maxWidth: 80,
  maxHeight: 100,
  minWidth: 80,
  autoClose: false,
  closeOnClick: false,
  className: 'marker-popup-layout trajectory-popup-layout arrow-map-layout'
}

@map
class Trajectory extends React.Component {
  constructor(props) {
    super(props)
    this.featureGroup = L.featureGroup().addTo(this.props.map)
    this.popupDom = document.createElement('div')
    this.popupDom.className = 'trajectory-popup-layout-content'
    this.state = {
      isPause: false,
      visible: true,
      data:  props.data?props.data.filter(v => (v.latitude && v.longitude)) : null,
      isDataChange: false,
      currentUrl: null,
      currentIndex: 0
    }
  }
  static getDerivedStateFromProps(props, state) {
    if (props.data && !isEqual(state.data, props.data.filter(v => (v.latitude && v.longitude)))) {
      return { data: _.cloneDeep(props.data).filter(v => (v.latitude && v.longitude)), isDataChange: true }
    }
    return null
  }
  componentDidMount() {
    if (Array.isArray(this.state.data) && this.state.data.length > 0) {
      this.createTrackPlayLayer()
    }
  }
  componentDidUpdate() {
    if (this.state.isDataChange) {
      this.setState({ isDataChange: false })
      if (Array.isArray(this.state.data) && this.state.data.length > 0) {
        this.createTrackPlayLayer()
      }
    }
  }
  componentWillUnmount() {
    this.popupDom.remove()
    this.popupDom = null
    this.trackLayer && this.trackLayer.dispose()
    this.featureGroup.clearLayers()
    this.featureGroup = null
  }

  cleanMap = () => {
    this.trackLayer && this.trackLayer.dispose()
    this.featureGroup.clearLayers()
  }

  createTrackPlayLayer() {
    this.trackLayer && this.trackLayer.dispose()
    const { map } = this.props
    let { data } = this.state
    this.createMarkers(data)
    this.trackLayer = new TrackPlayLayer(map, data, {
      autoStart: true,
      update: this.update,
      end: this.end,
      moveChange: this.moveChange,
      onInit: this.onInit
    })
  }

  onInit = marker => {
    this.marker = marker
  }
  update = () => {
    if (!this.trackLayer) {
      return
    }
    this.setState({ isPause: this.trackLayer.status.isPause })
  }

  createMarkers(data) {
    let { markerClick } = this.props;
    this.featureGroup.clearLayers()
    data.forEach((point, index) => {
      const maker = L.marker(L.latLng(point.latitude, point.longitude), {
        icon: createIndexIcon(markerIndexArr[index])
      })
      if (markerClick) {
        maker.on("click", () => {
          markerClick(point);
        });
      }
      this.featureGroup.addLayer(maker)
    })
    this.mapReset()
  }
  end = () => {
    console.log('轨迹播放结束！')
  }
  moveChange = index => {
    const { changeIndexCallback } = this.props
    const currentData = this.state.data[index]
    this.setState({ currentUrl: currentData.imageUrl, currentIndex: index })
    const popup = L.popup(popupConfig).setContent(this.popupDom)
    this.marker
      .closePopup()
      .unbindPopup()
      .bindPopup(popup)
    if (this.state.visible) {
      this.marker.openPopup()
    }
    changeIndexCallback && changeIndexCallback(index)
  }

  change = index => {
    this.trackLayer.start(index, false)
  }

  playOrPause = () => {
    if (this.trackLayer.status.isPause) {
      this.trackLayer.play()
    } else {
      this.trackLayer.pause()
    }
  }

  play = () => {
    if (this.trackLayer.status.isPause) {
      this.trackLayer.play()
    }
  }

  pause = () => {
    if (!this.trackLayer.status.isPause) {
      this.trackLayer.pause()
    }
  }
  reset = () => {
    this.trackLayer.reset()
  }
  prev = () => {
    this.trackLayer.prev()
  }
  next = () => {
    this.trackLayer.next()
  }

  onChangeVisible = async checked => {
    this.setState({ visible: checked })
    if (checked) {
      this.marker.openPopup()
    } else {
      this.marker.closePopup()
    }
  }
  mapReset = () => {
    this.props.map.fitBounds(this.featureGroup.getBounds())
  }
  render() {
    const { visible, isPause, currentUrl, currentIndex } = this.state
    return (
      <React.Fragment>
        <TrajectoryTools
          visible={visible}
          next={this.next}
          prev={this.prev}
          isPause={isPause}
          reset={this.reset}
          playOrPause={this.playOrPause}
          onChangeVisible={this.onChangeVisible}
        />
        <MapResetTools mapReset={this.mapReset} />
        {this.props.children}
        {ReactDOM.createPortal(<ImageView src={currentUrl} onClick={() => this.props.onClick && this.props.onClick(currentIndex)}></ImageView>, this.popupDom)}
      </React.Fragment>
    )
  }
}

export default Trajectory
