<template>
  <div class="mapdata">
    <v-stage
      ref="stageRef"
      :config="{ width: stageWidth, height: stageHeight }"
      class="konva-container"
    >
      <!-- 网格层 -->
      <v-layer>
        <v-line
          v-for="(line, index) in gridLines"
          :key="index"
          :config="line"
        />
      </v-layer>

      <!-- 背景图层 -->
      <v-layer>
        <v-image :config="bgImageConfig" />
      </v-layer>

      <!-- 点位图层 -->
      <v-layer>
        <template v-for="point in pointList" :key="point.entityId">
          <v-rect :config="getBgRectConfig(point)" />
          <v-image :config="getImageConfig(point)" @click="() => toggleSelect(point)" />
          <v-text :config="getTextConfig(point)" />
          <v-rect v-if="isSelected(point.entityId)" :config="getOverlayConfig(point)" />
          <v-text v-if="isSelected(point.entityId)" :config="getCheckTextConfig(point)" />
        </template>
      </v-layer>
    </v-stage>

    <div class="action-bar">
      <el-button
        v-no-more-click
        @click="handleSave"
        type="primary"
        :icon="Check"
        class="action-btn save-btn"
      >
        保存配置
      </el-button>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from 'vue-i18n'
import {
  Check,
} from '@element-plus/icons-vue'
import * as TechnologyApi from '@/api/dv/technology'
import * as LotoApi from '@/api/dv/lotoStation'
import * as MapApi from '@/api/basic/mapconfig'

const route = useRoute()
const message = useMessage()
const { t } = useI18n()

const stageRef = ref()
const stageWidth = 1600
const stageHeight = 860

const formData = ref({
  imageUrl: '',
  width: 1200,
  height: 860,
  x: 0,
  y: 0,
  pointList: [] as any[],
})

const pointIdList = ref<number[]>([])
const selectPoints = ref<number[]>([])

const pointList = computed(() => formData.value.pointList)

onMounted(async () => {
  const techRes = await TechnologyApi.getTechnologyInfo(route.query.machineryId as string)
  const lotoId = techRes.lotoId
  const lotoRes = await LotoApi.selectIsLotoStationById(lotoId)
  const mapRes = await MapApi.selectIsMapById(lotoRes.mapId)
  console.log(mapRes,'mapRes')
  // 关键：设置选中点
  if(techRes.pointIdList!==null){
    pointIdList.value = [...techRes.pointIdList]  // 替换这里！
  }
  formData.value = {
    ...formData.value,
    ...lotoRes.data,
    imageUrl: mapRes.imageUrl,
    width: mapRes.width,
    height: mapRes.height,
    x: mapRes.x,
    y: mapRes.y,
    pointList: mapRes.pointList
  }
})

const gridLines = computed(() => {
  const lines = []
  const cellSize = 50
  for (let i = 0; i <= stageWidth; i += cellSize) {
    lines.push({ points: [i, 0, i, stageHeight], stroke: '#e0e0e0', strokeWidth: 1 })
  }
  for (let j = 0; j <= stageHeight; j += cellSize) {
    lines.push({ points: [0, j, stageWidth, j], stroke: '#e0e0e0', strokeWidth: 1 })
  }
  return lines
})

const bgImageConfig = computed(() => {
  const image = new window.Image()
  image.src = formData.value.imageUrl
  return {
    image,
    x: formData.value.x,
    y: formData.value.y,
    width: formData.value.width,
    height: formData.value.height,
    draggable: false
  }
})

const imageCache = new Map<string, HTMLImageElement>()

const getImageConfig = (point: any) => {
  let img = imageCache.get(point.pointIcon)
  if (!img) {
    img = new window.Image()
    img.src = point.pointIcon
    imageCache.set(point.pointIcon, img)
  }
  return {
    image: img,
    x: point.x * 50,
    y: point.y * 50,
    width: 45,
    height: 45,
    draggable: false
  }
}


const getBgRectConfig = (point: any) => ({
  x: point.x * 50 - 2,
  y: point.y * 50 - 5,
  width: 50,
  height: 78,
  cornerRadius: 5,
  stroke: 'red',
  strokeWidth: 2,
  fill: 'white'
})

const getTextConfig = (point: any) => ({
  x: point.x * 50 + 8,
  y: point.y * 50 + 50,
  fontSize: 17,
  text: point.entityName,
  fontFamily: 'Calibri',
  fill: 'red'
})

const getOverlayConfig = (point: any) => ({
  x: point.x * 50 - 3,
  y: point.y * 50 - 6,
  width: 52,
  height: 80,
  cornerRadius: 5,
  fill: 'rgba(97, 97, 97, 0.5)',
  listening: false
})

const getCheckTextConfig = (point: any) => ({
  x: point.x * 50 + 13,
  y: point.y * 50 + 25,
  fontSize: 24,
  text: '✔',
  fontFamily: 'Arial',
  fill: 'white',
  align: 'center',
  verticalAlign: 'middle',
  listening: false
})

const isSelected = (id: number) => pointIdList.value.includes(id)

const toggleSelect = (point: any) => {
  const idx = pointIdList.value.indexOf(point.entityId)
  if (idx >= 0) {
    pointIdList.value.splice(idx, 1)
  } else {
    pointIdList.value.push(point.entityId)
  }
}

const handleSave = async () => {
  await message.confirm('请确认是否保存修改内容')
  const data = {
    machineryId: route.query.machineryId,
    pointIdList: pointIdList.value
  }
  await TechnologyApi.saveMachineryPoints(data)
  message.success(t('common.saveSuccess'))
}
</script>

<style scoped lang="scss">
.mapdata {
  display: flex;
  width: 100%;
  height: 100%;
}
.konva-container {
  width: 1600px;
  height: 860px;
}
/* 按钮样式 */
.action-btn {
  height: 44px;
  min-width: 120px;
  font-size: 16px;
  font-weight: bold;
  border-radius: 8px !important;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.2s;
}

.save-btn {
  background: linear-gradient(135deg, #409EFF, #3375e0);
  border: none;
  margin: 10px 0px 10px 10px;

}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.action-btn:active {
  transform: translateY(0);
}
</style>
