<template>
  <div class="mapdata">
    <div id="container" ref="container" style="width:1200px"></div>
    <div class="left">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span style="font-size: 18px">地图预览</span>
          <span
            style="
                float: right;
                padding: 1px 0;
                font-size: 22px;
                cursor: pointer;
              "
            type="text"
            @click="goBack"
          >×</span
          >
        </div>
        <div style="height: 100%;padding-bottom:10px">
          <el-input v-model="value" type="textarea" :rows="34" ></el-input>

        </div>
        <div class="bottombtn" style="width:100%;height: 35px;padding: 10px 0 0">
        <el-button v-no-more-click @click="save" type="primary" icon="el-icon-edit" style="float: right; height: 33px; line-height: 2px">保存</el-button>
        <el-button v-no-more-click @click="reset" type="primary" icon="el-icon-refresh"  style="float: right; height: 33px; line-height: 2px;margin: 0 10px">重置</el-button>
        <el-button v-no-more-click @click="view" type="primary" icon="el-icon-view" style="float: right; height: 33px; line-height: 2px">预览</el-button>
        </div>
      </el-card>

    </div>
  </div>

</template>

<script>
import Konva from "konva";
import { getWorkareaInfo,updateWorkarea,getMapDataApi } from '@/api/mes/wa/workarea'

export default {
  name: "KonvaExample",
  data() {
    return {
      stage: null,
      layer: null,
      selectedStates: [], // 用于存储每个元素的选中状态
      selectedText: [], // 用于存储未选中的元素文本
      rects: [], // 白色r        ect合集
      texts: [], // 白色text合集
      redrects: [], // 红色rect合集
      redtexts: [], // 白色text合集
      value:'',
      form:{},//拿到单个数据
      orignData:null,//原始数据
    };
  },
  watch:{
    '$route.query.workareaId':{
      handler(newValue){
        if(newValue){
          this.getWorkAreaInfo()
          this.initKonva();
        }
      }
    }
  },
  mounted() {
    this.$nextTick(()=>{
      this.getWorkAreaInfo()
    })
    console.log(this.$route.query.workareaId,'workareaId');
  },

  methods: {
    goBack(){
      this.$router.push('/mes/md/workarea');
    },
    getWorkAreaInfo(){
      const workareaId=this.$route.query.workareaId;
      const sopId=''
      const ticketId=''
      getWorkareaInfo(workareaId).then((response) => {
        console.log(response,'作业区域信息')
        this.form=response.data
      })
      getMapDataApi(workareaId,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();
        // console.log(this.value,'Value')
      })
    },
    // 重置
    reset(){
      this.value = this.orignData;
      this.initKonva(); // 重新初始化 Konva
    },
    // 预览
    view(){
      if(this.isJson(this.value)){
        this.form.map=this.value
        this.initKonva();
      }else {
        this.$message({
          type: 'error',
          message: '地图数据格式不正确，请输入有效的 JSON 格式!'
        });
      }
    },
    save() {
      this.$confirm('请确认是否保存修改内容', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 校验 this.value 是否为有效的 JSON
        if (this.isJson(this.value)) {
          const mapData = typeof this.value === 'string' ? this.value : JSON.stringify(this.value);
          const formData = {
            ...this.form,
            map: mapData
          };
          console.log( formData,'map')
          updateWorkarea(formData).then(response => {
            console.log(response, '修改车间区域地图');
            this.$router.push('/mes/md/workarea');
            this.$message({
              type: 'success',
              message: '保存成功!'
            });
          });
        } else {
          this.$message({
            type: 'error',
            message: '地图数据格式不正确，请输入有效的 JSON 格式!'
          });
        }
      }).catch(() => {
        // 取消操作
      });
    },

    // 校验字符串是否为有效的 JSON
    isJson(str) {
      try {
        JSON.parse(str);
        return true;
      } catch (e) {
        return false;
      }
    },
    initKonva() {
      // 创建舞台
      this.stage = new Konva.Stage({
        container: this.$refs.container, // 容器元素
        width: 1200,
        height: 860,
      });

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

      // 创建底图
      const bgImage = new Image();
      bgImage.src = require("@/assets/images/table.png");
      bgImage.onload = () => {
        const knovaImage = new Konva.Image({
          x: 330,
          y: 10,
          image: bgImage,
          width: 500,
          height: 790,
          draggable: false,
        });
        this.layer.add(knovaImage);
        this.layer.draw();
      };

      // 绘制无限网格
      this.drawGrid(50, 50, "#e0e0e0"); // 每个单元格50x50，浅灰色网格

      // 渲染数据
      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 = 1200;
      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(imageSrc) {
      this.selectedStates = []; // 用数组来存储选中状态
      this.rects = [];
      this.texts = [];
      this.bgrects={}
      this.redrects = [];
      this.redtexts = [];
      this.selectedText = [];

      const positions=JSON.parse(this.value)

      positions.forEach((pos, index) => {
        const x = pos.col * 50; // 每个单元格宽度为50
        const y = pos.row * 50; // 每个单元格高度为50
        const labelText = pos.pointName; // 对应的文字

        const point = new Image();
        point.src=pos.pointIcon
        // point.src = imageSrc;
        point.onload = () => {
          const knovaImage = new Konva.Image({
            x: x,
            y: y,
            image: point,
            width: 50,
            height: 50,
            draggable: false,
          });


          // 底部白色背景
          const bgrect=new Konva.Rect({
            x: x - 6,
            y: y - 5,
            width: 62,
            height: 80,
            cornerRadius: 5,
            stroke: 'white',
            strokeWidth: 2,
            fill: 'white'
          })
          this.layer.add(bgrect)
          this.bgrects[labelText] = bgrect // 用文字作为键存储

          // 普通矩形
          const rect = new Konva.Rect({
            x: x + 0,
            y: y - 1,
            width: 50,
            height: 72,
            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 + 50,
            fontSize: 20,
            text: labelText,
            fontFamily: 'Calibri',
            fill: 'red'
          })
          this.layer.add(text)
          this.texts[labelText] = text // 用文字作为键存储

          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>
