import Subscriber from '@cesium-extends/subscriber'
import chroma from 'chroma-js'
import { parseWKT } from '@/utils/parseWKT'
import { difference } from 'lodash'
import { polygonGradient } from '@/js/polygonGradient'
import { polygonMaterial } from '@/js/polygon'
import { centerOfMass } from '@turf/turf'

import { useHangjingPopup } from './hangjingPopup'

const { createPopup } = useHangjingPopup()

export const useHjPolygon = (polygonMap: Map<string | number, any>) => {
  let subscriber: Subscriber | null = null

  const colors = new Map()

  function addHangjingPolygon(data: Record<string, any>[]) {
    subscriber = new Subscriber(viewer, {
      pickResult: {
        enable: true,
      },
    })

    const ids = data.map(item => item.id)
    const addIds = difference(ids, [...polygonMap.keys()])
    const removeIds = difference([...polygonMap.keys()], ids)
    // 添加
    if (addIds.length > 0) {
      addIds.forEach(id => {
        const item = data.find(item => item.id === id)
        if (item) {
          if (item.zoneList.length > 0) {
            item.zoneList.forEach(zone => {
              addPolygon(zone, id)
            })
          } else {
            addPolygon(item)
          }
        }
      })
    }
    // 删除
    if (removeIds.length > 0) {
      console.log(removeIds, 'removeIds')
      removeIds.forEach(id => {
        removeEventSub(polygonMap.get(id))
        removeHangjingPolygon(id)
      })
    }
  }

  function addPolygon(item, parentId: number | null = null) {
    const { id, geom } = item
    const feature = parseWKT(geom)
    const position = feature.coordinates[0].map(pos => {
      return Cesium.Cartesian3.fromDegrees(...pos)
    })

    // console.log(item, id, position, 'id, position, color')
    // const randomColor =
    //   '#' + Math.random().toString(16).substring(2, 8).padEnd(6, '0')

    // if (!colors.has(id)) {
    //   const randomColor = chroma.random().alpha(0.5).hex()
    //   colors.set(id, randomColor)
    // }
    // if (zoneId) {
    //   if()
    // }
    const curId = parentId || id

    if (!colors.has(curId)) {
      const randomColor = chroma.random().brighten().alpha(0.6).hex()
      colors.set(curId, randomColor)
    }
    const color = colors.get(curId)

    const polygon = addPrimitivePolygon({
      id,
      color: color,
      position,
    })

    const centerPoint = centerOfMass(feature).geometry.coordinates
    addEventSub({
      parentId,
      id,
      entity: polygon,
      hjData: { ...item, centerPoint },
    })
    if (parentId) {
      if (polygonMap.get(parentId)) {
        polygonMap.get(parentId).push(polygon)
      } else {
        polygonMap.set(parentId, [polygon])
      }
    } else {
      polygonMap.set(id, polygon)
    }

    // console.log(polygonMap, 'polygonMap')
  }

  function addPrimitivePolygon({
    id,
    position,
    color,
  }: {
    id: string
    position: Cesium.Cartesian3[]
    color: string
  }): Cesium.Primitive {
    // const polygonOptions = {
    //   extrudedHeight: 5000,
    //   polygonHierarchy: new Cesium.PolygonHierarchy(position),
    // }

    // const geometry = new Cesium.PolygonGeometry(polygonOptions)

    // const geometryInstance = new Cesium.GeometryInstance({
    //   geometry: geometry,
    //   id,
    // })

    // const primitive = new Cesium.Primitive({
    //   releaseGeometryInstances: false,
    //   asynchronous: false,
    //   geometryInstances: [geometryInstance],
    //   appearance: new Cesium.EllipsoidSurfaceAppearance({
    //     material: polygonGradient(color),
    //   }),
    // })
    // return viewer.scene.primitives.add(primitive)

    return viewer.entities.add({
      id,
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(position),
        // material: Cesium.Color.fromCssColorString(color),
        material: polygonMaterial(color),
        // material: polygonGradient(color),
        // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      },
    })
  }
  function removeHangjingPolygon(id: string) {
    if (polygonMap.has(id)) {
      const polygon = polygonMap.get(id)
      if (polygon instanceof Array) {
        polygon.forEach(item => {
          // viewer.scene.primitives.remove(item)
          viewer.entities.remove(item)
        })
      } else {
        // viewer.scene.primitives.remove(polygonMap.get(id))
        viewer.entities.remove(polygonMap.get(id))
      }
      // viewer.entities.remove(hangjingMap.get(id))
      polygonMap.delete(id)
    }
  }

  function addEventSub({
    parentId,
    id,
    entity,
    hjData,
  }: {
    parentId: number | null
    id: number
    entity: Cesium.Entity
    hjData: Record<string, any>
  }) {
    subscriber &&
      subscriber.add(
        entity,
        (movement, entity) => {
          // console.log(movement, 'movement')
          // console.log(hjData, 'hjData')
          const position = Cesium.Cartesian3.fromDegrees(...hjData.centerPoint)
          ;(polygonMap.has(id) || polygonMap.has(parentId)) &&
            createPopup(id, { _value: position }, hjData)
        },
        'LEFT_CLICK'
      )
    // console.log(subscriber, '-------')
  }

  function removeEventSub(entity: Cesium.Entity) {
    subscriber && subscriber.remove(entity, 'LEFT_CLICK')
  }
  return {
    addHangjingPolygon,
    removeHangjingPolygon,
  }
}
