<template>
  <div class="mapdata">
    <div id="container" ref="container" ></div>
    <div class="left">
      <div
        class="bottombtn"
        style="width: 100%; height: 35px; padding: 10px;display: flex;flex-direction: column;"
      >
        <!--        <el-button-->
        <!--          v-no-more-click-->
        <!--          @click="close"-->
        <!--          type="primary"-->
        <!--          icon="el-icon-close"-->
        <!--          style="align-self: flex-end;margin-top: 10px"-->
        <!--        >关闭-->
        <!--        </el-button>-->

        <el-button
          v-no-more-click
          @click="save"
          type="primary"
          icon="el-icon-check"
          style="align-self: flex-end;margin-top: 10px"
        >保存
        </el-button>


      </div>
    </div>


  </div>
</template>

<script>
import Konva from 'konva'
import { getIsMotorListByLotoId, updateIsMotorMove } from '@/api/mes/motor/index'
import { getIsMapPointPage, selectIsMapPointById, updateMapPointList } from '@/api/system/mappoint'
import { selectIsMapById } from '@/api/system/mapconfig'

export default {
  name: 'KonvaExample',
  data() {
    return {
      stage: null,
      layer: null,
      selectedStates: [], // 用于存储每个元素的选中状态
      selectedText: [], // 用于存储未选中的元素文本
      value: '',
      form: {}, //拿到单个数据
      groups: [], //组移动数据
      isSave: true,
      isInitialized: false, // 添加初始化标志
      imageUrl: '',//获取底图
      width: '',//底图宽
      height: '',//底图高
      x: '',//底图横坐标
      y: '',//底图纵坐标
      mapId: null,//地图Id
      mapType: 4,//地图类型
      pointList: null,//接口给的所有点位数据
      movePoints: [],//给地图点位界面更新位置
      lotoId: null,
    }
  },

  created() {
    this.isInitialized = true
  },

  mounted() {
    this.$nextTick(() => {
      this.getInfo()
    })
  },

  methods: {
    getInfo() {
      this.lotoId = this.$route.query.lotoId
      const motorMapId = this.$route.query.motorMapId
      this.mapId = motorMapId
      const lotoId = this.$route.query.lotoId
      const motorType=4

      const mapPromise = selectIsMapById(motorMapId).then((response) => {
        console.log(response, '获取底图')
        this.imageUrl = response.data.imageUrl
        this.width = response.data.width
        this.height = response.data.height
        this.x = response.data.x
        this.y = response.data.y
      })

      const pointPromise = getIsMotorListByLotoId({ lotoId,motorType }).then((response) => {
        console.log(response, '查询电机对应的锁定站的点位列表')
        this.pointList = response.data || []
      })

      Promise.all([mapPromise, pointPromise]).then(() => {
        // 数据准备好以后再渲染
        this.initKonva()
      })
    },

    close() {
      setTimeout(() => {
        this.getInfo()
        this.initKonva()
      }, 1000)
    },
    save() {
      this.$confirm('请确认是否保存修改内容', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let dataMap = {
            moveList: this.movePoints
          }
          console.log(dataMap, '先拿到数据看看再说')
          updateIsMotorMove(dataMap).then((res) => {
            console.log(res, '拿到的新绑定数据')
            this.movePoints = []
          })

          this.close()

        })
        .catch(() => {
          // 取消操作
        })
    },

    initKonva() {
      // 创建舞台
      this.stage = new Konva.Stage({
        container: this.$refs.container, // 容器元素
        width: 1700,
        height: 860,
      })

      // 创建图层
      this.layer = new Konva.Layer()
      // 绘制隔离点等其他内容
      this.drawGrid(10, 10, '#e0e0e0') // 每个单元格10x10，浅灰色网格
      // 创建物资柜底图
      const bgImage = new Image()
      const imageConfig = {
        x: this.x,
        y: this.y,
        width: this.width,
        height: this.height,
        draggable: false
      }
      bgImage.src = this.imageUrl

      bgImage.onload = () => {
        const knovaImage = new Konva.Image({
          ...imageConfig,
          image: bgImage
        })
        this.layer.add(knovaImage)

        // 渲染数据
        const imageSrc = require('@/assets/images/localSetIcon.jpg') // 图片路径
        this.renderGrid(imageSrc, 6, 3, 450, 100, 120, 100, 50, 50, 60, 25)

        // 将图层添加到舞台
        this.stage.add(this.layer)
        this.layer.draw()
      }

      // 禁止舞台拖拽
      this.stage.draggable(false)
    },

    // 绘制无限网格
    drawGrid(cellWidth, cellHeight, gridColor) {
      const width = 1700
      const height = 860

      // 绘制竖线
      for (let i = 0; i <= width; i += cellWidth) {
        const verticalLine = new Konva.Line({
          points: [i, 0, i, height],
          stroke: gridColor,
          strokeWidth: 1
        })
        this.layer.add(verticalLine)
      }

      // 绘制横线
      for (let j = 0; j <= height; j += cellHeight) {
        const horizontalLine = new Konva.Line({
          points: [0, j, width, j],
          stroke: gridColor,
          strokeWidth: 1
        })
        this.layer.add(horizontalLine)
      }


      this.layer.draw()
    },

    // 绘制柜内所有点
    renderGrid() {
      this.bgrects = {}
      this.selectedText = []
      this.movePoints = []

      const positions = this.pointList.map(item => ({
        entityId: item.motorId,
        entityName: item.motorCode,
        pointId: item.pointId,
        mapPointId: item.mapPointId,
        // 如果 x / y 为空则默认放置到 0,0
        x: item.x != null ? item.x : 0,
        y: item.y != null ? item.y : 0
      }))

      console.log(positions, 'positions')

      positions.forEach(pos => {
        const x = pos.x * 10
        const y = pos.y * 10
        const labelText = pos.entityName

        const group = new Konva.Group({
          x: x,
          y: y,
          draggable: true
        })

        // 用圆来展示点位
        const circle = new Konva.Circle({
          x: 15,
          y: 15,
          radius: 15,
          fill: '#16af5d',
          stroke: '#16af5d',
          strokeWidth: 2
        })

        const text = new Konva.Text({
          x: 0,
          y: 0,
          width: 30,
          height: 30,
          text: labelText,
          fontSize: 12,
          fontFamily: 'Calibri',
          fill: 'white',
          align: 'center',
          verticalAlign: 'middle'
        })

        group.add(circle)
        group.add(text)
        this.layer.add(group)

        // 监听拖动结束
        group.on('dragend', () => {
          const groupPos = group.getAbsolutePosition()

          const newRow = Math.max(0, Math.round(groupPos.x / 10))
          const newCol = Math.max(0, Math.round(groupPos.y / 10))

          const updatedPoint = {
            ...pos,
            x: newRow,
            y: newCol,
            mapId: this.mapId,
            mapType: this.mapType
          }

          // 更新 movePoints，用 entityId 作为唯一标识
          const existIdx = this.movePoints.findIndex(p => p.entityId === updatedPoint.entityId)
          if (existIdx !== -1) {
            // 已存在 -> 替换
            this.movePoints.splice(existIdx, 1, updatedPoint)
          } else {
            // 不存在 -> 添加
            this.movePoints.push(updatedPoint)
          }

          console.log(this.movePoints, '更新后的 movePoints')
        })


      })

      this.layer.draw()
    }

  }
}
</script>

<style scoped lang="scss">
#container {
  width: 100%;
  height: 100%;
}

.mapdata {
  width: 100%;
  height: 100%;
  display: flex;
}

.left {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  margin-bottom: 20px;
}
</style>
