import { onMounted, ref } from 'vue'
import Subscriber from '@cesium-extends/subscriber'
import { difference } from 'lodash'
import { getSheshi } from '@/api/Sheshi'
import { useTree } from '@/utils/tree'
import { parseWKT } from '@/utils/parseWKT'
import { useBasePopup } from './basePopup'

const typeDict: Record<string, string> = {
  base: '/images/icons/base/base1.png',
  airport: '/images/icons/base/airport1.png',
  port: '/images/icons/base/port1.png',
  station: '/images/icons/base/station1.png',
}

const treeData = ref([])

const baseMap = new Map()

// const allKeys = computed(() => getAllKeys(treeData))
const allKeys = ref([])

let subscriber: Subscriber | null = null

const { filterTreeNodeByField } = useTree()

const { popupMap, createPopup } = useBasePopup()
export const useBase = () => {
  onMounted(async () => {
    await getSheshiData()
    allKeys.value = getAllKeys(treeData.value)
  })
  const addBaseFacilities = (ids: Array<string | number>) => {
    subscriber = new Subscriber(viewer, {
      pickResult: {
        enable: true,
      },
    })
    const addIds = difference(ids, [...baseMap.keys()])
    const removeIds = difference([...baseMap.keys()], ids)
    // console.log('addIds=>', addIds, 'removeIds=>', removeIds)
    if (addIds.length > 0) {
      const nodes = filterTreeNodeByField({
        treeData: treeData.value,
        params: addIds,
        paramName: 'dataId',
      })

      // console.log(nodes, '====')
      nodes.forEach(({ data, dataId }: TBase) => {
        const entity = addEntity(data)

        addEventSub(dataId, entity, data)
        baseMap.set(dataId, entity)
      })
    }

    removeIds.forEach(id => {
      removeEntity(id)
    })
  }

  return {
    treeData,
    allKeys,
    addBaseFacilities,
  }
}

async function getSheshiData() {
  const baseRes = await getSheshi()

  const { code, data } = baseRes
  if (code === '200') {
    // console.log(data, 'baseRes')
    treeData.value = [data]
  }
}

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

function getAllKeys(treeData: any) {
  const data = 'value' in treeData ? treeData.value : treeData

  return data.reduce((acc, node) => {
    // console.log(node, '---')
    acc.push(node.dataId)
    if (node.children) {
      acc = acc.concat(getAllKeys(node.children))
    }
    return acc
  }, [])
}

function addEntity(data: TBaseNode) {
  const { sheShiName, sheShiType, geom } = data
  const pos = parseWKT(geom).coordinates
  const entity = viewer.entities.add({
    name: sheShiName,
    position: Cesium.Cartesian3.fromDegrees(...pos),
    // label: {
    //   text: `${sheShiName}`,
    //   font: '12pt sans-serif',
    //   fillColor: Cesium.Color.YELLOW,
    //   outlineColor: Cesium.Color.BLACK,
    //   outlineWidth: 2,
    //   style: Cesium.LabelStyle.FILL_AND_OUTLINE,
    //   pixelOffset: new Cesium.Cartesian2(20, -20),
    //   disableDepthTestDistance: Number.POSITIVE_INFINITY,
    // },
    billboard: {
      image: typeDict[sheShiType],
      width: 30,
      height: 30,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
    },
  })
  return entity
}

function removeEntity(id: string | number) {
  if (baseMap.has(id)) {
    viewer.entities.remove(baseMap.get(id))
    baseMap.delete(id)
  }

  if (popupMap.has(id)) {
    popupMap.get(id).windowClose()
    popupMap.delete(id)
  }
}
