<template>
  <div>
    <Card>
      <Row :gutter="[8, 0]" style="margin-bottom: 10px">
        <Col :span="6">
          <a-card>
            <!-- 纸张设置 -->
            <a-button-group>
              <template v-for="(value, type) in paperTypes" :key="type">
                <a-button
                  :type="curPaperType === type ? 'primary' : 'info'"
                  @click="setPaper(type, value)"
                >
                  {{ type }}
                </a-button>
              </template>
              <a-popover v-model="paperPopVisible" title="设置纸张宽高(mm)" trigger="click">
                <template #content>
                  <a-input-group compact style="margin: 10px">
                    <a-input
                      type="number"
                      v-model="paperWidth"
                      style="width: 100px; text-align: center"
                      placeholder="宽(mm)"
                    />
                    <a-input
                      style="
                        width: 30px;
                        border-left: 0;
                        pointer-events: none;
                        background-color: #fff;
                      "
                      placeholder="~"
                      disabled
                    />
                    <a-input
                      type="number"
                      v-model="paperHeight"
                      style="width: 100px; text-align: center; border-left: 0"
                      placeholder="高(mm)"
                    />
                  </a-input-group>
                  <a-button type="primary" style="width: 100%" @click="setPaperOther"
                    >确定</a-button
                  >
                </template>
                <a-button :type="'other' == curPaperType ? 'primary' : ''">自定义纸张</a-button>
              </a-popover>
            </a-button-group>
            <div class="mt-2">
              <a-input-group compact>
                <a-tooltip title="缩小" @click="changeScale(false)">
                  <a-button>
                    <template #icon><ZoomOutOutlined /></template>
                  </a-button>
                </a-tooltip>
                <a-input-number
                  :value="scaleValue"
                  :min="scaleMin"
                  :max="scaleMax"
                  :step="0.1"
                  disabled
                  :formatter="value => `${(value * 100).toFixed(0)}%`"
                  :parser="value => value.replace('%', '')"
                />
                <a-tooltip title="放大" @click="changeScale(true)">
                  <a-button>
                    <template #icon><ZoomInOutlined /></template>
                  </a-button>
                </a-tooltip>
              </a-input-group>
            </div>
            <div class="flex justify-between mt-2">
              <a-button type="primary" @click="rotatePaper()">旋转</a-button>
              <!-- <a-button type="primary" icon="eye" @click="preView"> 预览 </a-button> -->
              <a-button type="primary" @click="print"> 打印 </a-button>
              <a-button type="primary" @click="exportJsonTid"> 导出模板 json tid </a-button>
              <a-popconfirm
                title="是否确认清空?"
                okType="danger"
                okText="确定清空"
                @confirm="clearPaper"
              >
                <a-button type="danger"> 清空 </a-button>
              </a-popconfirm>
            </div>
            <div class="mt-2">
              <div>
                <!-- <div class="title">provider1 默认样式</div> -->
                <!-- provider1 的容器; 加上 class "rect-printElement-types" 使用默认样式 -->
                <!-- 当然可以 重写 或者 自定义样式 -->
                <div id="provider-container1" class="clear-both rect-printElement-types" />
              </div>
              <div class="mt-2">
                <!-- <div class="title">provider2 自定义样式</div> -->
                <div class="title">样式</div>
                <!-- provider2 的容器; -->
                <div id="provider-container2" class="clear-both rect-printElement-types" />
              </div>
            </div>
          </a-card>
        </Col>
        <Col :span="14">
          <a-card class="card-design">
            <!-- 设计器的 容器 -->
            <div id="hiprint-printTemplate" />
          </a-card>
        </Col>
        <Col :span="4">
          <a-card>
            <!-- 元素参数的 容器 -->
            <div id="PrintElementOptionSetting" />
          </a-card>
        </Col>
      </Row>
    </Card>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref, getCurrentInstance } from 'vue';
  import { disAutoConnect, hiprint } from 'vue-plugin-hiprint';
  import { Card, Row, Col } from 'ant-design-vue';
  import { ZoomInOutlined, ZoomOutOutlined } from '@ant-design/icons-vue';
  // import { provider1 } from './provider1';
  import { provider2 } from './provider2';
  import template from './template';
  import printData from './printData';
  // 组合式函数 hooks
  import { usePaper } from './hooks/usePaper';
  import { useZoom } from './hooks/useZoom';
  // 工具
  import { newHiprintPrintTemplate } from './utils/template-helper';
  disAutoConnect();
  const TEMPLATE_KEY = getCurrentInstance().type.name; // 存储模板对象的 key
  console.log('🚀 ~ file: index.vue:110 ~ getCurrentInstance:', getCurrentInstance());
  const {
    // curPaper,
    paperTypes,
    curPaperType,
    paperPopVisible,
    paperWidth,
    paperHeight,
    // showPaperPop,
    setPaper,
    setPaperOther,
    scaleMin,
    scaleMax,
  } = usePaper(TEMPLATE_KEY);
  const { scaleValue, changeScale } = useZoom(TEMPLATE_KEY);

  // 初始化 provider
  hiprint.init({
    // providers: [provider1(), provider2()],
    providers: [provider2()],
  });

  onMounted(() => {
    buildLeftElement();
    buildDesigner();
  });

  /**
   * 构建左侧可拖拽元素
   * 注意: 可拖拽元素必须在 hiprint.init() 之后调用
   * 调用之前 可以先 console.log($("#hiprint-printTemplate")) 看看是否有该 dom
   */
  const buildLeftElement = () => {
    // ----- providerModule1 -----
    // eslint-disable-next-line no-undef
    $('#provider-container1').empty(); // 先清空, 避免重复构建
    // eslint-disable-next-line no-undef
    hiprint.PrintElementTypeManager.build($('#provider-container1'), 'providerModule1');
    // ----- providerModule2 -----
    // eslint-disable-next-line no-undef
    $('#provider-container2').empty(); // 先清空, 避免重复构建
    // eslint-disable-next-line no-undef
    hiprint.PrintElementTypeManager.build($('#provider-container2'), 'providerModule2');
  };

  /**
   * 构建设计器
   * 注意: 必须要在 onMounted 中去构建
   * 因为都是把元素挂载到对应容器中, 必须要先找到该容器
   */
  let hiprintTemplate;
  // ref 创建的模板json
  const templateRef = ref(template);
  console.log('templateRef 数据格式:');
  console.log('templateRef', templateRef);
  console.log('templateRef.value', templateRef.value);
  const buildDesigner = () => {
    // eslint-disable-next-line no-undef
    // const printTemplte = document.querySelector('#hiprint-printTemplate');
    // printTemplte.parentNode.removeChild(printTemplte);
    $('#hiprint-printTemplate').empty(); // 先清空, 避免重复构建
    // 注意事项: 模板json(object)
    // 如果使用 vue ref创建的模板json, 需要使用 .value 获取 (确保内部能够使用 object.key 拿到对应数据就行)
    hiprintTemplate = newHiprintPrintTemplate(TEMPLATE_KEY, {
      template: templateRef.value, // 模板json(object)
      settingContainer: '#PrintElementOptionSetting', // 元素参数容器
    });
    // 构建 并填充到 容器中
    hiprintTemplate.design('#hiprint-printTemplate');
    console.log(hiprintTemplate);
  };
  /**
   * 浏览器打印
   */
  const print = () => {
    // 参数: 打印时设置 左偏移量，上偏移量
    const options = { leftOffset: -1, topOffset: -1 };
    // 扩展
    const ext = {
      callback: () => {
        console.log('浏览器打印窗口已打开');
      },
      styleHandler: () => {
        // 重写 文本 打印样式
        return '<style>.hiprint-printElement-text{color:red !important;}</style>';
      },
    };
    // 调用浏览器打印
    hiprintTemplate.print(printData, options, ext);
  };
  // ----------------- 模板对象 api 部分 -----------------
  /**
   * 旋转纸张
   */
  const rotatePaper = () => {
    hiprintTemplate.rotatePaper();
  };
  /**
   * 清空所有元素
   */
  const clearPaper = () => {
    hiprintTemplate.clear();
  };
  /**
   * 导出模板 json
   * 必须确保 hiprintTemplate 已成功创建
   */
  // const exportJson = () => {
  //   const json = hiprintTemplate.getJson();
  //   console.log(json);
  //   alert('导出成功! 请查看控制台输出');
  // };
  /**
   * 导出模板 json tid
   * 仅导出 options, 不导出 printElementType
   * 必须确保 hiprintTemplate 已成功创建
   */
  const exportJsonTid = () => {
    const json = hiprintTemplate.getJsonTid();
    console.log(json);
    const html = hiprintTemplate.getHtml(printData);
    const createDiv = document.createElement('div');
    createDiv.setAttribute('class', 'hidden-print-div hidden');
    document.body.appendChild(createDiv);
    setTimeout(() => {
      const container = document.querySelector('.hidden-print-div');
      container.innerHTML = '';
      container.innerHTML = html[0].innerHTML;
      const len = document.querySelectorAll('.hidden-print-div .hiprint-printPaper').length;
      console.log('🚀 ~ file: index.vue:115 ~ exportJson ~ len:', len);
      console.info(`共有${len}页`);
      alert(`导出成功! 请查看控制台输出共有${len}页`);
    }, 10);
  };
</script>

<style lang="less" scoped>
  /* 重写默认的一个样式 */
  ::v-deep(.rect-printElement-types .hiprint-printElement-type > li > ul > li > a) {
    padding: 4px 6px;
    color: #1296db;
    line-height: 1;
    height: auto;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  ::v-deep(.rect-printElement-types .hiprint-printElement-type > li > ul > li) {
    width: 33.333% !important;
    float: none;
  }

  ::v-deep(.rect-printElement-types .hiprint-printElement-type > li > ul) {
    display: flex;
    list-style: none;
    flex-wrap: wrap;
  }
  // 默认图片
  ::v-deep(.hiprint-printElement-image-content) {
    img {
      content: url('/@/assets/images/header.png');
    }
  }

  // 设计容器
  .card-design {
    overflow: hidden;
    overflow-x: auto;
    overflow-y: auto;
  }

  .title {
    font-size: 16px;
    margin: 10px 10px 10px 0;
  }
</style>
