<template>
  <div class="mapdata">
    <div id="container" ref="container" style="width: 300px"></div>
  </div>
</template>

<script>
import Konva from "konva";
import { getLotoMapInfo, getLotoInfo } from "@/api/mes/lotoStation/lotoStation";
import { getTechnologyInfo } from "@/api/system/machinery";
export default {
  name: "KonvaExample",
  props: {
    machineryId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      stage: null,
      layer: null,
      selectedStates: [], // 用于存储每个元素的选中状态
      selectedText: [], // 用于存储未选中的元素文本
      rects: [], // 白色r        ect合集
      texts: [], // 白色text合集
      redrects: [], // 红色rect合集
      redtexts: [], // 白色text合集
      value: "",
      form: {}, //拿到单个数据
      orignData: null, //原始数据
      pointIdList: [], //选中的隔离点
      selectPoints: [], //回显之前选中的隔离点
    };
  },
  watch: {
    machineryId: {
      handler(newValue) {
        if (newValue) {
          console.log(this.machineryId, "Mapdata拿到的父组件machineryId");
          this.getLoToInfo();
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.$nextTick(() => {
      if (this.machineryId) {
        this.getLoToInfo();
        const machineryId = this.machineryId;
        console.log(machineryId, "Mapdata拿到的父组件传递数据");
      }
    });
  },

  methods: {
    getLoToInfo() {
      const machineryId = this.machineryId;
      getTechnologyInfo(machineryId).then((response) => {
        const lotoId = response.data.lotoId;
        const sopId = "";
        const ticketId = "";
        getLotoInfo(lotoId).then((response) => {
          console.log(response, "电柜信息");
          this.form = response.data;
        });
        getLotoMapInfo(lotoId, sopId, ticketId).then((response) => {
          console.log(response, "电柜预览接口调用");
          this.form.map = response.data;

          if (response.data) {
            try {
              this.value = JSON.stringify(response.data, null, 4);
              this.orignData = this.value;
            } catch (err) {}
          }
          this.initKonva();
        });
      });

      //   设备工艺详情
      getTechnologyInfo(this.machineryId).then((response) => {
        console.log(response, "设备/工艺详情");
        this.selectPoints = response.data.pointIdList;
      });
    },

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

      // 创建底图图层
      this.bgLayer = new Konva.Layer();

      // 创建底图
      const bgImage = new Image();
      bgImage.src = require("@/assets/images/table.png");
      bgImage.onload = () => {
        const knovaImage = new Konva.Image({
          x: 50,
          y: -25,
          image: bgImage,
          width: 220,
          height: 410,
          draggable: false,
        });
        this.bgLayer.add(knovaImage);
        this.bgLayer.draw(); // 绘制底图图层
      };

      // 将底图图层添加到舞台
      this.stage.add(this.bgLayer);

      // 创建点位图层
      this.layer = new Konva.Layer();

      // 将点位图层添加到舞台
      this.stage.add(this.layer);

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

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

    renderGrid(imageSrc) {
      this.selectedStates = []; // 用数组存储选中状态
      this.rects = {};
      this.texts = {};
      this.bgrects = {};
      this.redrects = {};
      this.redtexts = {};
      this.selectedText = [];
      this.pointIdList = []; // 初始化选中的点ID列表

      const positions = JSON.parse(this.value); // 获取点位数据

      // **计算柜子的布局范围**
      const cabinetWidth = this.stage.width(); // 柜子的宽度
      const cabinetHeight = this.stage.height(); // 柜子的高度
      const cols = Math.max(...positions.map((p) => p.col)) + 1; // 根据数据动态计算总列数
      const rows = Math.max(...positions.map((p) => p.row)) + 1; // 根据数据动态计算总行数
      // 调整横向和纵向间距
      const horizontalSpacingFactor = 1.032; // 横向间距放大倍数
      const verticalSpacingFactor = 0.53; // 纵向间距缩小倍数

      const cellWidth = (cabinetWidth / cols) * horizontalSpacingFactor; // 调整横向间距
      const cellHeight = (cabinetHeight / rows) * verticalSpacingFactor; // 调整纵向间距

      // 遍历点位，按行列布局计算位置
      positions.forEach((pos) => {
        const col = pos.col; // 当前点位的列
        const row = pos.row; // 当前点位的行

        // 计算点位的实际位置，确保它们位于柜子显示区域内
        const x = col * cellWidth - 100;
        const y = row * cellHeight - 30;

        const labelText = pos.pointName; // 对应的文字

        const point = new Image();
        point.src = pos.pointIcon;
        point.onload = () => {
          const knovaImage = new Konva.Image({
            x: x + 6, // 适当的偏移确保点位不重叠
            y: y + 6, // 适当的偏移确保点位不重叠
            image: point,
            width: 19,
            height: 18,
            draggable: false,
          });

          // **绘制背景矩形**（以单元格大小为基础）
          const bgrect = new Konva.Rect({
            x: x,
            y: y,
            width: 30,
            height: 36,
            cornerRadius: 5,
            stroke: "white",
            strokeWidth: 2,
            fill: "white",
          });
          this.layer.add(bgrect);
          this.bgrects[labelText] = bgrect;

          // **普通矩形边框**（同样按照单元格尺寸）
          const rect = new Konva.Rect({
            x: x + 4,
            y: y + 4,
            width: 30 - 8,
            height: 36 - 8,
            cornerRadius: 5,
            stroke: "red",
            strokeWidth: 2,
            fill: "white",
          });
          this.layer.add(rect);
          this.rects[labelText] = rect;

          // 添加图片
          this.layer.add(knovaImage);

          // **绘制点位的文字**（确保与背景矩形不重叠）
          const text = new Konva.Text({
            x: x + 8, // 适当的偏移，确保文字不与背景矩形重叠
            y: y + 43 - 20, // 文字放在底部
            fontSize: 8,
            text: labelText,
            fontFamily: "Calibri",
            fill: "red",
          });
          this.layer.add(text);
          this.texts[labelText] = text;

          // **选中覆盖矩形**（保持与背景矩形相同的尺寸）
          const redrect = new Konva.Rect({
            x: x,
            y: y,
            width: 30,
            height: 36,
            cornerRadius: 5,
            fill: "rgba(97, 97, 97, 0.5)", // 半透明灰色
            visible: false, // 初始状态隐藏
            listening: false,
          });
          this.layer.add(redrect);
          this.redrects[labelText] = redrect;

          // **对号文字（表示选中）**
          const redtext = new Konva.Text({
            x: x + 30 / 2 - 5, // 水平居中
            y: y + 36 / 2 - 5, // 垂直居中
            fontSize: 13,
            text: "✔",
            fontFamily: "Arial",
            fill: "white",
            align: "center",
            visible: false, // 初始隐藏状态
            listening: false,
          });
          this.layer.add(redtext);
          this.redtexts[labelText] = redtext;

          // 如果初始化时有选中的点位
          if (
            Array.isArray(this.selectPoints) &&
            this.selectPoints.length > 0
          ) {
            if (this.selectPoints.includes(pos.pointId)) {
              // 设置选中状态
              this.redrects[labelText].visible(true);
              this.redtexts[labelText].visible(true);
              this.pointIdList.push(pos.pointId); // 添加ID
            }
          }

          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;
}
</style>
