import SatelliteEntity from '@/js/SatelliteEntity'
import { difference } from 'lodash'
// import CreateFrustum from '@/js/Sensor'

interface ISatellite {
  name: string
  id: number | string
  tle: string
}

interface IBaseFilterParam {
  treeData: Array<any>
  params: Array<string | number>
  paramName: string
}
const satelliteList = ref<ISatellite[]>([])

// 保存分组的卫星实例
const satelliteMap = new Map()
export function useSatellite() {
  function addSatellites(ids: Array<string | number>) {
    const addIds = difference(ids, [...satelliteMap.keys()])
    const removeIds = difference([...satelliteMap.keys()], ids)

    if (addIds.length > 0) {
      const nodes = filterTreeNodeByField({
        treeData: satelliteList.value,
        params: addIds,
        paramName: 'id',
      })

      nodes.forEach(node => {
        const entity = addSatellite(node)
        satelliteMap.set(node.id, entity)
      })
    }

    removeIds.forEach(id => {
      removeSatellite(id)
    })
  }
  // 创建satellite entity 实例
  function addSatellite({ tle }: ISatellite) {
    const satellite = new SatelliteEntity(tle)
    const cesiumSateEntity = satellite.createSatelliteEntity()
    // const result = viewer.entities.add(cesiumSateEntity)

    // setTimeout(() => {
    //   satellite.sensor = true
    // }, 2000)
    // viewer.clock.multiplier = 100

    return cesiumSateEntity

    // let heading = 0
    // let pitch = 0
    // let roll = 0
    // let hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll)
    // let orientation = Cesium.Quaternion.fromHeadingPitchRoll(hpr)

    // // 创建视锥体
    // console.log(
    //   viewer.scene.canvas.clientWidth / viewer.scene.canvas.clientHeight,
    //   'viewer.scene.canvas.clientWidth / viewer.scene.canvas.clientHeight'
    // )
    // let createFrustum = new CreateFrustum({
    //   position: origin,
    //   orientation: orientation,
    //   fov: 30,
    //   near: 0.1,
    //   far: 10000,
    //   aspectRatio:
    //     viewer.scene.canvas.clientWidth / viewer.scene.canvas.clientHeight,
    // })
  }

  function removeSatellite(id: string | number) {
    if (satelliteMap.has(id)) {
      const satellite = satelliteMap.get(id)

      viewer.entities.remove(satellite)
      satelliteMap.delete(id)
    }
  }

  return { satelliteList, addSatellites }
}

function filterTreeNodeByField({
  treeData,
  params,
  paramName,
}: IBaseFilterParam): Array<ISatellite> {
  return treeData.reduce((acc, node) => {
    if (params.includes(node[paramName]) && !node.children) {
      acc.push(node)
    }
    if (node.children) {
      acc = acc.concat(
        filterTreeNodeByField({
          treeData: node.children,
          params,
          paramName,
        })
      )
    }
    return acc
  }, [])
}
