<template>
  <section class="hiprint-designer">
    <header class="hiprint-designer__header">
      <div class="hiprint-designer__header_content">
        <el-popover
          placement="bottom-start"
          :width="250"
          trigger="hover">
          <template #reference>
            <el-button-group>
              <el-button
                class="paper-setting-text"
                type="primary"
                plain>
                宽高：{{ paperTypeName }}
              </el-button>
              <el-button
                type="primary"
                style="padding: 8px">
                <i
                  style="padding: 0"
                  class="iconfont icon-down"></i>
              </el-button>
            </el-button-group>
          </template>
          <div class="paper-setting">
            <div class="paper-setting_types">
              <div
                class="paper-setting-type-item"
                v-for="type in paperTypesObj"
                @click="setPaperHandler(type.value)">
                {{ type.label }}
              </div>
            </div>
            <div class="paper-setting__content">
              <el-input
                v-model="paperWidth"
                type="number">
                <template #prepend>宽</template>
                <template #append>mm</template>
              </el-input>
              <el-input
                v-model="paperHeight"
                type="number">
                <template #prepend>高</template>
                <template #append>mm</template>
              </el-input>
              <el-button
                type="primary"
                @click="setPaperHandler('other')">
                设置
              </el-button>
            </div>
          </div>
        </el-popover>
        <el-dropdown>
          <el-button-group>
            <el-button
              class="paper-setting-text"
              type="primary"
              plain>
              缩放：{{ scalePercentage }}
            </el-button>
            <el-button
              type="primary"
              style="padding: 8px">
              <i
                style="padding: 0"
                class="iconfont icon-down"></i>
            </el-button>
          </el-button-group>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                :disabled="!canZoomIn"
                @click="zoomIn">
                <i class="iconfont icon-zoom-out"></i>
                缩小
              </el-dropdown-item>
              <el-dropdown-item
                :disabled="!canZoomOut"
                @click="zoomOut">
                <i class="iconfont icon-zoom-in"></i>
                放大
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown @command="onAlign">
          <el-button-group>
            <el-button
              type="primary"
              plain>
              对齐
            </el-button>
            <el-button
              type="primary"
              style="padding: 8px">
              <i
                style="padding: 0"
                class="iconfont icon-down"></i>
            </el-button>
          </el-button-group>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                :disabled="isLessThanTwoSelected"
                command="top">
                顶部对齐
              </el-dropdown-item>
              <el-dropdown-item
                :disabled="isLessThanTwoSelected"
                command="middle">
                上下居中
              </el-dropdown-item>
              <el-dropdown-item
                :disabled="isLessThanTwoSelected"
                command="bottom">
                底部对齐
              </el-dropdown-item>
              <el-dropdown-item
                :disabled="isLessThanTwoSelected"
                command="left">
                左对齐
              </el-dropdown-item>
              <el-dropdown-item
                :disabled="isLessThanTwoSelected"
                command="center">
                左右居中
              </el-dropdown-item>
              <el-dropdown-item
                :disabled="isLessThanTwoSelected"
                command="right">
                右对齐
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown @command="onSplit">
          <el-button-group>
            <el-button
              type="primary"
              plain>
              分布
            </el-button>
            <el-button
              type="primary"
              style="padding: 8px">
              <i
                style="padding: 0"
                class="iconfont icon-down"></i>
            </el-button>
          </el-button-group>
          <template #dropdown>
            <el-dropdown-menu class="cna-actions-dropdown">
              <el-dropdown-item
                :disabled="!isMoreSelected"
                command="horizontal">
                水平分布
              </el-dropdown-item>
              <el-dropdown-item
                :disabled="!isMoreSelected"
                command="vertical">
                垂直分布
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown @command="onSize">
          <el-button-group>
            <el-button
              type="primary"
              plain>
              尺寸
            </el-button>
            <el-button
              type="primary"
              style="padding: 8px">
              <i
                style="padding: 0"
                class="iconfont icon-down"></i>
            </el-button>
          </el-button-group>
          <template #dropdown>
            <el-dropdown-menu class="cna-actions-dropdown">
              <el-dropdown-item
                :disabled="isLessThanTwoSelected"
                command="width">
                等宽
              </el-dropdown-item>
              <el-dropdown-item
                :disabled="isLessThanTwoSelected"
                command="height">
                等高
              </el-dropdown-item>
              <el-dropdown-item
                :disabled="isLessThanTwoSelected"
                command="both">
                大小相等
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <el-form inline>
        <el-form-item label="数据源">
          <el-select
            placeholder="请选择数据源"
            multiple
            v-model="formCode"
            @change="handleFormCodeChange"
            collapse-tags
            collapse-tags-tooltip>
            <el-option
              v-for="d in dataSourceForm"
              :label="d.label"
              :value="d.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        text
        @click="previewPrint">
        <i class="iconfont icon-print"></i>
        预览
      </el-button>
      <el-button
        type="primary"
        text
        @click="saveConfig">
        <i class="iconfont icon-save"></i>
        保存
      </el-button>
      <el-button
        type="danger"
        text
        @click="clearPrint">
        <i class="iconfont icon-clear"></i>
        清空
      </el-button>
    </header>
    <main class="hiprint-designer__main">
      <aside class="hiprint-designer__main_left">
        <el-scrollbar noresize>
          <div class="hiprint-designer_title">基础</div>
          <el-row>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.text">
                <i class="iconfont icon-font-size"></i>
                <span>文本</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.textVal">
                <i class="iconfont icon-font-size"></i>
                <span>值（文本）</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.image">
                <i class="iconfont icon-image-fill"></i>
                <span>图片</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.longText">
                <i class="iconfont icon-file-text"></i>
                <span>长文本</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.table">
                <i class="iconfont icon-table"></i>
                <span>表格</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.emptyTable">
                <i class="iconfont icon-layout"></i>
                <span>空白表格</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.html">
                <i class="iconfont icon-HTML"></i>
                <span>html</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.customText">
                <i class="iconfont icon-container-fill"></i>
                <span>自定义文本</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.barcode">
                <i class="iconfont icon-barcode"></i>
                <span>条形码</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.qrcode">
                <i class="iconfont icon-qrcode"></i>
                <span>二维码</span>
              </a>
            </el-col>
          </el-row>
          <div class="hiprint-designer_title">辅助</div>
          <el-row>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.hline">
                <i class="iconfont icon-border-verticle"></i>
                <span>横线</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.vline">
                <i class="iconfont icon-border-horizontal"></i>
                <span>竖线</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.rect">
                <i class="iconfont icon-border"></i>
                <span>矩形</span>
              </a>
            </el-col>
            <el-col :span="8">
              <a
                class="ep-draggable-item"
                tid="defaultModule.oval">
                <i class="iconfont icon-round"></i>
                <span>椭圆</span>
              </a>
            </el-col>
          </el-row>
        </el-scrollbar>
      </aside>
      <section class="hiprint-designer__main_canvas">
        <el-scrollbar ref="canvasRef">
          <div id="hiprint-printTemplate"></div>
        </el-scrollbar>
      </section>
      <aside class="hiprint-designer__main_right">
        <div id="PrintElementOptionSetting"></div>
        <template v-if="selectedTableEleColumns.length">
          <div class="hiprint-designer_title">表格字段设置</div>
          <el-form
            label-position="top"
            size="small">
            <el-form-item label="表数据选择">
              <template v-if="hasDataSource">
                <el-select
                  v-model="listCode"
                  @change="tableFieldChange">
                  <el-option
                    v-for="d in dataSourceList"
                    :label="d.label"
                    :value="d.value"></el-option>
                </el-select>
              </template>
              <template v-else>
                <el-input
                  v-model="listCode"
                  @change="tableFieldChange"></el-input>
              </template>
            </el-form-item>
            <el-row gutter="10">
              <el-col
                :span="12"
                v-for="col in selectedTableEleColumns">
                <el-form-item :label="col.title">
                  <template v-if="hasDataSource">
                    <el-select v-model="col.field">
                      <el-option
                        v-for="d in listColumns"
                        :value="d"></el-option>
                    </el-select>
                  </template>
                  <template v-else>
                    <el-input v-model="col.field"></el-input>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row gutter="10">
              <el-col :span="12">
                <el-button
                  @click="tableColumnCancel"
                  type="warning">
                  取消
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </aside>
    </main>
  </section>
  <el-dialog v-model="previewShow">
    <div
      class="print-preview"
      v-html="previewHtml"></div>
  </el-dialog>
</template>
<script setup lang="ts">
  // @ts-nocheck
  import {onMounted, ref, onActivated, onDeactivated, computed, watch, shallowRef, nextTick} from 'vue';
  import {
    hiprint,
    defaultElementTypeProvider,
    fontSize,
    scale,
    zIndex,
    panel,
    usePaper,
    useScale,
    useDataSource,
  } from 'yh-hiprint';
  import {useRoute, onBeforeRouteUpdate} from 'vue-router';
  import {toValue} from '@vueuse/core';
  import {ElMessageBox, ElMessage} from 'element-plus';
  import axios from '@/libs/api.request';
  import previewHiprint from './libs/previewHiprint';
  import {defaultPrintElement} from 'yh-hiprint';

  const route = useRoute();
  const hiprintTemplate = shallowRef<HiprintTemplate | null>(null);

  const {paperType, paperTypeName, paperTypesObj, paperWidth, paperHeight, setPaper} = usePaper();

  function setPaperHandler(type) {
    setPaper(type, () => {
      if (!hiprintTemplate.value) return;
      hiprintTemplate.value.setPaper(paperWidth.value, paperHeight.value);
    });
  }

  const canvasRef = ref();
  const {scaleValue, scalePercentage, canZoomIn, canZoomOut, zoomIn, zoomOut} = useScale(() => {
    hiprintTemplate.value?.zoom(scaleValue.value);
    canvasRef?.value.update();
  });

  async function previewPrint() {
    previewHiprint(detailData.value.code);
  }

  function handleFormCodeChange() {
    // 手动触发字段更新，解决延迟问题
    nextTick(() => {
      if (formColumns.value && formColumns.value.length && hiprintTemplate.value) {
        hiprintTemplate.value.setFields(
          formColumns.value.map((item) => {
            return {
              field: item,
              text: item,
            };
          })
        );
      } else {
        hiprintTemplate.value?.setFields('');
      }
    });
  }

  function saveConfig() {
    let arr = [].concat(formCode.value);
    let json = hiprintTemplate.value?.getJson();
    json.panels[0].printElements.forEach((item) => {
      if (item.printElementType.type === 'table') {
        arr.push(item.options.field);
      }
    });
    // 去重，避免表格 field 与 formCode 已选项在反复保存中累加
    arr = [...new Set(arr)];

    axios
      .request({
        url: '/printTemplate/save',
        method: 'post',
        type: 'json',
        data: {
          id: detailData.value.id,
          json: JSON.stringify(json),
          dsIds: arr.join(','),
        },
      })
      .then((res) => {
        ElMessage.success({
          message: '恭喜模板保存成功',
        });
      });
  }

  function clearPrint() {
    hiprintTemplate.value?.clear();
  }

  const {
    detailData,
    getDetail,
    listCode,
    dataSourceList,
    listColumns,
    formCode,
    formColumns,
    dataSourceForm,
    getDataSourceList,
  } = useDataSource(axios);

  watch(
    () => formColumns.value,
    (val) => {
      if (val && val.length && hiprintTemplate.value) {
        hiprintTemplate.value.setFields(
          val.map((item) => {
            return {
              field: item,
              text: item,
            };
          })
        );
      } else {
        hiprintTemplate.value?.setFields('');
      }
    },
    {
      deep: true,
      immediate: true,
    }
  );

  const selectedEle = shallowRef([]);

  const isLessThanTwoSelected = computed(() => {
    return !selectedEle.value || selectedEle.value.length < 2;
  });

  const isMoreThanTwoSelected = computed(() => {
    return selectedEle.value && selectedEle.value.length >= 2;
  });

  const isMoreSelected = computed(() => {
    return selectedEle.value && selectedEle.value.length >= 3;
  });

  let selectedTableEle = ref(null);

  let selectedTableEleColumns = computed(() => {
    if (selectedTableEle.value && selectedTableEle.value.printElementType.type === 'table') {
      return selectedTableEle.value.options?.columns[0]['columns'] || [];
    } else {
      return [];
    }
  });

  function onAlign(e) {
    switch (e) {
      case 'top':
        let tys = selectedEle.value.map((item) => item.options.top);
        let tminY = Math.min(...tys);
        selectedEle.value.forEach((item) => {
          item.options.top = tminY;
          hiprintJQuery(item.designTarget[0]).css('top', item.options.displayTop());
        });
        break;
      case 'middle':
        let mys = selectedEle.value.map((item) => item.options.top);
        let mminY = Math.min(...mys);
        let mbaseIndex = mys.indexOf(mminY);
        let mbaseObj = selectedEle.value[mbaseIndex];
        let baseY = mbaseObj.options.height / 2 + mbaseObj.options.top;
        selectedEle.value.forEach((item, index) => {
          if (mbaseIndex !== index) {
            item.options.top = baseY - item.options.height / 2;
            hiprintJQuery(item.designTarget[0]).css('top', item.options.displayTop());
          }
        });
        break;
      case 'bottom':
        let bys = selectedEle.value.map((item) => item.options.top + item.options.height);
        let bmaxY = Math.max(...bys);
        selectedEle.value.forEach((item) => {
          item.options.top = bmaxY - item.options.height;
          hiprintJQuery(item.designTarget[0]).css('top', item.options.displayTop());
        });
        break;
      case 'left':
        let lxs = selectedEle.value.map((item) => item.options.left);
        let lminX = Math.min(...lxs);
        selectedEle.value.forEach((item) => {
          item.options.left = lminX;
          hiprintJQuery(item.designTarget[0]).css('left', item.options.displayLeft());
        });
        break;
      case 'center':
        let cxs = selectedEle.value.map((item) => item.options.left);
        let cminX = Math.min(...cxs);
        let cbaseIndex = cxs.indexOf(cminX);
        let cbaseObj = selectedEle.value[cbaseIndex];
        let baseX = cbaseObj.options.width / 2 + cbaseObj.options.left;
        selectedEle.value.forEach((item, index) => {
          if (cbaseIndex !== index) {
            item.options.left = baseX - item.options.width / 2;
            hiprintJQuery(item.designTarget[0]).css('left', item.options.displayLeft());
          }
        });
        break;
      case 'right':
        let rxs = selectedEle.value.map((item) => item.options.left + item.options.width);
        let rmaxX = Math.max(...rxs);
        selectedEle.value.forEach((item) => {
          item.options.left = rmaxX - item.options.width;
          hiprintJQuery(item.designTarget[0]).css('left', item.options.displayLeft());
        });
        break;
      default:
        break;
    }
  }

  function onSplit(key) {
    switch (key) {
      case 'horizontal':
        let lxs = selectedEle.value.map((item) => item.options.left);
        let rxs = selectedEle.value.map((item) => item.options.left + item.options.width);
        let minlx = Math.min(...lxs);
        let maxrx = Math.max(...rxs);
        let minlxIndex = lxs.indexOf(minlx);
        let maxrxIndex = rxs.indexOf(maxrx);
        if (minlxIndex !== maxrxIndex) {
          let sortCompos = selectedEle.value.sort((a, b) => {
            return a.options.left - b.options.left;
          });
          let countWidth = 0;
          sortCompos.forEach((item) => {
            countWidth += item.options.width;
          });
          let countGap = maxrx - minlx - countWidth;
          let gap = countGap / (sortCompos.length - 1);
          sortCompos.forEach((item, index, arr) => {
            if (index > 0 && index < arr.length - 1) {
              let preItem = arr[index - 1];
              item.options.left = preItem.options.left + preItem.options.width + gap;
              hiprintJQuery(item.designTarget[0]).css('left', item.options.displayLeft());
            }
          });
        } else {
          // TODO 此处隐藏了操作提示，这一处提示是告知为什么不能进行操作的原因，不过措辞没有研究好。所以遇到这种情况暂时做静默处理吧。
          // let obj = selectedEle.value[minlxIndex];
          // this.$message.info(`[${obj.compName}]元素影响均匀分布计算了，请取消选中[${obj.compName}]`)
        }
        break;
      case 'vertical':
        let tys = selectedEle.value.map((item) => item.options.top);
        let bys = selectedEle.value.map((item) => item.options.top + item.options.height);
        let minly = Math.min(...tys);
        let maxry = Math.max(...bys);
        let minlyIndex = tys.indexOf(minly);
        let maxryIndex = bys.indexOf(maxry);
        if (minlyIndex !== maxryIndex) {
          let sortCompos = selectedEle.value.sort((a, b) => {
            return a.options.top - b.options.top;
          });
          let countHeight = 0;
          sortCompos.forEach((item) => {
            countHeight += item.options.height;
          });
          let countGap = maxry - minly - countHeight;
          let gap = countGap / (sortCompos.length - 1);
          sortCompos.forEach((item, index, arr) => {
            if (index > 0 && index < arr.length - 1) {
              let preItem = arr[index - 1];
              item.options.top = preitem.options.top + preItem.options.height + gap;
              hiprintJQuery(item.designTarget[0]).css('top', item.options.displayTop());
            }
          });
        } else {
          // TODO 此处隐藏了操作提示，这一处提示是告知为什么不能进行操作的原因，不过措辞没有研究好。所以遇到这种情况暂时做静默处理吧。
          // let obj = selectedEle.value[minlxIndex];
          // this.$message.info(`[${obj.compName}]元素影响均匀分布计算了，请取消选中[${obj.compName}]`)
        }
        break;
      default:
        break;
    }
  }

  function onSize(key) {
    switch (key) {
      case 'width':
        let width = selectedEle.value[0].options.width;
        selectedEle.value.forEach((item) => {
          item.options.width = width;
          hiprintJQuery(item.designTarget[0]).css('width', item.options.displayWidth());
        });
        break;
      case 'height':
        let height = selectedEle.value[0].options.height;
        selectedEle.value.forEach((item) => {
          item.options.height = height;
          hiprintJQuery(item.designTarget[0]).css('height', item.options.displayHeight());
        });
        break;
      case 'both':
        let {w, h} = selectedEle.value[0].rect;

        selectedEle.value.forEach((item) => {
          item.options.height = h;
          item.options.width = w;
          hiprintJQuery(item.designTarget[0])
            .css('height', item.options.displayHeight())
            .css('width', item.options.displayWidth());
        });
        break;
      default:
        break;
    }
  }

  function tableFieldChange(val) {
    selectedTableEle.value.updateOption('field', val);
  }

  function tableColumnCancel() {
    selectedTableEle.value = null;
  }

  function init() {
    try {
      hiprint.init({
        providers: [new defaultElementTypeProvider()],
      });
      hiprint.setConfig();
      hiprint.setConfig({
        optionItems: [fontSize, scale, zIndex],
        movingDistance: 2.5,
        text: {
          tabs: [
            {
              options: [],
            },
            {
              name: '样式',
              options: [
                {
                  name: 'scale',
                  after: 'transform',
                  hidden: false,
                },
              ],
            },
          ],
          supportOptions: [
            {
              name: 'styler',
              hidden: true,
            },
            {
              name: 'scale',
              after: 'transform',
              hidden: false,
            },
            {
              name: 'formatter',
              hidden: true,
            },
          ],
        },
        image: {
          tabs: [
            {
              replace: true,
              name: '基本',
              options: [
                {
                  name: 'field',
                  hidden: false,
                },
                {
                  name: 'src',
                  hidden: false,
                },
                {
                  name: 'fit',
                  hidden: false,
                },
              ],
            },
          ],
        },
        table: {
          tabs: [{options: [{name: 'field', hidden: true}]}],
        },
      });

      hiprint.PrintElementTypeManager.buildByHtml(hiprintJQuery('.ep-draggable-item'));
      hiprintJQuery('#hiprint-printTemplate').empty();
      let template = JSON.parse(detailData.value.json) || panel;
      hiprintTemplate.value = new hiprint.PrintTemplate({
        template,
        onImageChooseClick: (target) => {
          console.log(target);
        },
        fontList: [
          {title: '微软雅黑', value: 'Microsoft YaHei'},
          {title: '黑体', value: 'STHeitiSC-Light'},
          {title: '思源黑体', value: 'SourceHanSansCN-Normal'},
          {title: '宋体', value: 'SimSun'},
          {title: '华为楷体', value: 'STKaiti'},
          {title: 'cursive', value: 'cursive'},
          {title: 'Times New Roman', value: 'Times New Roman'},
        ],
        dataMode: 1,
        history: true,
        onDataChanged: (type, json) => {},
        onUpdateError: (e) => {
          console.error(e);
        },
        settingContainer: '#PrintElementOptionSetting',
        paginationContainer: '.hiprint-printPagination',
      });

      hiprintTemplate.value?.design('#hiprint-printTemplate', {grid: true});
      scaleValue.value = hiprintTemplate.value.editingPanel.scale || 1;
      window.ht = hiprintTemplate.value;

      if (formColumns.value) {
        hiprintTemplate.value?.setFields(
          formColumns.value.map((item) => {
            return {
              field: item,
              text: item,
            };
          })
        );
      }
      hiprintJQuery('.hiprint-designer').on('mousedown', '.hiprint-printElement', (e) => {
        let t = e.currentTarget;
        selectedEle.value = hiprintTemplate.value?.getSelectEls() || [];
        let pes = hiprintTemplate.value?.editingPanel.printElements;
        let index = pes.map((item) => item.designTarget[0]).findIndex((item) => t === item);
        let pe = pes[index];
        selectedTableEle.value = pe || null;
        if (pe && pe.options.field) {
          listCode.value = pe.options.field;
        }
      });
      hiprintJQuery('#PrintElementOptionSetting').on('input', 'input[type=number]', ($el) => {
        let val = parseInt($el.target.value);
        if (val < 1) {
          $el.target.value = 1;
        }
        if (val > 2000) {
          $el.target.value = 2000;
        }
      });
    } catch (error) {
      console.error('yh-hiprint init 异常：', error);
      clearPrint();
      hiprintTemplate.value = null;
      if (error.message.indexOf('setTemplateId') > -1) {
        ElMessageBox.alert('模板有错误，请返回列表手动修改或这清空模板！');
      }
    }
  }

  let updateing = false;
  async function updateTemplate(code) {
    if (updateing === true) {
      return false;
    }
    updateing = true;
    if (hiprintTemplate.value) {
      await getDetail(code);
      if (detailData.value && detailData.value.json) {
        let jsonObj = JSON.parse(detailData.value.json);
        hiprintTemplate.value?.update(jsonObj);
        let {width, height} = jsonObj.panels[0];
        paperWidth.value = width;
        paperHeight.value = height;
        setPaperHandler('other');
        scaleValue.value = 1;
      } else {
        hiprintTemplate.value?.update({
          panels: [
            {
              index: 0,
              name: 1,
              height: 297,
              width: 210,
              paperHeader: 125,
              paperFooter: 272.5,
              paperNumberLeft: 430,
              paperNumberTop: 5,
              printElements: [],
              watermarkOptions: {
                content: '',
                rotate: 25,
                timestamp: false,
                format: 'YYYY-MM-DD HH:mm',
              },
            },
          ],
        });
        paperWidth.value = 210;
        paperHeight.value = 297;
        setPaperHandler('other');
        scaleValue.value = 1;
      }
    } else {
      await getDetail(code);
      if (detailData.value && detailData.value.json) {
        let jsonObj = JSON.parse(detailData.value.json);
        let {width, height} = jsonObj.panels[0];
        paperWidth.value = width;
        paperHeight.value = height;
        setPaperHandler('other');
      } else {
        paperWidth.value = 210;
        paperHeight.value = 297;
        setPaperHandler('other');
      }
      init();
    }
    updateing = false;
  }

  const hasDataSource = computed(() => {
    return Array.isArray(formCode.value) ? formCode.value.length > 0 : formCode.value;
  });

  function wheelHandler(e: MouseEvent) {
    if (e.ctrlKey) {
      const isZoomIn = e.wheelDelta < 0;
      const isZoomOut = e.wheelDelta > 0;
      if (isZoomIn && canZoomIn) {
        e.preventDefault();
        e.stopPropagation();
        zoomIn();
      }
      if (isZoomOut && canZoomOut) {
        e.preventDefault();
        e.stopPropagation();
        zoomOut();
      }
    }
  }

  onActivated(() => {
    updateTemplate(route.query.code);
    window.addEventListener('wheel', wheelHandler, {passive: false});
  });

  onBeforeRouteUpdate((to) => {
    updateTemplate(to.query.code);
  });

  onDeactivated(() => {
    clearPrint();
    window.removeEventListener('wheel', wheelHandler);
  });

  onMounted(async () => {
    await getDataSourceList();
    if (route.query.code) {
      updateTemplate(route.query.code);
    }
  });
</script>
<style lang="scss">
  .hiprint-designer {
    width: calc(100% + 32px);
    height: calc(100%);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    background-color: var(--el-bg-color-page);
    margin: 0 -16px;
    &__header {
      padding: 0 16px;
      height: 50px;
      display: flex;
      background-color: var(--el-bg-color);
      align-items: center;
      box-shadow: var(--el-box-shadow-lighter);
      position: relative;
      z-index: 1;
      > * {
        margin-right: 10px;
        margin-left: 0 !important;
      }
      .paper-setting-text {
        width: 100px;
        .iconfont {
          display: inline-block;
          padding: 0 10px 0 20px;
        }
      }
      .percentage {
        width: 165px;
      }
      .el-select {
        --el-select-width: auto;
        width: 150px;
      }
      > .el-button {
        padding: 5px;
      }
      .el-form-item {
        margin-bottom: 0;
        margin-right: 10px;
      }
      &_content {
        flex: 1;
        > * {
          margin-right: 10px;
          margin-left: 0 !important;
        }
      }
    }
    &_title {
      font-size: 18px;
      font-weight: bold;
      line-height: 1.7em;
      margin-bottom: 10px;
    }
    .ep-draggable-item {
      user-select: none;
      width: 100%;
      height: 70px;
      display: inline-flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 10px;
      .iconfont {
        font-size: 30px;
        width: 40px;
        height: 40px;
        text-align: center;
        line-height: 40px;
      }
    }
    &__main {
      flex: 1;
      overflow: hidden;
      display: flex;
      &_left {
        width: 300px;
        overflow: hidden;
        background-color: var(--el-color-white);
        box-shadow: var(--el-box-shadow-lighter);
        .el-scrollbar__view {
          padding: 16px;
        }
      }
      &_canvas {
        flex: 1;
        overflow: hidden;
        .el-scrollbar__view {
          padding: 20px 10px 40px 20px;
          #hiprint-printTemplate {
            position: relative;
          }
        }
      }
      &_right {
        width: 340px;
        overflow: hidden;
        background-color: var(--el-color-white);
        box-shadow: var(--el-box-shadow-lighter);
        display: flex;
        flex-direction: column;
        .prop-tabs {
          height: 100%;
          overflow: hidden;
          display: flex;
          flex-direction: column;
          .prop-tab-items {
            display: flex;
            height: 43px;
            box-sizing: border-box;
            .prop-tab-item {
              height: 40px;
              line-height: 40px;
              flex: 1;
              text-align: center;
            }
          }
          .hiprint-option-items.active {
            display: block;
            padding: 0 6px 0 12px;
          }
        }
        .hiprint-option-items {
          height: 100%;
          overflow: auto;
          padding: 16px;
          box-sizing: border-box;
          &::-webkit-scrollbar {
            width: 4px;
            height: 4px;
          }

          &::-webkit-scrollbar-thumb {
            border-radius: 4px;
            background: #bbb;
          }
        }
        .hiprint-designer_title {
          padding: 0 10px;
          margin: 0;
        }
        #PrintElementOptionSetting {
          flex: 1;
          overflow: hidden;
        }
        .el-form {
          padding: 0 10px 10px;
          .el-form-item--small {
            margin-bottom: 5px;
          }
          .el-form-item__label {
            margin-bottom: 0;
          }
          .el-button {
            width: 100%;
          }
        }
      }
    }
  }

  .print-preview-dialog {
    min-width: 1000px;
    max-width: 1200px;
    .el-message-box__container {
      justify-content: center;
      background-color: #f2f2f2;
    }
    .hiprint-printPaper {
      margin-top: 5px;
      position: relative;
      background-color: #fff;
      &:last-child {
        margin-bottom: 5px;
      }
    }
  }
  .paper-setting {
    display: flex;
    .paper-setting_types {
      width: 100px;
      margin-right: 10px;
      .paper-setting-type-item {
        width: 100%;
        text-align: center;
        height: 40px;
        line-height: 40px;
        cursor: pointer;
        &:hover {
          background-color: var(--el-color-primary-light-9);
        }
      }
    }
    .paper-setting__content {
      flex: 1;
      .el-input {
        width: 140px;
        .el-input-group__prepend,
        .el-input-group__append {
          padding: 0 9px;
        }
      }
      .el-button + .el-button {
        margin-left: 0;
      }
      > * {
        width: 100%;
        margin-bottom: 10px;
      }
    }
  }
</style>
