import Taro, { Component } from '@tarojs/taro'
import { Map } from '@tarojs/components'
import icons from './icons'

const centerIcon = require('@/assets/dingwei.png')
const centerProject = 'project-999'

function ObjEqual(a = {}, b = {}) { return JSON.stringify(a) === JSON.stringify(b) }

export default class PoiAround extends Component {
  map = null;

  componentDidMount() {
    this.map = wx.createMapContext('poi-around', this)
  }

  componentWillReceiveProps(nextProps) {
    if (this.map) {
      if (!ObjEqual(nextProps.markers, this.props.markers)) {
        this.map.moveToLocation({
          latitude: nextProps.latitude,
          longitude: nextProps.longitude,
        })
      }
    }
  }

  handleTap = (e) => {
    if (e.markerId === centerProject) return;

    const marker = this.props.markers.filter(x => x.id === e.markerId)[0]
    this.props.onMarkerClick && this.props.onMarkerClick(marker)
  }

  render() {
    const markers = (this.props.markers || []).map((marker, index) => {
      const icon = icons[index].normal
      const activeIcon = icons[index].active

      return {
        id: marker.id,
        latitude: marker.latitude,
        longitude: marker.longitude,
        iconPath: this.props.current === marker.id ? activeIcon : icon,
        width: 56,
        height: 56,
      }
    })

    // 最后放项目位置
    markers.push({
      id: centerProject,
      latitude: this.props.latitude,
      longitude: this.props.longitude,
      iconPath: centerIcon,
      width: 20,
      height: 20,
    })


    return this.props.longitude &&
      (
        <Map
          id="poi-around"
          showLocation
          show-location={true}
          scale={12}
          markers={markers}
          longitude={this.props.longitude}
          latitude={this.props.latitude}
          onMarkerTap={this.handleTap}
          onClick={this.props.mapClick}
          style={this.props.style}
          enable-scroll={this.props.coverShow ? false : true}
          enable-zoom={this.props.coverShow ? false : true}
        />
      )
  }
}
