import { NAlert } from 'naive-ui'
import { watch, h } from 'vue'
import { useWebSocket } from '@vueuse/core'
import { parseWKT } from '@/utils/parseWKT'
import { speakText } from '@/utils/speak'
import { useEarth } from '@/views/Earth/hooks/earth'
// import url1 from '../assets/icons/star1.png'
// import url2 from '../assets/icons/star.png'
// import PS1 from '../assets/icons/PS.png'
// import PS2 from '../assets/icons/PS1.png'

import { getConfigs, getTextList } from '@/api/text'

interface point {
  position: Number[]
  entityType: String
  showOnEarthIconName: String
  showOnEarthTimeSec: Number
  toastMsgTimeSec: Number
}

const pointMap = new Map()
export const useTextReport = () => {
  const getTextConfigs = async () => {
    const res = await getConfigs()
    if (Array.isArray(res.data) && res.data.length > 0) {
      return res.data
    } else {
      return []
    }
  }

  const getTextReportList = async (type: string) => {
    const res = await getTextList(type)
    if (Array.isArray(res.data) && res.data.length > 0) {
      return res.data
    } else {
      return []
    }
  }

  const initWebSocket = () => {
    const {
      status: wsStatus,
      data: eventData,
      send,
      close,
    } = useWebSocket(`ws://192.168.10.187:8080/message/wzb`, {
      autoReconnect: {
        retries: 5,
        delay: 5000,
        onFailed: () => {
          console.log('连接失败')
        },
      },
      heartbeat: {
        message: 'ping',
        interval: 5000,
        pongTimeout: 10000,
      },
    })

    watch(wsStatus, newStatus => {
      switch (newStatus) {
        case 'OPEN':
          console.log('wzb ====> 连接成功')
          break
        case 'CLOSED':
          console.log('wzb ====> 连接关闭')
          break
        default:
          console.log('wzb ====> 连接中...')
          break
      }
    })

    watch(eventData, newEventData => {
      // console.log('eventData =====> ', typeof newEventData)

      if (typeof newEventData === 'string') {
        const newEventDataObj = JSON.parse(newEventData)
        if (newEventDataObj.code === '200') {
          const { data } = newEventDataObj
          // console.log('data =====> ', data)
          // speakText(data.title)

          const config = window.settings.textConfigs.find(
            item => data.entityType === item.id
          )

          createWarningMessage(data, config)

          createPointFromGeom(data, config)
        }
      }
    })
  }

  const { flyTo } = useEarth()
  const createWarningMessage = (data, config) => {
    const { toastMsgTimeSec, showOnEarthIconName } = config
    window.$message.warning(data.title, {
      duration: toastMsgTimeSec * 1000 || 10000,
      // duration: 200000,
      closable: true,
      icon: () =>
        h(
          'img',
          { src: `/images/icons/text/${showOnEarthIconName}.png` },
          { default: () => '' }
        ),
      render: props =>
        h(
          NAlert,
          {
            // bg-[#171c26]
            class: 'cursor-pointer',
            closable: props.closable,
            type: 'default',
            title: data.title,
            style: {
              boxShadow: 'var(--n-box-shadow)',
            },
            header: props.icon,
            onClick: () => flyToPosition(data.geom, props),
          },
          {
            icon: props.icon,
          }
        ),
    })
  }

  const flyToPosition = (geom: string, props) => {
    console.log(props)
    if (geom) {
      const [lon, lat] = parseWKT(geom).coordinates
      flyTo({ lon, lat })
    }
  }

  const createPointFromGeom = (data, config) => {
    const geom = parseWKT(data.geom)

    if (geom) {
      const point = createFlashPoint({
        position: geom.coordinates,
        entityType: data.entityType,
        ...config,
      })

      pointMap.set(data.id, point)
      // console.log(data, '------')
      setTimeout(() => {
        removePoint(data.id)
      }, config.showOnEarthTimeSec * 1000)
    }
  }

  const removePoint = (id: number) => {
    if (pointMap.has(id)) {
      const point = pointMap.get(id)
      viewer.entities.remove(point)
      pointMap.delete(id)
    }
  }

  const createFlashPoint = ({ position, showOnEarthIconName }: point) => {
    const [lon, lat] = position
    let x = 1
    let flag = true
    // let color = 'RED'

    const image1 = `/images/icons/text/${showOnEarthIconName}.png`
    const image2 = `/images/icons/text/${showOnEarthIconName}1.png`

    let image = image1
    const point = viewer.entities.add({
      name: '圆点point闪烁',
      position: Cesium.Cartesian3.fromDegrees(lon, lat),
      // point: {
      //   show: true, // default
      //   color: new Cesium.CallbackProperty(function () {
      //     if (flog) {
      //       x = x - 0.05
      //       if (x <= 0) {
      //         flog = false
      //         color = 'RED'
      //       }
      //     } else {
      //       x = x + 0.05
      //       if (x >= 1) {
      //         flog = true
      //         color = 'GREEN'
      //       }
      //     }
      //     return Cesium.Color[color]
      //   }, false),
      //   pixelSize: 10, // default: 1
      //   outlineWidth: 2,
      // },
      billboard: {
        image: new Cesium.CallbackProperty(function () {
          if (flag) {
            x = x - 0.05
            if (x <= 0) {
              flag = false
              image = image1
            }
          } else {
            x = x + 0.05
            if (x >= 1) {
              flag = true
              image = image2
            }
          }
          return image
        }, false),

        name: 'singleWarning',
        width: 25,
        height: 25,
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
          0,
          6.8e10
        ),
        // verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        // disableDepthTestDistance: Number.POSITIVE_INFINITY,
      },
    })

    return point
  }

  return { getTextConfigs, initWebSocket, getTextReportList }
}
