<template>
  <div style="overflow:hidden;">
    <div class="top">
      <div style="line-height: 60px;margin-left: 12px;">
        <el-button-group>
          <el-button :type="pageType === 'A3' ? 'primary' : ''" @click="setPage('A3',42,29.7)">A3</el-button>
          <el-button :type="pageType === 'A4' ? 'primary' : ''" @click="setPage('A4',21,29.7)">A4</el-button>
          <el-button :type="pageType === 'A5' ? 'primary' : ''" @click="setPage('A5',14.8,21)">A5</el-button>
          <el-button :type="pageType === 'B3' ? 'primary' : ''" @click="setPage('B3',35.3,50)">B3</el-button>
          <el-button :type="pageType === 'B4' ? 'primary' : ''" @click="setPage('B4',25,35.2)">B4</el-button>
          <el-button :type="pageType === 'B5' ? 'primary' : ''" @click="setPage('B5',17.6,25)">B5</el-button>
          <el-button :type="pageType === 'zdy' ? 'primary' : ''" @click="setPage('zdy')">自定义</el-button>
        </el-button-group>
        <el-input-number :disabled="pageType !== 'zdy'" v-model="pageWidth" style="width: 80px;margin-left: 8px;"
                         :min="0" :controls="false" />
        <span style="margin: 0 8px">x</span>
        <el-input-number :disabled="pageType !== 'zdy'" v-model="pageHeight" style="width: 80px" :min="0"
                         :controls="false" />
        <el-button @click="zoomChange(-0.1)" icon="ZoomOut" circle style="margin-left: 12px;" />
        <el-input v-model="zoomInput" disabled style="margin-left: 8px;width:100px" />
        <el-button @click="zoomChange(0.1)" icon="ZoomIn" circle style="margin-left: 8px;" />
        <el-button type="primary" @click="view" style="margin-left: 12px;">预览</el-button>
        <el-button type="primary" @click="imp" style="margin-left: 12px;">场景1</el-button>
        <el-button type="primary" @click="save" style="margin-left: 12px;">保存</el-button>
        <el-button type="primary" @click="clear" style="margin-left: 12px;">清空</el-button>
      </div>
    </div>
    <div class="bottom">
      <div class="leftPanel">
        <h4>基础组件</h4>
        <el-tag :draggable="true" @dragstart="onDragStart($event, 'text',pid)" class="mx-1" size="large">文字</el-tag>
        <el-tag :draggable="true" @dragstart="onDragStart($event, 'image',pid)" class="mx-1" size="large">图片</el-tag>
        <el-tag :draggable="true" @dragstart="onDragStart($event, 'barCode',pid)" class="mx-1" size="large">条形码
        </el-tag>
        <el-tag :draggable="true" @dragstart="onDragStart($event, 'QRCode',pid)" class="mx-1" size="large">二维码
        </el-tag>
        <el-tag :draggable="true" @dragstart="onDragStart($event, 'dateTime',pid)" class="mx-1" size="large">日期时间
        </el-tag>
        <el-tag :draggable="true" @dragstart="onDragStart($event, 'select',pid)" class="mx-1" size="large">可选择
        </el-tag>
        <el-tag :draggable="true" @dragstart="onDragStart($event, 'inputNode',pid)" class="mx-1" size="large">可输入
        </el-tag>
        <!--        <el-tag :draggable="true" @dragstart="onDragStart($event, 'box',pid)" class="mx-1" size="large">方形框-->
        <!--        </el-tag>-->
        <!--        <el-tag :draggable="true" @dragstart="onDragStart($event, 'transverseLine',pid)" class="mx-1" size="large">横线-->
        <!--        </el-tag>-->
        <!--        <el-tag :draggable="true" @dragstart="onDragStart($event, 'verticalLine',pid)" class="mx-1" size="large">竖线-->
        <!--        </el-tag>-->
        <!--        <el-tag :draggable="true" @dragstart="onDragStart($event, 'rectangle',pid)" class="mx-1" size="large">矩形-->
        <!--        </el-tag>-->
        <!--        <el-tag :draggable="true" @dragstart="onDragStart($event, 'circle',pid)" class="mx-1" size="large">圆形-->
        <!--        </el-tag>-->
        <h4>表单组件</h4>
        <el-tag :draggable="true" @dragstart="onDragStart($event, 'text',pid,{name:'deviceName'})" class="mx-1"
                size="large">
          设备名称
        </el-tag>
      </div>
      <div class="content" @drop="onDrop">
        <div class="flowArea" :style="{width:zoom * cmToPx(pageWidth)+'px',height:zoom * cmToPx(pageHeight)+'px'}">
          <VueFlow :autoPanSpeed="0" :min-zoom="0.01" ref="flowRef" v-model:nodes="nodes" v-model:edges="edges"
                   :zoomOnScroll="false"
                   :snapToGrid="isSnapToGrid" :snapGrid="[cmToPx(0.5), cmToPx(0.5)]"
                   :panOnDrag="false"
                   fit-view-on-init
                   default-marker-color="#409EFF"
                   @selectionEnd="logEvent('selectionEnd', $event)"
                   @dragover="onDragOver"
                   @node-click="logEvent('click', $event)"
                   @pane-click="logEvent('paneClick', $event)"
                   @node-drag-start="logEvent('nodeDrag', $event)"
                   @node-drag-stop="logEvent('nodeDragEnd', $event)"
          >
            <Background variant="lines" :size="0.4" :gap="cmToPx(0.5)" pattern-color="#ddd"
                        style="background-color: #fff" />

            <template #node-area="areaNodeProps">
              <AreaNode v-bind="areaNodeProps"
                        :pageData="{width: cmToPx(pageWidth)+'px',height:  cmToPx(pageHeight)+'px'}"></AreaNode>
            </template>
            <template #node-text="textNodeProps">
              <TextNode v-bind="textNodeProps"
                        :pageSize="{width:zoom * cmToPx(pageWidth) ,height:zoom * cmToPx(pageHeight) }"></TextNode>
            </template>
            <template #node-image="imageNodeProps">
              <ImageNode v-bind="imageNodeProps"
                         :pageSize="{width:zoom * cmToPx(pageWidth) ,height:zoom * cmToPx(pageHeight) }"></ImageNode>
            </template>
            <template #node-barCode="barCodeNodeProps">
              <BarCodeNode v-bind="barCodeNodeProps"
                           :pageSize="{width:zoom * cmToPx(pageWidth) ,height:zoom * cmToPx(pageHeight) }"></BarCodeNode>
            </template>
            <template #node-QRCode="QRCodeNodeProps">
              <QRCodeNode v-bind="QRCodeNodeProps"
                          :pageSize="{width:zoom * cmToPx(pageWidth) ,height:zoom * cmToPx(pageHeight) }"></QRCodeNode>
            </template>
            <template #node-dateTime="dateTimeNodeProps">
              <TimeNode v-bind="dateTimeNodeProps"
                        :pageSize="{width:zoom * cmToPx(pageWidth) ,height:zoom * cmToPx(pageHeight) }"></TimeNode>
            </template>
            <template #node-select="selectNodeProps">
              <SelectNode v-bind="selectNodeProps"
                          :pageSize="{width:zoom * cmToPx(pageWidth) ,height:zoom * cmToPx(pageHeight) }"></SelectNode>
            </template>
            <template #node-inputNode="inputNodeProps">
              <InputNode v-bind="inputNodeProps"
                         :pageSize="{width:zoom * cmToPx(pageWidth) ,height:zoom * cmToPx(pageHeight) }"></InputNode>
            </template>
            <template #node-box="boxNodeProps">
              <BoxNode v-bind="boxNodeProps"
                       :pageSize="{width:zoom * cmToPx(pageWidth) ,height:zoom * cmToPx(pageHeight) }"></BoxNode>
            </template>
          </VueFlow>
        </div>
      </div>
      <div class="rightPanel" style="padding: 8px">
        <el-form :model="nodeAttrForm" label-width="auto" style="max-width: 600px">
          <el-form-item label="组件大小" v-if="Object.keys(nodeData).length>0">
            <el-input-number :min="1" :controls="false" v-model="nodeData.dimensions.width"
                             style="width: calc(50% - 12px)"
                             @change="nodeData.dimensions.width = Math.max(1,nodeData.dimensions.width);nodeChange()" />
            <div style="display: inline-block;width: 20px;text-align: center">x</div>
            <el-input-number :min="1" :controls="false" v-model="nodeData.dimensions.height"
                             style="width: calc(50% - 12px)"
                             @change="nodeData.dimensions.height = Math.max(1,nodeData.dimensions.height);nodeChange()" />
          </el-form-item>
          <el-form-item label="组件位置" v-if="Object.keys(nodeData).length>0">
            <el-input-number :precision="2" :min="1" :controls="false" v-model="nodeData.position.x"
                             style="width: calc(50% - 12px)"
                             @change="nodeData.position.x = Math.max(1,nodeData.position.x);nodeChange()" />
            <div style="display: inline-block;width: 20px;text-align: center">x</div>
            <el-input-number :precision="2" :min="1" :controls="false" v-model="nodeData.position.y"
                             style="width: calc(50% - 12px)"
                             @change="nodeData.position.y = Math.max(1,nodeData.position.y);nodeChange()" />
          </el-form-item>
          <el-form-item label="名称" v-if="Object.keys(nodeAttrForm).includes('name')">
            <el-input v-model="nodeAttrForm.name" style="width: 100%" />
          </el-form-item>
          <el-form-item label="字段名" v-if="Object.keys(nodeAttrForm).includes('field')">
            <el-input v-model="nodeAttrForm.field" style="width: 100%" />
          </el-form-item>
          <el-form-item label="集合字段名" v-if="Object.keys(nodeAttrForm).includes('selectField')">
            <el-input v-model="nodeAttrForm.selectField" style="width: 100%" />
          </el-form-item>
          <el-form-item label="缺省显示" v-if="Object.keys(nodeAttrForm).includes('default')">
            <el-input v-model="nodeAttrForm.default" style="width: 100%" />
          </el-form-item>
          <el-form-item label="字号大小" v-if="Object.keys(nodeAttrForm).includes('fontSize')">
            <el-input-number :min="12" :controls="false" v-model="nodeAttrForm.fontSize"
                             style="width: 100%" />
          </el-form-item>
          <el-form-item label="使用字典" v-if="Object.keys(nodeAttrForm).includes('dic')">
            <el-select
              v-model="nodeAttrForm.dic"
              placeholder="Select"
            >
              <el-option
                v-for="i in dics"
                :key="i"
                :label="i.dictName"
                :value="i.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图片地址" v-if="Object.keys(nodeAttrForm).includes('imageSrc')">
            <el-input v-model="nodeAttrForm.imageSrc" style="width: 100%" />
          </el-form-item>
          <el-form-item label="时间类型" v-if="Object.keys(nodeAttrForm).includes('dateTimeType')">
            <el-select
              v-model="nodeAttrForm.dateTimeType"
              placeholder="Select"
            >
              <el-option
                label="实时"
                value="1"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="Object.keys(nodeAttrForm).includes('selectOptions')" label="选项集合">
            <el-input-tag
              v-model="nodeAttrForm.selectOptions"
            />
          </el-form-item>
          <el-form-item v-if="Object.keys(nodeAttrForm).includes('horizontalAlign')" label="水平对齐">
            <el-select
              v-model="nodeAttrForm.horizontalAlign"
              placeholder="Select"
            >
              <el-option
                label="左对齐"
                value="left"
              />
              <el-option
                label="居中对齐"
                value="center"
              />
              <el-option
                label="右对齐"
                value="right"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="Object.keys(nodeAttrForm).includes('verticalAlign')" label="垂直对齐">
            <el-select
              v-model="nodeAttrForm.verticalAlign"
              placeholder="Select"
            >
              <el-option
                label="顶部对齐"
                value="start"
              />
              <el-option
                label="居中对齐"
                value="center"
              />
              <el-option
                label="底部对齐"
                value="end"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="边框设置" v-if="Object.keys(nodeAttrForm).includes('border')">
            <div class="borderArea">
              <div class="borderTopLine"
                   :style="{display:nodeAttrForm.border.find(e=>e.type==='top').isShow?'block':'none'}"></div>
              <div class="borderTopArea"
                   @click="nodeAttrForm.border.find(e=>e.type==='top').isShow = !nodeAttrForm.border.find(e=>e.type==='top').isShow"></div>
              <div class="borderRightLine"
                   :style="{display:nodeAttrForm.border.find(e=>e.type==='right').isShow?'block':'none'}"></div>
              <div class="borderRightArea"
                   @click="nodeAttrForm.border.find(e=>e.type==='right').isShow = !nodeAttrForm.border.find(e=>e.type==='right').isShow"></div>
              <div class="borderBottomLine"
                   :style="{display:nodeAttrForm.border.find(e=>e.type==='bottom').isShow?'block':'none'}"></div>
              <div class="borderBottomArea"
                   @click="nodeAttrForm.border.find(e=>e.type==='bottom').isShow = !nodeAttrForm.border.find(e=>e.type==='bottom').isShow"></div>
              <div class="borderLeftLine"
                   :style="{display:nodeAttrForm.border.find(e=>e.type==='left').isShow?'block':'none'}"></div>
              <div class="borderLeftArea"
                   @click="nodeAttrForm.border.find(e=>e.type==='left').isShow = !nodeAttrForm.border.find(e=>e.type==='left').isShow"></div>
            </div>
          </el-form-item>
          <el-form-item label="上框设置"
                        v-if="Object.keys(nodeAttrForm).includes('border') && nodeAttrForm.border.find(e=>e.type==='top').isShow">
            <el-input
              v-model="nodeAttrForm.border.find(e=>e.type==='top').width"
              style=" width: 90px"
              class="borderOption"
            >
              <template #append>px</template>
            </el-input>

            <el-dropdown @command="(e)=>{nodeAttrForm.border.find(v=>v.type==='top').borderType = e}">
              <div class="borderType">
                <div class="borderView"
                     :style="`border-bottom: 2px ${nodeAttrForm.border.find(e=>e.type==='top').borderType} #000;`"></div>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="solid">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px solid #000"></div>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="dashed">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px dashed #000"></div>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="dotted">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px dotted #000"></div>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-color-picker style="margin-left: 8px; "
                             v-model="nodeAttrForm.border.find(e=>e.type==='top').color"
                             show-alpha />
          </el-form-item>
          <el-form-item label="右框设置"
                        v-if="Object.keys(nodeAttrForm).includes('border') && nodeAttrForm.border.find(e=>e.type==='right').isShow">
            <el-input
              v-model="nodeAttrForm.border.find(e=>e.type==='right').width"
              style=" width: 90px"
              class="borderOption"
            >
              <template #append>px</template>
            </el-input>

            <el-dropdown @command="(e)=>{nodeAttrForm.border.find(v=>v.type==='right').borderType = e}">
              <div class="borderType">
                <div class="borderView"
                     :style="`border-bottom: 2px ${nodeAttrForm.border.find(e=>e.type==='right').borderType} #000;`"></div>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="solid">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px solid #000"></div>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="dashed">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px dashed #000"></div>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="dotted">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px dotted #000"></div>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-color-picker style="margin-left: 8px; "
                             v-model="nodeAttrForm.border.find(e=>e.type==='right').color"
                             show-alpha />
          </el-form-item>
          <el-form-item label="下框设置"
                        v-if="Object.keys(nodeAttrForm).includes('border') && nodeAttrForm.border.find(e=>e.type==='bottom').isShow">
            <el-input
              v-model="nodeAttrForm.border.find(e=>e.type==='bottom').width"
              style=" width: 90px"
              class="borderOption"
            >
              <template #append>px</template>
            </el-input>

            <el-dropdown @command="(e)=>{nodeAttrForm.border.find(v=>v.type==='bottom').borderType = e}">
              <div class="borderType">
                <div class="borderView"
                     :style="`border-bottom: 2px ${nodeAttrForm.border.find(e=>e.type==='bottom').borderType} #000;`"></div>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="solid">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px solid #000"></div>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="dashed">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px dashed #000"></div>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="dotted">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px dotted #000"></div>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-color-picker style="margin-left: 8px; "
                             v-model="nodeAttrForm.border.find(e=>e.type==='bottom').color"
                             show-alpha />
          </el-form-item>
          <el-form-item label="左框设置"
                        v-if="Object.keys(nodeAttrForm).includes('border') && nodeAttrForm.border.find(e=>e.type==='left').isShow">
            <el-input
              v-model="nodeAttrForm.border.find(e=>e.type==='left').width"
              style=" width: 90px"
              class="borderOption"
            >
              <template #append>px</template>
            </el-input>

            <el-dropdown @command="(e)=>{nodeAttrForm.border.find(v=>v.type==='left').borderType = e}">
              <div class="borderType">
                <div class="borderView"
                     :style="`border-bottom: 2px ${nodeAttrForm.border.find(e=>e.type==='left').borderType} #000;`"></div>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="solid">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px solid #000"></div>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="dashed">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px dashed #000"></div>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="dotted">
                    <div style="width: 100%;height: 20px;padding-top: 9px">
                      <div style="width: 50px;margin: 0 auto;height: 0px;border-bottom: 2px dotted #000"></div>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-color-picker style="margin-left: 8px; "
                             v-model="nodeAttrForm.border.find(e=>e.type==='left').color"
                             show-alpha />
          </el-form-item>
          <el-form-item label="自定义脚本">
            <el-input type="textarea" :rows="2" v-model="nodeAttrForm.JScript" style="width: 100%" />
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { v4 as uuidv4 } from 'uuid';
import { useRouter } from 'vue-router';
import { useVueFlow, VueFlow } from '@vue-flow/core';
import { Background } from '@vue-flow/background';
import tool, { options } from './tool';
import AreaNode from './nodes/areaNode.vue';
import TextNode from './nodes/textNode.vue';
import ImageNode from './nodes/image.vue';
import BarCodeNode from './nodes/barCodeNode.vue';
import QRCodeNode from './nodes/QRCodeNode.vue';
import TimeNode from './nodes/timeNode.vue';
import SelectNode from './nodes/selectNode.vue';
import InputNode from './nodes/inputNode.vue';
import BoxNode from './nodes/boxNode.vue';
import { updatePrintTemplateList } from '@/api/system/printTemplateList';
import { getPrintTemplateInfo, listPrintTemplateInfo, updatePrintTemplateInfo } from '@/api/system/printTemplateInfo';
import { getPrintTemplateNode, getSysPrintTemplateNodeList, updateTemplateNode } from '@/api/system/printTemplateNode';
import { listType } from '@/api/system/dict/type';

const router = useRouter();
const { updateNode } = useVueFlow();
// 获取自定义的方法
const { onDragStart, onDrop, onDragOver } = tool();
const { cmToPx } = options;
const internalInstance = getCurrentInstance();

const data = {
  planCode:'1',
  cardId:'1',
  classes:'1',
  team: '1',
  specification: '1',
  machineTable: '1',
  operatorName: '张三',
  operatorList: ['张三', '李四'],
  barcode: '1',
  qrcode: '1'
};

const dics = ref([]);
const flowRef = ref();
// const isView = ref(false);
const isSnapToGrid = ref(true);
const pageWidth = ref(21);
const pageHeight = ref(29.7);
const pageType = ref('A4');
const pageId = ref('');
const zoom = ref(1);
const zoomInput = ref('100%');
const nodeAttrForm = ref({});
const nodeData = ref({});
const pid = ref(`area_${uuidv4().replaceAll('-', '_')}`);

const logEvent = async (eventname, event) => {
  switch (eventname) {
    case 'paneClick':
      nodeAttrForm.value = {};
      nodeData.value = {};
      break;
    case 'click':
      if (nodes.value.filter(e => e.selected).length === 1) {
        nodeAttrForm.value = event.node.data.options;
        nodeData.value = JSON.parse(JSON.stringify(event.node));
      } else {
        nodeAttrForm.value = {};
        nodeData.value = {};
      }
      break;
    case 'nodeDrag':
      if (event.nodes.length === 1) {
        nodeAttrForm.value = event.node.data.options;
        nodeData.value = JSON.parse(JSON.stringify(event.node));
      } else {
        nodeAttrForm.value = {};
        nodeData.value = {};
      }
      break;
    case 'nodeDragEnd':
      if (event.nodes.length === 1) {
        nodeAttrForm.value = event.node.data.options;
        nodeData.value = JSON.parse(JSON.stringify(event.node));
      } else {
        nodeAttrForm.value = {};
        nodeData.value = {};
      }
      break;
    case 'selectionEnd':
      console.log(event);
      break;
  }
};
const nodes = ref([{
  id: pid.value,
  name: 'area',
  type: 'area',
  position: {
    x: 0,
    y: 0
  },
  data: {}
}]);
// const nodes = ref([]);
const edges = ref([]);

const setPage = (type, width, height) => {
  pageType.value = type;
  pageHeight.value = height || pageHeight.value;
  pageWidth.value = width || pageWidth.value;
};

const zoomChange = (e) => {
  console.log(flowRef.value.autoPanSpeed);
  flowRef.value.viewport.x = 0;
  flowRef.value.viewport.y = 0;
  let num = zoom.value;
  num += e;
  zoom.value = parseFloat(Math.min(2, Math.max(0.2, num)).toFixed(2));
  zoomInput.value = (zoom.value * 100).toFixed(0) + '%';
  flowRef.value.setTransform({
    x: 0,
    y: 0,
    zoom: zoom.value
  });
};

const view = () => {
  localStorage.setItem('printNodes', JSON.stringify(nodes.value));
  console.log();
  internalInstance.appContext.config.globalProperties.$openPrint([data, data, data], 'demo1');
  // isView.value = true;

};
const save = () => {
  localStorage.setItem('printNodes', JSON.stringify(nodes.value));
  updatePrintTemplateInfo({
    templateInfoId: pageId.value,
    templateListId: router.currentRoute.value.query.id,
    paperType: pageType.value === 'zdy' ? '自定义' : pageType.value,
    width: pageWidth.value,
    height: pageHeight.value,
    activeFlag: '1'
  });
  console.log(nodes.value);
  updateTemplateNode(
    nodes.value.map(e => {
      return {
        templateInfoId: pageId.value,
        id: e.id,
        type: e.type,
        name: e.name,
        width: e.dimensions.width,
        height: e.dimensions.height,
        x: e.position.x,
        y: e.position.y,
        parentNode: e.parentNode,
        data: JSON.stringify(e.data)
      };
    })
  );
};
const clear = () => {
  pid.value =  `area_${uuidv4().replaceAll('-', '_')}`
   nodes.value = [{
    id: pid.value,
    name: 'area',
    type: 'area',
    position: {
      x: 0,
      y: 0
    },
    data: {}
  }]
};

onMounted(() => {
  // listType({
  //   pageNum: 1,
  //   pageSize: 9999999
  // }).then(e => {
  //   dics.value = e.rows;
  //   console.log(dics.value);
  // });
  flowRef.value.onInit(() => {
    flowRef.value.setTransform({
      x: 0,
      y: 0,
      zoom: 1
    });
  });
  // let nodesData = localStorage.getItem('printNodes')
  // if(nodesData){
  //   nodes.value = JSON.parse(nodesData);
  //   pid.value = nodes.value.find(e => e.name === 'area')?.id;
  // }

  listPrintTemplateInfo({ templateListId: router.currentRoute.value.query.id }).then(e => {
    let data = e.rows[0] || {};
    pageType.value = (data.paperType || 'A4') === '自定义' ? 'zdy' : data.paperType;
    pageId.value = data.templateInfoId;
    pageWidth.value = data.width || 21;
    pageHeight.value = data.height || 29.7;
    getSysPrintTemplateNodeList({ templateInfoId: data.templateInfoId }).then(v => {
      nodes.value = v.data.map((vv, index) => {
        return {
          id: vv.id,
          type: vv.type,
          name: vv.name,
          extent: 'parent',
          dimensions: {
            width: vv.width,
            height: vv.height
          },
          computedPosition: {
            x: parseFloat(vv.x || 0),
            y: parseFloat(vv.y || 0),
            z: index + 1
          },
          handleBounds: {
            source: null,
            target: null
          },
          position: {
            x: parseFloat(vv.x || 0),
            y: parseFloat(vv.y || 0)
          },
          parentNode: vv.parentNode,
          data: JSON.parse(vv.data)
        };
      });
      if (nodes.value.length > 0) {
        pid.value = nodes.value.find(e => e.name === 'area')?.id;
      } else {
        clear();
      }
      console.log(nodes.value);
    });
  });
});
watch(() => flowRef.value?.viewport, () => {
  if (flowRef.value && (flowRef.value.viewport.x !== 0 || flowRef.value.viewport.y !== 0)) {
    flowRef.value.setTransform({
      x: 0,
      y: 0,
      zoom: zoom.value
    });
  }
}, { deep: true });

const toggleSnapToGrid = (e) => {
  if (e.key === 'Alt') {
    isSnapToGrid.value = false;
  }
};
const keyup = () => {
  isSnapToGrid.value = true;
};
window.addEventListener('keydown', toggleSnapToGrid);
window.addEventListener('keyup', keyup);
const nodeChange = () => {
  updateNode(nodeData.value.id, JSON.parse(JSON.stringify(nodeData.value)), { replace: false });
};
const imp = () =>{
  let json = '[{"id":"text_e0ed2e33_b370_493f_9e85_179277939055","type":"text","dimensions":{"width":189,"height":76},"computedPosition":{"x":283.4645669291338,"y":0,"z":1000},"handleBounds":{"source":null,"target":null},"selected":true,"dragging":false,"resizing":false,"initialized":false,"isParent":false,"position":{"x":283.4645669291338,"y":0},"data":{"options":{"field":"planDetailId","default":"","border":[{"type":"top","isShow":false,"width":1,"color":"#000","borderType":"solid"},{"type":"right","isShow":false,"width":1,"color":"#000","borderType":"solid"},{"type":"bottom","isShow":true,"width":1,"color":"#000","borderType":"solid"},{"type":"left","isShow":false,"width":1,"color":"#000","borderType":"solid"}]},"outputData":{}},"events":{},"name":"text","extent":"parent"},{"id":"barCode_1dd4465e_928c_49f2_867b_061fc5f96843","type":"barCode","dimensions":{"width":189,"height":76},"computedPosition":{"x":0,"y":188.97637795275588,"z":0},"handleBounds":{"source":null,"target":null},"selected":false,"dragging":false,"resizing":false,"initialized":false,"isParent":false,"position":{"x":0,"y":188.97637795275588},"data":{"options":{"field":"returnBarcode","default":""},"outputData":{}},"events":{},"name":"barCode","extent":"parent"},{"id":"QRCode_9ad0beba_b555_45ac_a1c6_23f23a6c9e9a","type":"QRCode","dimensions":{"width":189,"height":189},"computedPosition":{"x":529.1338582677165,"y":151.1811023622047,"z":0},"handleBounds":{"source":null,"target":null},"selected":false,"dragging":false,"resizing":false,"initialized":false,"isParent":false,"position":{"x":529.1338582677165,"y":151.1811023622047},"data":{"options":{"field":"returnBarcode","default":""},"outputData":{}},"events":{},"name":"QRCode","extent":"parent"},{"id":"text_1d36c573_734e_4b05_bbc5_4a048ed19e7f","type":"text","dimensions":{"width":189,"height":19},"computedPosition":{"x":283.4645669291338,"y":94.48818897637794,"z":0},"handleBounds":{"source":null,"target":null},"selected":false,"dragging":false,"resizing":false,"initialized":false,"isParent":false,"position":{"x":283.4645669291338,"y":94.48818897637794},"data":{"options":{"field":"planId","default":"","border":[{"type":"top","isShow":false,"width":1,"color":"#000","borderType":"solid"},{"type":"right","isShow":false,"width":1,"color":"#000","borderType":"solid"},{"type":"bottom","isShow":false,"width":1,"color":"#000","borderType":"solid"},{"type":"left","isShow":false,"width":1,"color":"#000","borderType":"solid"}]},"outputData":{}},"events":{},"name":"text","extent":"parent","style":{"width":"189px","height":"19px"}}]';
  nodes.value = JSON.parse(json);
  pid.value = nodes.value.find(e => e.name === 'area')?.id;
}
</script>
<style lang="less" scoped>
.borderOption {
  :deep(.el-input-group__append) {
    padding-left: 8px;
    padding-right: 8px;
  }
}
:deep(.vue-flow__node-area) {
  z-index: -1 !important;
  pointer-events: none !important;
}

:deep(.el-tag) {
  margin-bottom: 8px;
}

.top {
  height: 64px;
  margin: 8px 8px 0 8px;
  border: 1px solid #ccc;
  width: calc(100% - 16px);
  display: inline-block;
}

.bottom {
  height: calc(100vh - 64px - 16px - 8px);
}


.leftPanel, .rightPanel {
  vertical-align: top;
  display: inline-block;
  width: 300px;
  height: 100%;
  margin: 8px 8px 0;
  overflow: auto;
  border: 1px solid #ccc;
}

.content {
  vertical-align: top;
  display: inline-block;
  width: calc(100% - 300px - 300px - 16px - 16px);
  height: 100%;
  margin-top: 8px;
  border: 1px solid #ccc;
  overflow: auto;

  &::-webkit-scrollbar {
    display: none;
  }
}

.flowArea {
  border-right: 1px solid #ccc;
}

.borderArea {
  width: 200px;
  height: 200px;
  position: relative;
}

.borderTopArea, .borderBottomArea {
  position: absolute;
  left: 50px;
  width: 100px;
  height: 20px;
  background: #0000;
  border: 1px solid #ccc;
}

.borderTopArea {
  top: 11px;
}

.borderBottomArea {
  bottom: 11px;
}

.borderRightArea, .borderLeftArea {
  position: absolute;
  top: 50px;
  width: 20px;
  height: 100px;
  background: #0000;
  border: 1px solid #ccc;
}

.borderRightArea {
  right: 11px;
}

.borderLeftArea {
  left: 11px;
}

.borderTopLine, .borderBottomLine {
  position: absolute;
  left: 30px;
  width: 140px;
  height: 2px;
  background: #000;
}

.borderTopLine {
  top: 20px;
}

.borderBottomLine {
  bottom: 20px;
}

.borderRightLine, .borderLeftLine {
  position: absolute;
  top: 30px;
  width: 2px;
  height: 140px;
  background: #000;
}

.borderRightLine {
  right: 20px;
}

.borderLeftLine {
  left: 20px;
}

.borderType {
  margin-left: 8px;
  width: 60px;
  height: 30px;
  border: 1px solid #ccc;
  position: relative;

  .borderView {
    position: absolute;
    top: calc(50% - 1px);
    width: 80%;
    left: 10%;
  }
}
</style>

