import { useWebSocket } from '@vueuse/core'
import { useHjPolygon } from './hangjingPolygon'
interface IPolygonData {
  id: string
  position: number[]
  color?: string
}

const hangjingMap: Map<string, any> = new Map()

const { addHangjingPolygon, removeHangjingPolygon } = useHjPolygon(hangjingMap)
export const useHangjing = () => {
  onMounted(() => {
    initWebSocket()
  })
  const addHangjing = (data: Record<string, any>[]) => {
    addHangjingPolygon(data)
  }

  const removeHangjing = (id: string) => {
    removeHangjingPolygon(id)
  }

  return {
    addHangjing,
    removeHangjing,
  }
}

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

  watch(wsStatus, newStatus => {
    switch (newStatus) {
      case 'OPEN':
        console.log('hj ====> 连接成功')
        break
      case 'CLOSED':
        console.log('hj ====> 连接关闭')
        break
      default:
        console.log('hj ====> 连接中...')
        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)
      }
    }
  })
}
