<template>
  <div class="mapdata-container">
    <v-stage
      ref="stageRef"
      :config="stageConfig"
      @dragend="handleStageDragEnd"
    >
      <v-layer ref="layerRef">
        <!-- 网格 -->
        <v-line
          v-for="(line, index) in gridLines"
          :key="`grid-${index}`"
          :config="line"
        />

        <!-- 背景图片 -->
        <v-image
          v-if="backgroundImage"
          :config="backgroundImage"
        />

        <!-- 右侧盒子 -->
        <v-rect
          :config="rightBoxConfig"
        />
        <v-text
          :config="rightBoxTextConfig"
        />

        <!-- 隔离点 -->
        <v-group
          v-for="point in renderedPoints"
          :key="`point-${point.id}`"
          :config="point.groupConfig"
          @dragend="(e) => handlePointDragEnd(e, point)"
        >
          <v-rect :config="point.bgRectConfig" />
          <v-rect :config="point.rectConfig" />
<!--          <v-image :config="point.imageConfig" />-->
          <v-circle
            ref="lightRefs"
            :config="{
            x: point.lightConfig.x,
            y: point.lightConfig.y,
            radius: point.lightConfig.radius,
            fill: point.lightConfig.fill,
            stroke: point.lightConfig.stroke,
            strokeWidth: point.lightConfig.strokeWidth,
            shadowColor: point.lightConfig.shadowColor,
            shadowBlur: point.lightConfig.shadowBlur,
            shadowOffset: point.lightConfig.shadowOffset,
            shadowOpacity: point.lightConfig.shadowOpacity
          }"
            @mouseover="() => highlightLight(point)"
          />
          <v-text :config="point.textConfig" />
        </v-group>

        <!-- 右侧隔离点 -->
        <v-group
          v-for="(rightPoint, index) in rightPoints"
          :key="`right-point-${rightPoint.pointId}`"
          :config="getRightPointConfig(rightPoint, index)"
          @dragend="(e) => handleRightPointDragEnd(e, rightPoint)"
        >
          <v-rect :config="getRightPointRectConfig()" />
          <v-image :config="getRightPointImageConfig(rightPoint)" />
          <v-text :config="getRightPointTextConfig(rightPoint)" />
        </v-group>
      </v-layer>
    </v-stage>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import {  ElMessageBox } from 'element-plus'
import * as LotoStationApi from '@/api/dv/lotoStation/index'
import * as SegregationPointApi from '@/api/dv/spm/index'
import * as MapPointApi from '@/api/basic/mappoint/index'
import * as MapConfigApi from '@/api/basic/mapconfig/index'

defineOptions({ name: 'MapData' })

const route = useRoute()
const message = useMessage()

// 响应式数据
const stageRef = ref()
const layerRef = ref()

// 地图相关数据
const mapData = reactive({
  form: {} as any,
  originData: null as any,
  filterData: null as any,
  leftPoints: [] as any[],
  orgLeftPoints: [] as any[],
  rightPoints: [] as any[],
  orgRightPoints: [] as any[],
  groups: [] as any[],
  bindingPointIds: [] as string[],
  unbindPointIds: [] as string[],
  isSave: true,
  isInitialized: false,
  imageUrl: '',
  width: 0,
  height: 0,
  x: 0,
  y: 0,
  mapId: null as number | null,
  mapType: 2,
  pointList: null as any[] | null,

})

// 舞台配置
const stageConfig = reactive({
  width: 1600,
  height: 860,
  draggable: false
})

// 网格线配置
const gridLines = computed(() => {
  const lines = []
  const cellWidth = 50
  const cellHeight = 50
  const width = 1600
  const height = 860

  // 竖线
  for (let i = 0; i <= width; i += cellWidth) {
    lines.push({
      points: [i, 0, i, height],
      stroke: '#e0e0e0',
      strokeWidth: 1
    })
  }

  // 横线
  for (let j = 0; j <= height; j += cellHeight) {
    lines.push({
      points: [0, j, width, j],
      stroke: '#e0e0e0',
      strokeWidth: 1
    })
  }

  return lines
})

// 背景图片配置
const backgroundImage = computed(() => {
  console.log(mapData,'背景图')

  // 创建图片对象并设置src
  const img = new Image()
  img.src = mapData.imageUrl
  return {
    x: mapData.x,
    y: mapData.y,
    width: mapData.width,
    height: mapData.height,
    image: img,
    draggable: false
  }
})



// 渲染的点位数据
const renderedPoints = computed(() => {
  if (!mapData.pointList) return []

  return mapData.pointList.map((item: any) => {
    const x = item.x * 50
    const y = item.y * 50
    const labelText = item.entityName

    // 获取灯光配置
    const { lightColor, shadowColor, stroke, isRed, isGrey } = getLightConfig(item.switchStatus)

    return {
      id: item.id,
      pointId: item.entityId,
      entityName: item.entityName,
      originalData: item,
      groupConfig: {
        x: x,
        y: y,
        draggable: true
      },
      bgRectConfig: {
        x: -1,
        y: -5,
        width: 50,
        height: 78,
        cornerRadius: 5,
        stroke: 'white',
        strokeWidth: 2,
        fill: 'white'
      },
      rectConfig: {
        x: 1,
        y: -1,
        width: 45,
        height: 70,
        cornerRadius: 5,
        stroke: 'red',
        strokeWidth: 2,
        fill: 'white'
      },
      lightConfig: {
        x: 22.5,
        y: 25,
        radius: 12,
        fill: lightColor,
        stroke: stroke,
        strokeWidth: 2,
        shadowColor: shadowColor,
        shadowBlur: 5,
        shadowOffset: { x: 0, y: 0 },
        shadowOpacity: 0.8,
        isRed,
        isGrey
      },
      textConfig: {
        x: 8,
        y: 50,
        fontSize: 17,
        text: labelText,
        fontFamily: 'Calibri',
        fill: 'red'
      }
    }
  })
})
// 添加灯光配置获取函数
const getLightConfig = (switchStatus: string) => {
  let lightColor, shadowColor, stroke

  switch (switchStatus) {
    case "0": // 关闭状态
      lightColor = '#e0e0e0'
      shadowColor = '#e0e0e0'
      stroke = '#e0e0e0'
      break
    case "1": // 开启状态
      lightColor = '#0ea562'
      shadowColor = '#3ab890'
      stroke = '#3ab890'
      break
    default: // 未知状态
      lightColor = 'white'
      shadowColor = 'white'
      stroke = 'white'
  }

  return {
    lightColor,
    shadowColor,
    stroke,
    isRed: switchStatus === "0",
    isGrey: switchStatus == null
  }
}
// 获取作业区域信息
const getInfo = async () => {
  try {
    const lotoId = route.query.id as string
    const response = await LotoStationApi.selectIsLotoStationById(lotoId)
    console.log(response, '作业区域信息')

    mapData.form = response
    mapData.mapId = response.mapId

    // 获取底图信息
    const mapResponse = await MapConfigApi.selectIsMapById(response.mapId)
    console.log(mapResponse, '获取底图')

    mapData.imageUrl = mapResponse.imageUrl
    mapData.width = mapResponse.width
    mapData.height = mapResponse.height
    mapData.x = mapResponse.x
    mapData.y = mapResponse.y


    // 获取地图JSON数据
    const mapJsonResponse = await LotoStationApi.selectLotoMapById(lotoId, '', '')
    console.log(mapJsonResponse, '作业区域预览接口调用')

    mapData.form.map = mapJsonResponse
    mapData.filterData = mapJsonResponse
    if(mapResponse.pointList){
      mapData.pointList = mapResponse.pointList
    }else {
      mapData.pointList = mapJsonResponse
    }

    // 获取隔离点数据
    const pointData = {
      pageNo: 1,
      pageSize: -1,
      lotoId: route.query.id
    }

    const pointResponse = await SegregationPointApi.getIsIsolationPointPage(pointData)
    const data1 = pointResponse.list
    const data2 = mapData.filterData

    console.log(data1, '该柜子或地图所有点', data2, '该柜子里json拿到的点位')

    // 创建Set来存储已存在的pointId
    const data2PointIds = new Set(data2.map((item: any) => item.pointId))
    const pointListIds = new Set(mapData.pointList?.map((item: any) => item.pointId) || [])

    // 过滤掉已存在的点位
    const filterData = data1.filter(
      (item: any) => !data2PointIds.has(item.pointId) && !pointListIds.has(item.pointId)
    )

    console.log(filterData, 'filterData-交叉数据')

    mapData.orgLeftPoints = pointResponse.list.map((item: any) => ({
      pointId: item.pointId,
      entityId: item.pointId,
      entityName: item.pointName,
      pointName: item.pointName,
      remark: item.remark,
      prePointId: item.prePointId,
      pointType: item.pointType,
      pointTypeName: item.pointTypeName,
      powerType: item.powerType,
      powerTypeName: item.powerTypeName,
      pointIcon: item.pointIcon,
      status: false,
      pointPicture: item.pointPicture,
      mapImg: null
    }))

    if (mapJsonResponse) {
      try {
        mapData.originData = JSON.stringify(mapJsonResponse, null, 4)
      } catch (err) {
        console.error('JSON解析错误:', err)
      }
    }
  } catch (error) {
    console.error('获取信息失败:', error)
    message.error('获取信息失败')
  }
}

// 获取未绑定的所有隔离点
const getIsIsolationPointPage = async () => {
  try {
    const data = {
      pageNo: 1,
      pageSize: -1,
      lotoId: 0
    }

    const response = await SegregationPointApi.getIsIsolationPointPage(data)

    mapData.rightPoints = response.list.map((item: any) => ({
      entityId: item.pointId,
      entityName: item.pointName,
      pointId: item.pointId,
      pointName: item.pointName,
      remark: item.remark,
      prePointId: item.prePointId,
      pointType: item.pointType,
      pointTypeName: item.pointTypeName,
      powerType: item.powerType,
      powerTypeName: item.powerTypeName,
      pointIcon: item.pointIcon,
      status: false,
      pointPicture: item.pointPicture,
      mapImg: null,
      mapId: mapData.mapId,
      mapType: mapData.mapType
    }))

    mapData.orgRightPoints = JSON.parse(JSON.stringify(mapData.rightPoints))
  } catch (error) {
    console.error('获取隔离点失败:', error)
    message.error('获取隔离点失败')
  }
}
// 全局控制闪烁频率同步函数
// 响应式变量定义
const blinkLights = ref([])
const globalBlinkTimer = ref(null)
const startGlobalBlinkTimer = () => {
  if (globalBlinkTimer.value) return // 已经启动了

  globalBlinkTimer.value = setInterval(() => {
    const currentSecond = Math.floor(Date.now() / 200) % 2
    const isOn = currentSecond === 1

    blinkLights.value.forEach(light => {
      light.opacity(isOn ? 1 : 0.6)
      light.scale({ x: isOn ? 1 : 1.1, y: isOn ? 1 : 1.1 })
    })

    if (blinkLights.value.length > 0) {
      blinkLights.value[0].getLayer().batchDraw() // 统一刷新一次就行
    }
  }, 50)
}

// 绿灯动画
const addBlinkAnimation = (light, isRed, isGrey) => {
  if (!isGrey && !isRed) {
    if (!blinkLights.value.includes(light)) {
      blinkLights.value.push(light)
    }
    startGlobalBlinkTimer()
  }
}
// 添加灯光引用
const lightRefs = ref([])

// 高亮灯光效果
const highlightLight = (point) => {
  const light = lightRefs.value.find(l => l.getNode().id() === point.id)
  if (light) {
    light.getNode().to({
      scaleX: 1.2,
      scaleY: 1.2,
      duration: 0.3
    })
  }
}
// 在渲染后初始化闪烁效果
watch(renderedPoints, (newPoints) => {
  nextTick(() => {
    blinkLights.value = [] // 清空之前的灯光引用

    newPoints.forEach((point, index) => {
      const light = lightRefs.value[index]?.getNode()
      if (light) {
        // 确保lightConfig存在
        if (point.lightConfig) {
          addBlinkAnimation(light, point.lightConfig.isRed, point.lightConfig.isGrey)
        }
      }
    })
  })
}, { immediate: true })

// 组件挂载
onMounted(async () => {
  await nextTick()
  await getInfo()
  await getIsIsolationPointPage()
})
onUnmounted(async () => {
  if (globalBlinkTimer.value) {
    clearInterval(globalBlinkTimer.value)
    globalBlinkTimer.value = null
  }
})
</script>

<style scoped lang="scss">
.mapdata-container {
  width: 100%;
  height: 100%;
  display: flex;
}

</style>
