<template>
  <el-dialog
    :class="`${prefixCls} flx-col`"
    width="80%"
    align-center
    v-model="dialogVisible"
    destroy-on-close
    append-to-body
    :show-close="false"
    :fullscreen="isFullscreen"
    :before-close="beforeCloseFunc"
    @closed="onClosed"
  >
    <template #header>
      <div class="flx-start">
        <div class="flx-1 flx-start">
          <span class="text-h4-m">
            {{ $t("business.printEditor.title") }}
          </span>
          <el-divider direction="vertical" />
          <span class="text-h4-m mr-12 text-secondary-text">
            {{ dwnameTitle }}
          </span>
        </div>
        <div class="flx-shrink">
          <span class="text-primary-text text-body-r" style="cursor: text" v-if="!isEditAliase" @click="toEditAliase">
            {{ templateData.aliase }}
            <i class="iconfont iconedit-02" style="cursor: text"></i>
          </span>
          <el-input
            v-else
            ref="aliaseInputRef"
            :class="`${prefixCls}__aliase-input text-body-r`"
            v-model="templateData.aliase"
            style="width: auto"
            :placeholder="$t('table.sys_print_template.aliase')"
            @blur="isEditAliase = !isEditAliase"
          />
        </div>
        <div class="flx-1 flx-end">
          <el-button type="primary" plain @click="preView">
            <template #icon>
              <i class="iconfont iconShow_light"></i>
            </template>
            {{ $t("business.printEditor.preview") }}
          </el-button>
          <el-divider direction="vertical" />
          <el-button type="primary" @click="toSave">
            <template #icon>
              <i class="iconfont iconShow_light"></i>
            </template>
            {{ $t("common.saveText") }}
          </el-button>
          <el-button text circle @click="isFullscreen = !isFullscreen">
            <template #icon>
              <i :class="['iconfont', isFullscreen ? 'iconminimize-02' : 'iconmaximize-02']" class="toolBar-icon"></i>
            </template>
          </el-button>
          <el-button type="danger" :icon="Close" text circle @click="beforeCloseFunc"></el-button>
        </div>
      </div>
      <el-row :class="`${prefixCls}__control mt-4 pt-6 pb-6`" :gutter="12">
        <el-col :span="4">
          <div class="flx-justify-between">
            <el-button-group>
              <el-tooltip effect="dark" :content="$t('common.undo')" placement="bottom" :show-after="8">
                <el-button :disabled="disabled_undo" @click="toDoWhat('undo')">
                  <template #icon>
                    <i class="iconfont iconflip-backward"></i>
                  </template>
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" :content="$t('common.redoText')" placement="bottom" :show-after="8">
                <el-button :disabled="disabled_redo" @click="toDoWhat('redo')">
                  <template #icon>
                    <i class="iconfont iconflip-forward"></i>
                  </template>
                </el-button>
              </el-tooltip>
            </el-button-group>
            <el-button-group>
              <el-tooltip effect="dark" :content="$t('common.fontAdd')" placement="bottom" :show-after="800">
                <el-button @click="updateFontSize('plus')">
                  <template #icon>
                    <i class="iconfont iconfont-plus-01"></i>
                  </template>
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" :content="$t('common.fontReduce')" placement="bottom" :show-after="800">
                <el-button @click="updateFontSize('minus')">
                  <template #icon>
                    <i class="iconfont iconfont-minus-01"></i>
                  </template>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </div>
        </el-col>
        <el-col :span="14">
          <div class="flx-justify-between">
            <div class="flx-center">
              <el-button-group>
                <el-tooltip effect="dark" :content="$t('common.alignLeft')" placement="bottom" :show-after="800">
                  <el-button @click="setElsAlign('left')">
                    <template #icon>
                      <i class="iconfont iconalign-left-02"></i>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip effect="dark" :content="$t('common.alignHorizontalCenter')" placement="bottom" :show-after="800">
                  <el-button @click="setElsAlign('vertical')">
                    <template #icon>
                      <i class="iconfont iconalign-horizontal-centre-02"></i>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip effect="dark" :content="$t('common.alignRight')" placement="bottom" :show-after="800">
                  <el-button @click="setElsAlign('right')">
                    <template #icon>
                      <i class="iconfont iconalign-right-02"></i>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip effect="dark" :content="$t('common.alignTop')" placement="bottom" :show-after="800">
                  <el-button @click="setElsAlign('top')">
                    <template #icon>
                      <i class="iconfont iconalign-top-arrow-02"></i>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip effect="dark" :content="$t('common.alignVerticalCenter')" placement="bottom" :show-after="800">
                  <el-button @click="setElsAlign('horizontal')">
                    <template #icon>
                      <i class="iconfont iconalign-vertical-center-02"></i>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip effect="dark" :content="$t('common.alignBottom')" placement="bottom" :show-after="800">
                  <el-button @click="setElsAlign('bottom')">
                    <template #icon>
                      <i class="iconfont iconalign-bottom-02"></i>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip
                  effect="dark"
                  :content="$t('common.distributeHorizontalSpacing')"
                  placement="bottom"
                  :show-after="800"
                >
                  <el-button @click="setElsAlign('distributeHor')">
                    <template #icon>
                      <i class="iconfont iconspacing-width-01"></i>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip effect="dark" :content="$t('common.distributeVerticalSpacing')" placement="bottom" :show-after="800">
                  <el-button @click="setElsAlign('distributeVer')">
                    <template #icon>
                      <i class="iconfont iconspacing-height-01"></i>
                    </template>
                  </el-button>
                </el-tooltip>
              </el-button-group>
              <el-divider direction="vertical" />
              <div :class="`flx-center ${prefixCls}__control-scale`">
                <el-button @click="changeScale(false)">
                  <template #icon>
                    <i class="iconfont iconzoom-out"></i>
                  </template>
                </el-button>
                <el-input class="ml-4 mr-4" v-model="scalePaper" disabled> </el-input>
                <el-button @click="changeScale(true)">
                  <template #icon>
                    <i class="iconfont iconzoom-in"></i>
                  </template>
                </el-button>
              </div>
              <el-button v-if="scalePaper != '100%'" class="ml-4 -enter-x" @click="resetScale">
                {{ $t("common.reduction") }}
              </el-button>
            </div>
            <el-button-group>
              <el-tooltip effect="dark" :content="$t('common.rotate')" placement="bottom" :show-after="800">
                <el-button @click="rotatePaper">
                  <template #icon>
                    <i class="iconfont iconrefresh-cw-01"></i>
                  </template>
                </el-button>
              </el-tooltip>
              <el-tooltip effect="dark" :content="$t('common.empty')" placement="bottom" :show-after="800">
                <el-button @click="clearPaper">
                  <template #icon>
                    <i class="iconfont iconbrush-03-1"></i>
                  </template>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="flx-justify-between">
            <el-dropdown
              ref="paperDropDownRef"
              trigger="click"
              :hide-on-click="false"
              @command="setPaper"
              @visible-change="handlePaperVisible"
            >
              <el-button type="primary" plain class="pr-10">
                <i class="iconfont iconfile-04"></i>
                <template v-if="curPaper.type == 'other'">
                  {{ `${$t("business.printEditor.customize")}(${curPaper.width}x${curPaper.height})` }}
                </template>
                <template v-else>
                  {{ curPaper.type }}
                </template>
                <el-icon class="pl-4 el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu :class="`${prefixCls}__control-paper`">
                  <el-dropdown-item
                    v-for="(value, type) in paperTypes"
                    :key="type"
                    :icon="curPaperType == type ? Select : ''"
                    :class="{ 'is-select': curPaperType == type }"
                    :command="{ value, type }"
                  >
                    {{ type }}
                    <span class="ml-4 text-body-c text-disable">{{ `${value.width} x ${value.height}` }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item
                    divided
                    :class="{ 'is-select': curPaperType == 'other' }"
                    :command="{ value: { width: paperWidth, height: paperHeight }, type: 'other' }"
                  >
                    <div class="flx-justify-between">
                      <el-input-number
                        v-model="paperWidth"
                        :min="10"
                        :max="500"
                        :step="10"
                        :precision="2"
                        controls-position="right"
                        placeholder="宽度"
                        style="width: 100px"
                      />
                      <span class="text-disable ml-4 mr-4">x</span>
                      <el-input-number
                        v-model="paperHeight"
                        :min="10"
                        :max="500"
                        :step="10"
                        :precision="2"
                        controls-position="right"
                        placeholder="宽度"
                        style="width: 100px"
                      />
                      <el-button class="ml-8" @click="toSetOtherPager">
                        {{ $t("business.printEditor.customize") }}
                      </el-button>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <div class="flx-end">
              <el-upload
                ref="uploadRef"
                class="upload-demo mr-8"
                :auto-upload="false"
                accept=".json,.txt"
                :show-file-list="false"
                :on-change="paperUploadOnChange"
                :before-upload="paperbeforeAvatarUpload"
              >
                <template #trigger>
                  <el-tooltip effect="dark" placement="bottom" :show-after="800">
                    <template #content>
                      {{ $t("common.import") }} <br />
                      {{ $t("business.printEditor.importTips") }}
                    </template>
                    <el-button>
                      <template #icon>
                        <i class="iconfont iconupload-01"></i>
                      </template>
                    </el-button>
                  </el-tooltip>
                </template>
              </el-upload>
              <el-tooltip effect="dark" :content="$t('business.printEditor.export')" placement="bottom" :show-after="800">
                <el-button @click="exportJson">
                  <template #icon>
                    <i class="iconfont icondownload-01"></i>
                  </template>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </el-col>
        <!-- 多面板的容器 -->
        <!-- <div class="hiprint-printPagination" style="margin-top: 14px"></div> -->
      </el-row>
    </template>
    <template #default>
      <el-row :gutter="12" v-loading="paperLoading">
        <el-col :span="4">
          <div class="rect-printElement-types hiprintEpContainer" ref="hiprintEpContainerRef"></div>
          <!-- <div class="rect-printElement-types hiprintEpContainer">
            <el-row v-for="(group, index) in printProviders.options" :key="'ptemplate' + index">
              <div class="group">
                {{ group.groupName }}
              </div>
              <el-col :span="12" v-for="item in group.printElements" :key="item.tid">
                <div>
                  <a class="ep-draggable-item" :tid="printProviders.key + '.' + item.tid">
                    <i class="iconfont iconfont-plus-01"></i>
                    <p class="glyphicon-class">{{ item.title }}</p>
                  </a>
                </div>
              </el-col>
            </el-row>
          </div> -->
        </el-col>
        <el-col :span="14">
          <el-row :class="`${prefixCls}-design relative`">
            <div id="hiprint-printTemplate" class="hiprint-printTemplate pt-15 pl-15"></div>
          </el-row>
        </el-col>
        <el-col :span="6">
          <el-row :class="`${prefixCls}-layout-sider card flx-col pl-12 pr-12`">
            <LjHeader size="small" simple>
              <template #title="scope">
                <i class="iconfont iconFilter_light pr-4"></i>
                <span :class="scope.textSize">属性</span>
              </template>
            </LjHeader>
            <div id="PrintElementOptionSetting"></div>
          </el-row>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
  <Preview ref="printPreviewRef" @print-callback="toPrintCallback" />
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch } from "vue";
import { useDesign } from "@/hooks/useDesign";
import { hiprint } from "vue-plugin-hiprint";
import { Close, Select, ArrowDown } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import LjHeader from "@/components/LjHeader/index.vue";
import Preview from "./components/preview.vue";
import { useI18n } from "vue-i18n";
import { useDownloadLocal } from "@/hooks/useDownload";
import PopoverConfirm from "@/components/PopoverConfirm/index.vue";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { savePrintTemplate } from "@/api/modules/print";
// import type { sys_print_template } from "@/typings/business";
import { providers, providerList, createProvider } from "./providers";
import { PRINT_DWNAME_ENUM, PRINT_DWNAME_NAME } from "./interface/index";
import dayjs from "dayjs";
import { isArray } from "@/utils/is";
import { useHiPrintPlugin } from "@/hooks/useHiPrintPlugin";
import { pick } from "lodash-es";
import { PRINT_KEY_ATTR } from "@/config/index";

const { t } = useI18n();
const { prefixCls } = useDesign("print-editor");
const dialogVisible = ref<boolean>(false);
const paperLoading = ref<boolean>(false);
const isFullscreen = ref<boolean>(false);
const isEditAliase = ref<boolean>(false);
const dwnameTitle = ref("");
const modeList = ref();
const hiprintEpContainerRef = ref();
const printPreviewRef = ref();
const curMode = ref(0);
// const hiprintTemplate = ref();
const scalePaper = ref("");
const templateData = ref<any>({});
const emit = defineEmits(["closed", "printCallback"]);
/**
 * @description 是否保存过
 */
const hasSave = ref<boolean>(false);
/**
 * @description 是否修改过
 */
const hasChange = ref<boolean>(false);
// const printData = ref();
const printProviders = ref();

const toPrintCallback = (data: any) => {
  emit("printCallback", data);
};

const { hiprintTemplate, printData, setPrintTemplate, hiprintDisConnect, toPrintOfDefaultBtn } = useHiPrintPlugin(
  t,
  toPrintCallback,
  toPrintCallback
);

/**
 * @description 模板对照表
 */
const templateList = ref<ColumnProps[]>([]);
/**
 * @description 调节字体大小 间隔
 */
const fontSizeSpace = 0.75;
/**
 * @description 当前纸张尺寸
 */
const curPaper = ref({
  type: "A4",
  width: 210,
  height: 297
});
/**
 * @description 纸张固定列表
 */
const paperTypes = {
  A3: {
    width: 420,
    height: 297
  },
  A4: {
    width: 210,
    height: 297
  },
  A5: {
    width: 210,
    height: 148
  },
  B3: {
    width: 500,
    height: 353
  },
  B4: {
    width: 250,
    height: 353
  },
  B5: {
    width: 250,
    height: 176
  },
  qrcode1: {
    width: 70,
    height: 100
  }
};
const paperWidth = ref(220);
const paperHeight = ref(80);
const paperDropDownRef = ref();
const getPaperType = (data: any) => {
  let type = "other";
  let types: any = paperTypes;
  for (const key in types) {
    let item = types[key];
    let { width, height } = data;
    if (item.width === width && item.height === height) {
      type = key;
    }
  }
  return type;
};
const curPaperType = computed(() => {
  return getPaperType(curPaper.value);
});

// const initParams = {
//   dwname: "web_fx_print_template_saletaskmx_tracking"
// };
// const dataCallback = (data: any) => {
//   return data.templateList;
// };

/**
 * @description 显示组件
 */
const open = (data: any, showData: any) => {
  dialogVisible.value = true;
  templateData.value = data;
  let template = data.dwSyntax ?? {};
  if (template.hasOwnProperty("panels") && template?.panels.length > 0) {
    curPaper.value.width = template.panels[0].width;
    curPaper.value.height = template.panels[0].height;
    curPaper.value.type = curPaperType.value;
    // template.panels[0].paperNumberFormat = "第${paperNo}页，共${paperCount}页";
  }
  console.log("data :>> ", data);
  console.log("datshowDataa :>> ", showData);
  console.log("template :>> ", template);
  console.log("curPaper.value :>> ", curPaper.value);
  console.log("curPaperType :>> ", curPaperType);
  let dwname = templateData.value?.dwname;
  console.log("changeMode PRINT_DWNAME_ENUM[dwname] :>> ", PRINT_DWNAME_ENUM[dwname]);

  let _dwname = dwname.indexOf("_print_template") > -1 ? dwname.replace("_print_template", "") : dwname;
  dwnameTitle.value = t(`business.dwname.${_dwname}`);

  printProviders.value = PRINT_DWNAME_ENUM[dwname];
  printData.value = showData;
  nextTick(() => {
    init();
  });
};

const scaleFormatterFunc = (value: number) => `${(value * 100).toFixed(0)}%`;
const scaleParserFunc = (value: string) => (Number(value.replace("%", "")) / 100).toFixed(2);

const changeMode = () => {
  // let provider = providerList[curMode.value];
  let provider = createProvider(printProviders.value, t);
  console.log("changeMode providers :>> ", providers);
  console.log("changeMode provider :>> ", provider);
  hiprint.init({
    // providers: [...providers]
    providers: [provider]
  });
  // $('.hiprintEpContainer').empty()
  // console.log("hiprintEpContainerRef.value :>> ", hiprintEpContainerRef.value);
  hiprintEpContainerRef.value.innerHTML = "";
  hiprint.PrintElementTypeManager.build(".hiprintEpContainer", printProviders.value.key);

  // /* eslint-disable-next-line no-unused-vars */
  // hiprint.PrintElementTypeManager.buildByHtml($(".ep-draggable-item"));
  // hiprint.PrintElementTypeManager.buildByHtml(document.querySelectorAll(".ep-draggable-item"));
};
const buildTemplate = () => {
  let id_hiprintPrintTemplate = document.getElementById("hiprint-printTemplate");
  // $('#hiprint-printTemplate').empty()
  id_hiprintPrintTemplate!.innerHTML = "";
  hiprintTemplate.value = new hiprint.PrintTemplate({
    template: templateData.value.content,
    settingContainer: "#PrintElementOptionSetting",
    // paginationContainer: ".hiprint-printPagination",
    // defaultPanelName: "默认面板名称",
    // onPanelAddClick: (panel: any, createPanel: any) => {
    //   panel.name = "新面板" + (panel.index + 1);
    //   ElMessage.success("弹出个东西,让你们知道,在这里可以自定义面板名称");
    //   createPanel(panel);
    // }
    // // 图片选择功能
    // onImageChooseClick: (target: any) => {
    //   // 测试 3秒后修改图片地址值
    //   setTimeout(() => {
    //     // target.refresh(url,options,callback)
    //     // callback(el, width, height) // 原元素,宽,高
    //     // target.refresh(url,false,(el,width,height)=>{
    //     //   el.options.width = width;
    //     //   el.designTarget.css('width', width + "pt");
    //     //   el.designTarget.children('.resize-panel').trigger($.Event('click'));
    //     // })
    //     target.refresh(
    //       "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAtAAAAIIAQMAAAB99EudAAAABlBMVEUmf8vG2O41LStnAAABD0lEQVR42u3XQQqCQBSAYcWFS4/QUTpaHa2jdISWLUJjjMpclJoPGvq+1WsYfiJCZ4oCAAAAAAAAAAAAAAAAAHin6pL9c6H/fOzHbRrP0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0u/SY9LS0tLS0tLS0tLS0n+edm+UlpaWlpaWlpaWlpaW/tl0Ndyzbno7/+tPTJdd1wal69dNa6abx+Lq6TSeYtK7BX/Diek0XULSZZrakPRtV0i6Hu/KIt30q4fM0pvBqvR9mvsQkZaW9gyJT+f5lsnzjR54xAk8mAUeJyMPwYFH98ALx5Jr0kRLLndT7b64UX9QR/0eAAAAAAAAAAAAAAAAAAD/4gpryzr/bja4QgAAAABJRU5ErkJggg==",
    //       {
    //         // auto: true, // 根据图片宽高自动等比(宽>高?width:height)
    //         // width: true, // 按宽调整高
    //         // height: true, // 按高调整宽
    //         real: true // 根据图片实际尺寸调整(转pt)
    //       }
    //     );
    //   }, 3000);
    //   // target.getValue()
    //   // target.refresh(url)
    // },
    // 自定义可选字体
    // 或者使用 hiprintTemplate.setFontList([])
    // 或元素中 options.fontList: []
    fontList: [
      { title: "微软雅黑", value: "Microsoft YaHei" },
      { title: "黑体", value: "STHeitiSC-Light" },
      { title: "思源黑体", value: "SourceHanSansCN-Normal" },
      { title: "王羲之书法体", value: "王羲之书法体" },
      { title: "宋体", value: "SimSun" },
      { title: "华为楷体", value: "STKaiti" },
      { title: "cursive", value: "cursive" }
    ],
    dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
    history: true, // 是否需要 撤销重做功能
    // defaultPaperNumberFormat: "第${paperNo}页，共${paperCount}页",
    onDataChanged: (type: any, json: any) => {
      hasChange.value = true;
      console.log("新增、移动、删除、修改(参数调整)、大小、旋转:", type); // 新增、移动、删除、修改(参数调整)、大小、旋转
      console.log("json:", json); // 返回 template

      disabled_undo.value = hiprintTemplate.value.historyPos == 0;
      disabled_redo.value = hiprintTemplate.value.historyPos == hiprintTemplate.value.historyList.length - 1;
    },
    onUpdateError: (e: any) => {
      console.log("onUpdateError:", e);
    }
  });
  hiprintTemplate.value.design("#hiprint-printTemplate", { grid: true });

  // 获取当前放大比例, 当zoom时传true 才会有
  let _scaleV = hiprintTemplate.value.editingPanel.scale || 1;
  scalePaper.value = scaleFormatterFunc(_scaleV);
  console.log("scalePaper.value :>> ", typeof scalePaper.value);
};

// 预览
const preView = () => {
  console.log("preView printData :>> ", printData.value);
  const newDate = dayjs().format("YYYY-MM-DD HH:mm");
  if (isArray(printData.value)) {
    printData.value.forEach((item: any) => {
      item.printDate = newDate;
    });
  } else {
    printData.value.printDate = newDate;
  }
  printPreviewRef.value.show({ hTemplate: hiprintTemplate.value, pData: printData.value, width: curPaper.value.width });
};
// 只预览
const onlyPreview = (template: any, pData: any, title = "") => {
  let _data = setPrintTemplate(template, pData, title);
  printPreviewRef.value.show(_data);
};

// 只预览
const onlyPrint = (template: any, pData: any, title = "") => {
  // let printTem = new hiprint.PrintTemplate({
  //   template: template.dwSyntax,
  //   fontList: [
  //     { title: "微软雅黑", value: "Microsoft YaHei" },
  //     { title: "黑体", value: "STHeitiSC-Light" },
  //     { title: "思源黑体", value: "SourceHanSansCN-Normal" },
  //     { title: "王羲之书法体", value: "王羲之书法体" },
  //     { title: "宋体", value: "SimSun" },
  //     { title: "华为楷体", value: "STKaiti" },
  //     { title: "cursive", value: "cursive" }
  //   ],
  //   dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
  //   history: true // 是否需要 撤销重做功能
  // });
  // console.log("preView printData :>> ", template);
  // const newDate = dayjs().format("YYYY-MM-DD HH:mm");
  // pData.printDate = newDate;
  // printPreviewRef.value.onlyPrint({ hTemplate: printTem, pData: pData, width: printTem.getPanel().width, sTitle: title });
  let _data = setPrintTemplate(template, pData, title);
  printPreviewRef.value.onlyPrint(_data);
};

// 直接打印
const directPrint = (template: any, pData: any, title = "", printerParams?: any) => {
  console.log("directPrint _data printerParams :>> ", template, printerParams);
  let _data = setPrintTemplate(template, pData, title);
  toPrintOfDefaultBtn(_data, printerParams);
};

const init = () => {
  modeList.value = providerList;
  changeMode();
  buildTemplate();
};

// 画板缩放
const scaleMax = 5,
  scaleMin = 0.5;
const changeScale = (big: boolean) => {
  let _scaleV = Number(scaleParserFunc(scalePaper.value));
  console.log("typeof _scaleV :>> ", typeof _scaleV);
  console.log("_scaleV :>> ", _scaleV);
  if (big) {
    _scaleV += 0.1;
    if (_scaleV > scaleMax) _scaleV = scaleMax;
  } else {
    _scaleV -= 0.1;
    if (_scaleV < scaleMin) _scaleV = scaleMin;
  }
  if (hiprintTemplate.value) {
    // scalePaper: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
    hiprintTemplate.value.zoom(_scaleV);
    scalePaper.value = scaleFormatterFunc(_scaleV);
  }
};
const resetScale = () => {
  if (hiprintTemplate.value) {
    // scalePaper: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
    hiprintTemplate.value.zoom(1);
    scalePaper.value = scaleFormatterFunc(1);
  }
};

// 旋转
const rotatePaper = () => {
  if (hiprintTemplate.value) {
    hiprintTemplate.value.rotatePaper();
  }
};

// 清空画板
const clearPaper = () => {
  ElMessageBox.confirm(t("business.printEditor.emptyWarn"), t("sys.app.warning"), {
    confirmButtonText: t("business.printEditor.confirmEmpty"),
    cancelButtonText: t("common.cancelText"),
    type: "warning"
  }).then(() => {
    try {
      hiprintTemplate.value.clear();
      ElMessage.success(t("sys.api.operationSuccess"));
    } catch (error) {
      ElMessage.error(`${t("sys.api.operationFailed")}: ${error}`);
    }
  });
};

// 排版
const setElsAlign = (e: string) => {
  if (hiprintTemplate.value) {
    hiprintTemplate.value.setElsAlign(e);
  }
};

// 撤销/ 重做
const disabled_undo = ref(false),
  disabled_redo = ref(false);
const toDoWhat = (event: string) => {
  console.log("hiprintTemplate.value :>> ", hiprintTemplate.value);
  if (hiprintTemplate.value) {
    hiprintTemplate.value[event]();
    disabled_undo.value = hiprintTemplate.value.historyPos == 0;
    disabled_redo.value = hiprintTemplate.value.historyPos == hiprintTemplate.value.historyList.length - 1;
  }
};

// 切换纸张大小
const handlePaperVisible = (bool: boolean) => {
  if (bool) {
    paperDropDownRef.value.handleOpen();
  }
};
const setPaper = (val: any) => {
  let { value, type } = val;
  if (type != "other") {
    setPaperFunc(val);
  }
};
const setPaperFunc = (val: any) => {
  let { value, type } = val;
  try {
    if (Object.keys(paperTypes).includes(type)) {
      curPaper.value = { type: type, width: value.width, height: value.height };
      hiprintTemplate.value.setPaper(value.width, value.height);
    } else {
      curPaper.value = { type: "other", width: value.width, height: value.height };
      hiprintTemplate.value.setPaper(value.width, value.height);
    }
    // 关闭下拉菜单
    paperDropDownRef.value.handleClose();
  } catch (error) {
    ElMessage.error(`${t("sys.api.operationFailed")}: ${error}`);
  }
};
const toSetOtherPager = () => {
  let val = {
    type: "other",
    value: {
      width: paperWidth.value,
      height: paperHeight.value
    }
  };
  setPaperFunc(val);
};

// 浏览器自动读取剪贴板内容
// const pasteOption = () =>
//   new Promise((resolve, reject) => {
//     navigator.clipboard
//       .readText()
//       .then(v => {
//         importTextarea.value = v;
//         resolve(true);
//       })
//       .catch(v => {
//         resolve(false);
//       });
//   });
// const openImportPopover = () => {
//   pasteOption().then(() => {
//     importVisible.value = true;
//   });
// };
/**
 * @description 导入: 上传文件时检测
 */
const paperbeforeAvatarUpload = (rawFile: any) => {
  if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error(t("business.printEditor.sizeWarnTips"));
    return false;
  }
  return true;
};
const paperUploadOnChange = (uploadFile: any, uploadFiles: any) => {
  paperLoading.value = true;
  const reader = new FileReader();
  reader.onload = (e: any) => {
    // const content = e.target.result;
    // importTextarea.value = content;
    // 导入
    updateJson(e.target.result);
    nextTick(() => {
      paperLoading.value = false;
      ElMessage.success(t("sys.api.operationSuccess"));
      console.log("hiprintTemplate.value :>> ", hiprintTemplate.value);

      // 设置纸张大小
      let targetPaper = hiprintTemplate.value?.printPanels[0] || undefined;
      if (targetPaper) {
        curPaper.value = {
          type: getPaperType(targetPaper),
          width: targetPaper.width,
          height: targetPaper.height
        };
        let val = {
          type: curPaper.value.type,
          value: {
            width: curPaper.value.width,
            height: curPaper.value.height
          }
        };
        setPaperFunc(val);
      }
    });
  };
  reader.readAsText(uploadFile.raw);
};

// 更新面板
const updateJson = (content: string) => {
  if (hiprintTemplate.value) {
    try {
      hiprintTemplate.value.update(JSON.parse(content));
    } catch (e) {
      ElMessage.error(t("sys.api.operationFailed"));
      console.error("updateJson 更新面板内容 :>> ", e);
    }
  }
};

// 字体加减
const updateFontSize = (type: string) => {
  if (hiprintTemplate.value) {
    let els = hiprintTemplate.value.getSelectEls();
    console.log(els);
    for (let i = 0; i < els.length; i++) {
      let fs = els[i].options.fontSize;
      let nextFs = type == "plus" ? fs + fontSizeSpace : type == "minus" ? fs - fontSizeSpace : fs;
      hiprintTemplate.value.getSelectEls()[i].updateOption("fontSize", nextFs);
    }
  }
};

// 导出json
const exportJson = () => {
  if (hiprintTemplate.value) {
    const newDate = dayjs().format("YYYY-MM-DD HH:mm:ss");
    let dwname = templateData.value?.dwname;
    let content = JSON.stringify(hiprintTemplate.value.getJson() || {});
    useDownloadLocal(t, content, PRINT_DWNAME_NAME[dwname] + newDate, { type: "text/plain;charset=utf-8" }, ".json");
  }
};

// 切换打印模板
/**
 * @name 批接收 确认窗口table显示列
 */
const columns_printTemplate: ColumnProps[] = [
  {
    field: "aliase",
    title: "模板名称",
    table: "sys_print_template"
  },
  {
    field: "dwname",
    title: "默认",
    table: "sys_print_template"
  },
  {
    field: "comid",
    title: "供应商",
    table: "sys_print_template"
  },
  {
    field: "dscrp",
    title: "备注",
    table: "sys_print_template"
  }
];
const changeTemplate = (template: string) => {};
const toSelectTemplate = (callback: any) => {
  callback();
};

// 修改模板别名
const aliaseInputRef = ref();
const toEditAliase = () => {
  isEditAliase.value = !isEditAliase.value;
  nextTick(() => {
    aliaseInputRef.value?.focus();
    aliaseInputRef.value?.select();
  });
};

// 保存模板
const toSave = async () => {
  if (!templateData.value.aliase) {
    ElMessage.warning(t("business.printEditor.aliaseEmptyTips"));
    isEditAliase.value = true;

    nextTick(() => {
      aliaseInputRef.value?.focus();
    });
    return;
  }
  let content = JSON.stringify(hiprintTemplate.value.getJson() || {});
  templateData.value.content = content;
  hasSave.value = true;
  hasChange.value = false;

  let _data = pick(templateData.value, PRINT_KEY_ATTR);
  await savePrintTemplate({ template: _data });

  ElMessage.success(t("sys.api.sueccessToSave"));
  dialogVisible.value = false;

  // emit("save", templateData.value, () => {
  //   dialogVisible.value = false;
  // });
};

const beforeCloseFunc = () => {
  console.log("handleClose.value :>> ", hasChange.value);
  if (!hasChange.value) {
    dialogVisible.value = false;
    return;
  }
  ElMessageBox.confirm(t("business.printEditor.closeConfirm"), t("sys.app.logoutTip"), {
    confirmButtonText: t("common.quitText"),
    cancelButtonText: t("common.cancelText"),
    type: "warning"
  })
    .then(() => {
      dialogVisible.value = false;
    })
    .catch(() => {});
};

const onClosed = () => {
  emit("closed", hasSave.value);
};

// 暴露给父组件的参数和方法(外部需要什么，都可以从这里暴露出去)
defineExpose({
  // previewElement: printPreviewRef,
  open,
  onlyPreview,
  onlyPrint,
  directPrint
});
</script>

<style scoped lang="scss">
@import "./index.scss";
:deep(.hiprint-printElement-type) {
  & > li {
    .title {
      color: $color-text-secondary-text;
      padding-top: 0;
    }
    & + li {
      .title {
        padding-top: $space-b2;
        padding-bottom: $space-a1;
      }
    }
    & > ul {
      & > li {
        max-width: unset;
        & > a {
          color: $color-text-primary-text;
          border-color: $color-gray-5;
          background-color: $color-gray-2;
          line-height: 1;
          height: auto;
          text-overflow: ellipsis;
          max-width: unset;
          border-radius: $br-sm;

          &:hover {
            color: $color-gray-1;
            border-color: $color-primary-600;
            background-color: $color-primary-500;
          }
        }
      }
    }
  }
}
</style>

<style lang="scss">
$prefix-cls: "#{$namespace}-print-editor";

.#{$prefix-cls} {
  .el-dialog__header {
    flex-shrink: 0;
    padding-bottom: 4px;
  }
  .el-dialog__body {
    padding-top: $space-b2;
    max-height: 60vh;
    overflow: auto;
    flex: 1;
  }
  &.is-fullscreen {
    .el-dialog__body {
      max-height: unset;
    }
  }
  &__control {
    &-scale {
      z-index: 100;
      .el-input {
        width: 60px;
      }
      .el-input__inner {
        text-align: center;
      }
    }
    &-paper {
      .is-select {
        color: $color-primary-500;
      }
      .el-dropdown-menu__item {
        justify-content: center;
      }
    }
  }
}
</style>
