import { ref, nextTick } from 'vue'
import { parseWKT } from '@/utils/parseWKT'
import Subscriber from '@cesium-extends/subscriber'
import { useWeatherPopup } from './weatherPopup'
const { popupMap, createPopup } = useWeatherPopup()

let subscriber: Subscriber | null = null
const weatherMap = new Map()
const weatherList = [
  {
    id: '10',
    createTime: null,
    updateTime: null,
    geom: 'POINT (121.9 29.02)',
    type: 'weather',
    name: '晴天',
    description: null,
  },
]
const useWeather = () => {
  const showWeather = ref(true)

  nextTick(() => {
    watch(
      showWeather,
      newVal => {
        newVal ? showWeatherPoints() : hideWeatherPoints()
      },
      {
        immediate: true,
      }
    )
  })

  return {
    showWeather,
  }
}

function showWeatherPoints() {
  subscriber = new Subscriber(viewer, {
    pickResult: {
      enable: true,
    },
  })
  weatherList.forEach(data => {
    const entity = createWeatherPoint(data)
    addEventSub(data.id, entity, data)
    weatherMap.set(data.id, entity)
  })
}

function hideWeatherPoints() {
  subscriber && subscriber.destroy()
  weatherMap.keys().forEach(key => {
    viewer.entities.remove(weatherMap.get(key))
    weatherMap.delete(key)
    if (popupMap.has(key)) {
      popupMap.get(key).windowClose()
      popupMap.delete(key)
    }
  })
}

function createWeatherPoint(data) {
  const { name, geom } = data
  const pos = parseWKT(geom).coordinates
  const entity = viewer.entities.add({
    name,
    position: Cesium.Cartesian3.fromDegrees(...pos),
    billboard: {
      image: '/images/icons/base/weather.png',
      width: 30,
      height: 30,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
    },
  })
  return entity
}

function addEventSub(
  id: string | number,
  entity: Cesium.Entity,
  data: Record<string, any>
) {
  subscriber &&
    subscriber.add(
      entity,
      (movement, entity) => {
        console.log(movement, entity, 'move')
        createPopup(id, entity.position, data)
      },
      'LEFT_CLICK'
    )
  // console.log(subscriber, '-------')
}

export { useWeather }
