<template>
  <div class="app-container">
    <div>基础设置</div>
    <div style="display: flex; justify-content: flex-start">
      <div class="left">
        <el-form ref="formRef" :model="form" label-width="100px">
          <el-form-item label="模板名称：">
            <el-input
              v-model="form.templateName"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item label="纸张尺寸：">
            <!-- <el-input
              v-model="form.pageSize"
              readonly
              style="width: 300px"
            ></el-input> -->
            <el-input
              v-model="form.pageWidth"
              placeholder="宽"
              style="width: 100px"
              oninput="value=value.replace(/[^0-9]/g,'')"
            ></el-input>
            <div style="padding: 0 10px">x</div>
            <el-input
              v-model="form.pageHeight"
              placeholder="高"
              style="width: 100px"
              oninput="value=value.replace(/[^0-9]/g,'')"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="模板设置：">
            <el-button type="primary" @click="print">打印</el-button>
          </el-form-item> -->
        </el-form>
        <div class="ele-container">
          <div style="font-weight: bold; margin-bottom: 20px">酒款信息</div>
          <div
            style="
              display: flex;
              flex-wrap: wrap;
              justify-content: flex-start;
              gap: 16px;
            "
          >
            <div
              class="ep-draggable-item item"
              v-for="(item, index) in list1"
              :key="index"
              :tid="item.tid"
            >
              {{ item.title }}
            </div>
          </div>

          <!-- <div
            id="provider-container1"
            class="container rect-printElement-types"
          ></div> -->
        </div>
        <div class="ele-container" style="margin: 10px 0">
          <div style="font-weight: bold; margin-bottom: 20px">生产信息</div>
          <div
            style="
              display: flex;
              flex-wrap: wrap;
              justify-content: flex-start;
              gap: 16px;
            "
          >
            <div
              class="ep-draggable-item item2"
              v-for="(item, index) in list2"
              :key="index"
              :tid="item.tid"
            >
              {{ item.title }}
            </div>
          </div>
        </div>
        <div>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>
      <div class="right">
        <div id="hiprint-printTemplate"></div>
      </div>
      <div class="right2">
        <div id="PrintElementOptionSetting" style="width: 400px"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import {
  hiprint,
  defaultElementTypeProvider,
  disAutoConnect,
} from "vue-plugin-hiprint";
import beerName from "./els/beerName";

import {
  getBreweryTagPrintTemplate,
  addBreweryTagPrintTemplate,
  updateBreweryTagPrintTemplate,
} from "@/api/brewery/printTemplate";
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
let hiprintTemplate;
const list1 = [
  {
    tid: "customModule.beerName",
    title: "产品名称",
  },
  {
    tid: "customModule.materials",
    title: "原料/辅料",
  },
  {
    tid: "customModule.netContent",
    title: "净含量",
  },
  {
    tid: "customModule.beerAbv",
    title: "酒精度",
  },
  {
    tid: "customModule.beerIbus",
    title: "苦度",
  },
  {
    tid: "customModule.beerOg",
    title: "原麦汁浓度度",
  },
  {
    tid: "customModule.shelfLife",
    title: "保质期",
  },
  {
    tid: "customModule.productionDate",
    title: "生产日期",
  },
  {
    tid: "customModule.batchSn",
    title: "批次号",
  },
];
const list2 = [
  { tid: "customModule.executeStandard", title: "执行标准" },
  { tid: "customModule.qualityLevel", title: "质量等级" },
  { tid: "customModule.storageMethod", title: "存储方式" },
  { tid: "customModule.manufacturer", title: "生产商" },
  { tid: "customModule.distributor", title: "委托生产商" },
  { tid: "customModule.productionAddress", title: "生产地址" },
  { tid: "customModule.companyName", title: "公司地址" },
  { tid: "customModule.contactPerson", title: "产地" },
  { tid: "customModule.contactPhone", title: "联系电话" },
  // { tid: "defaultModule.barcode", title: "条形码" },
  { tid: "defaultModule.qrcode", title: "二维码" },
  { tid: "customModule.remarks", title: "注意事项" },
  { tid: "customModule.licenseNumber", title: "生产许可证编号" },

  { tid: "customModule.numberInChina", title: "境外生产企业在华注册编号" },
];
// 文本：defaultModule.text
// 图片：defaultModule.image
// 长文：defaultModule.longText
// 表格：defaultModule.table
// 空白表格：defaultModule.emptyTable
// 自定义文本：defaultModule.customText
// 横线：defaultModule.hline
// 竖线：defaultModule.vline
// 矩形：defaultModule.rect
// 椭圆：defaultModule.oval
// 条形码：defaultModule.barcode
// 二维码：defaultModule.qrcode
disAutoConnect(); // 禁用自动连接

const templateId = ref(null);
hiprint.init({
  providers: [defaultElementTypeProvider(), , beerName()],
});
onMounted(() => {
  buildLeftElement();
  buildDesigner();
  templateId.value = route.query.id;
  if (templateId.value) {
    getTemplateInfo();
  }
});
function getTemplateInfo() {
  getBreweryTagPrintTemplate(templateId.value).then((res) => {
    form.value.templateName = res.data.templateName;
    // form.value.pageSize = `${res.data.pageWidth}MM * ${res.data.pageHeight}MM`;
    form.value.pageHeight = res.data.pageHeight;
    form.value.pageWidth = res.data.pageWidth;
    hiprintTemplate.update(JSON.parse(res.data.elements));
    // buildDesigner();
  });
}
const form = ref({
  pageSize: "76MM * 120MM",
});

function save() {
  let arr = hiprintTemplate.getJson().panels[0].printElements;
  // console.log(data.panels[0].printElements);
  if (templateId.value) {
    let data = {
      id: templateId.value,
      elements: JSON.stringify(hiprintTemplate.getJson()),
      templateName: form.value.templateName,
      pageWidth: form.value.pageWidth,
      pageHeight: form.value.pageHeight,
    };
    updateBreweryTagPrintTemplate(data).then((res) => {
      proxy.$message.success("保存成功");
      router.go(-1);
    });
  } else {
    let data = {
      elements: JSON.stringify(hiprintTemplate.getJson()),
      templateName: form.value.templateName,
      pageWidth: form.value.pageWidth,
      pageHeight: form.value.pageHeight,
    };
    addBreweryTagPrintTemplate(data).then((res) => {
      proxy.$message.success("保存成功");
      router.go(-1);
    });
  }
}
function cancel() {
  router.go(-1);
}
function addProvider() {
  let panel = hiprintTemplate.addPrintPanel({
    width: 100,
    height: 130,
    // paperFooter: 340,
    // paperHeader: 10,
  });
  //文本
  panel.addPrintText({
    options: {
      width: 140,
      height: 15,
      top: 20,
      left: 20,
      title: "你好，世界！",
      textAlign: "center",
    },
  });
  hiprintTemplate.print({});
}

function print() {
  let printData = { name: "CcSimple" };
  // 参数: 打印时设置 左偏移量，上偏移量
  let options = { leftOffset: -1, topOffset: -1 };
  // 扩展
  let ext = {
    callback: () => {
      console.log("浏览器打印窗口已打开");
    },
    styleHandler: () => {
      // 重写 文本 打印样式
      return "<style>.hiprint-printElement-text{color:red !important;}</style>";
    },
  };
  // 调用浏览器打印
  hiprintTemplate.print(printData, options, ext);
}
const buildLeftElement = () => {
  // eslint-disable-next-line no-undef
  hiprint.PrintElementTypeManager.buildByHtml($(".ep-draggable-item"));
};

const buildDesigner = () => {
  // eslint-disable-next-line no-undef
  $("#hiprint-printTemplate").empty(); // 先清空, 避免重复构建
  hiprintTemplate = new hiprint.PrintTemplate({
    settingContainer: "#PrintElementOptionSetting", // 元素参数容器
    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" },
    ],
    onDataChanged: (type, json) => {
      // 模板发生改变回调
      console.log(type); // 新增、移动、删除、修改(参数调整)、大小、旋转
      console.log(json); // 返回 template
    },
  });
  // 构建 并填充到 容器中
  hiprintTemplate.design("#hiprint-printTemplate");
};
</script>

<style scoped lang="scss">
.left {
  width: 400px;
  min-height: 100vh;
  background-color: #fff;
  padding: 10px;
  .ele-container {
    padding: 20px;
    background-color: #f5f5f5;
    margin-bottom: 10px;
    .item {
      width: 100px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      border: 1px solid #ccc;
      cursor: pointer;
      margin-bottom: 10px;
    }
    .item2 {
      min-width: 100px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      border: 1px solid #ccc;
      cursor: pointer;
      margin-bottom: 10px;
    }
  }
}
.right {
  width: 800px;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 10px;
}
</style>
