<template>
  <a-card class="parent-card" :bodyStyle="{height:'100%',padding:0}">
    <a-row :gutter="[8, 0]" style="height:100%;margin:0">
      <div class="left">
        <div
          style="height: 100vh;overflow:auto" 
          class="rect-printElement-types hiprintEpContainer"
        >
          <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>文本</span>
              </template>
              <a class="ep-draggable-item" tid="defaultModule.text">
                <span class="glyphicon glyphicon-text-width" aria-hidden="true"></span>
              </a>
            </a-tooltip>
          </div>
          <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>图片</span>
              </template>
              <a class="ep-draggable-item" tid="defaultModule.image" style>
                <span class="glyphicon glyphicon-picture" aria-hidden="true"></span>
              </a>
            </a-tooltip>
          </div>
          <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>长文</span>
              </template>
              <a class="ep-draggable-item" tid="defaultModule.longText">
                <span class="glyphicon glyphicon-subscript" aria-hidden="true"></span>
              </a>
            </a-tooltip>
          </div>
          <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>html</span>
              </template>
              <a class="ep-draggable-item" tid="defaultModule.html" style="">
                <span class="glyphicon glyphicon-header" aria-hidden="true"></span>
              </a>
            </a-tooltip>
          </div>
          <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>条形码</span>
              </template>
                <a class="ep-draggable-item" tid="defaultModule.barcode" style="">
                  <span class="glyphicon glyphicon-barcode" aria-hidden="true"></span>
                </a>
              </a-tooltip>
            </div>
            <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>二维码</span>
              </template>
                <a class="ep-draggable-item" tid="defaultModule.qrcode" style="">
                  <span class="glyphicon glyphicon-qrcode" aria-hidden="true"></span>
                </a>
              </a-tooltip>
            </div>
          <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>横线</span>
              </template>
              <a class="ep-draggable-item" tid="defaultModule.hline" style>
                <span
                  class="glyphicon glyphicon-resize-horizontal"
                  aria-hidden="true"
                ></span>
              </a>
            </a-tooltip>
          </div>
          <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>竖线</span>
              </template>
              <a class="ep-draggable-item" tid="defaultModule.vline" style>
                <span
                  class="glyphicon glyphicon-resize-vertical"
                  aria-hidden="true"
                ></span>
              </a>
            </a-tooltip>
          </div>
          <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>矩形</span>
              </template>
              <a class="ep-draggable-item" tid="defaultModule.rect">
                <span class="glyphicon glyphicon-unchecked" aria-hidden="true"></span>
              </a>
            </a-tooltip>
          </div>
          <div class="drag_item_box">
            <a-tooltip placement="right">
              <template #title>
                <span>圆形</span>
              </template>
              <a class="ep-draggable-item" tid="defaultModule.oval">
                <span class="glyphicon glyphicon-record" aria-hidden="true"></span>
              </a>
            </a-tooltip>
          </div>
          <template v-if="defaultList.length>0">
          <div class="drag_item_box" v-for="(item, index) in defaultList" :key="index">
            <a-tooltip placement="right">
              <template #title>
                <span>{{ item.title }}</span>
              </template>
              <a class="ep-draggable-item" :tid="item.tid" style>
                <span class="glyphicon glyphicon-th" aria-hidden="true"></span>
              </a>
            </a-tooltip>
          </div>
        </template>
        </div>
      </div>
      <div class="content">
        <div
          style="
            display: flex;
            flex-direction: column;
            position: fixed;
            height: 32px;
            z-index: 2;
            top: 64px;
          "
        >
          <a-space>
            <a-button-group>
              <template v-for="(value, type) in paperTypes">
                <a-button
                  :type="curPaperType === type ? 'primary' : 'info'"
                  @click="setPaper(type, value)"
                >
                  {{ type }}
                </a-button>
              </template>
              <a-popover
                v-model="paperPopVisible"
                title="设置纸张宽高(mm)"
                trigger="click"
              >
                <div slot="content">
                  <a-input-group compact style="margin: 10px 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="otherPaper"
                    >确定</a-button
                  >
                </div>
                <a-button :type="'other' == curPaperType ? 'primary' : ''"
                  >自定义纸张</a-button
                >
              </a-popover>
            </a-button-group>
            <a-button type="primary" icon="redo" @click="rotatePaper()">旋转</a-button>
            <a-button type="primary" icon="eye" @click="preView"> 预览 </a-button>
            <a-button type="primary" icon="printer" @click="print"> 打印 </a-button>
            <a-popconfirm
              title="是否确认清空?"
              okType="danger"
              okText="确定清空"
              cancelText="取消"
              @confirm="clearPaper"
            >
              <a-icon slot="icon" type="question-circle-o" style="color: red" />
              <a-button type="danger" style="width: 82px;"> 清空 </a-button>
            </a-popconfirm>
          </a-space>
        </div>
        <a-card class="card-design">
          <div id="hiprint-printTemplate" class="hiprint-printTemplate"></div>
        </a-card>
      </div>
      <div class="right params_setting_container">
        <!-- <a-card  :bordered="false" class="hinnn-layout-sider"> -->
        <!-- <a-row class="hinnn-layout-sider"> -->
        <div id="PrintElementOptionSetting" class="hinnn-layout-sider"></div>
        <!-- </a-row> -->
        <!-- </a-card> -->
      </div>
    </a-row>
    <!-- 预览 -->
    <print-preview ref="preView" />
  </a-card>
</template>

<script>
import { defaultElementTypeProvider, hiprint } from "./../index";
import printPreview from "./preview";
import fontSize from "./font-size.js";
import scale from "./scale.js";

let hiprintTemplate;

export default {
  name: "printDesign",
  components: { printPreview },
  props: {
    printApiData: {
      type: Object|Array,
      default: {},
    },
    defaultList: {
      type: Array,
      default: [],
    },
    panel: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      template: null,
      curPaper: {
        type: "A4",
        width: 210,
        height: 296.6,
      },
      paperTypes: {
        A3: {
          width: 420,
          height: 296.6,
        },
        A4: {
          width: 210,
          height: 296.6,
        },
        A5: {
          width: 210,
          height: 147.6,
        },
        B3: {
          width: 500,
          height: 352.6,
        },
        B4: {
          width: 250,
          height: 352.6,
        },
        B5: {
          width: 250,
          height: 175.6,
        },
      },
      // 自定义纸张
      paperPopVisible: false,
      paperWidth: "220",
      paperHeight: "80",
      // 缩放
      scaleValue: 1,
      scaleMax: 5,
      scaleMin: 0.5,
      // 导入导出json
      jsonIn: "",
      jsonOut: "",
    };
  },
  computed: {
    curPaperType() {
      let type = "other";
      let types = this.paperTypes;
      for (const key in types) {
        let item = types[key];
        let { width, height } = this.curPaper;
        if (item.width === width && item.height === height) {
          type = key;
        }
      }
      return type;
    },
  },
  mounted() {
    console.log("son ** printApiData", this.printApiData);
    this.init();
  },
  methods: {
    init() {
      hiprint.init({
        providers: [new defaultElementTypeProvider(this.defaultList)],
      });
      // 还原配置
      hiprint.setConfig();
      // 替换配置
      hiprint.setConfig({
        optionItems: [
          fontSize,
          scale,
          (function () {
            function t() {
              this.name = "zIndex";
            }

            return (
              (t.prototype.css = function (t, e) {
                if (t && t.length) {
                  if (e) return t.css("z-index", e);
                }
                return null;
              }),
              (t.prototype.createTarget = function (t) {
                // console.log('createTarget t: ', t);
                return (
                  (this.target = $(
                    ""
                    // '<div class="hiprint-option-item hiprint-option-item-row">\n        <div class="hiprint-option-item-label">\n        元素层级2\n        </div>\n        <div class="hiprint-option-item-field">\n        <input type="number" class="auto-submit"/>\n        </div>\n    </div>'
                  )),
                  this.target
                );
              }),
              (t.prototype.getValue = function () {
                var t = this.target.find("input").val();
                if (t) return parseInt(t.toString());
              }),
              (t.prototype.setValue = function (t) {
                this.target.find("input").val(t);
              }),
              (t.prototype.destroy = function () {
                this.target.remove();
              }),
              t
            );
          })(),
        ],
        movingDistance: 2.5,
        text: {
          tabs: [
            // 隐藏部分
            {
              // name: '测试', // tab名称 可忽略
              options: [], // 必须包含 options
            }, // 当修改第二个 tabs 时,必须把他之前的 tabs 都列举出来.
            {
              name: "样式配置",
              options: [
                {
                  name: "scale",
                  after: "transform", // 自定义参数，插入在 transform 之后
                  hidden: false,
                },
              ],
            },
          ],
          supportOptions: [
            {
              name: "styler",
              hidden: true,
            },
            {
              name: "scale", // 自定义参数，supportOptions 必须得添加
              after: "transform", // 自定义参数，插入在 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,
                },
              ],
            },
          ],
        },
      });
      // eslint-disable-next-line no-undef
      hiprint.PrintElementTypeManager.buildByHtml($(".ep-draggable-item"));
      $("#hiprint-printTemplate").empty();
      let self = this;
      if(self.panel.curPaper){
        let curPaper = self.panel.curPaper;
        this.curPaper = { type: curPaper.type, width: curPaper.width, height: curPaper.height };
      }
      this.template = hiprintTemplate = new hiprint.PrintTemplate({
        template: self.panel,
        // 自定义可选字体
        // 或者使用 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, // 是否需要 撤销重做功能
        onDataChanged: (type, json) => {
          // console.log(type); // 新增、移动、删除、修改(参数调整)、大小、旋转
          // console.log(json); // 返回 template
        },
        onUpdateError: (e) => {
          // console.log(e);
        },
        settingContainer: "#PrintElementOptionSetting",
        paginationContainer: ".hiprint-printPagination",
      });
      hiprintTemplate.design("#hiprint-printTemplate", { grid: true });
      // console.log(hiprintTemplate);
      // 获取当前放大比例, 当zoom时传true 才会有
      this.scaleValue = hiprintTemplate.editingPanel.scale || 1;
      this.clickTemplate();
    },
    clickTemplate(){
      //点亮右边属性栏
      $(".hiprint-printPaper.hidroppable.design.grid")[0].click();
    },
    getDefaultConfig(tid, title, tableName, fields, columns) {
      return {
        tid: tid,
        title: title,
        type: "table",
        options: {
          field: tableName,
          tableHeaderRepeat: "first",
          tableFooterRepeat: "last",
          fields: fields,
        },
        editable: true,
        columnDisplayEditable: true, //列显示是否能编辑
        columnDisplayIndexEditable: true, //列顺序显示是否能编辑
        columnTitleEditable: true, //列标题是否能编辑
        columnResizable: true, //列宽是否能调整
        columnAlignEditable: true, //列对齐是否调整
        isEnableEditField: true, //编辑字段
        isEnableContextMenu: true, //开启右键菜单 默认true
        isEnableInsertRow: true, //插入行
        isEnableDeleteRow: true, //删除行
        isEnableInsertColumn: true, //插入列
        isEnableDeleteColumn: true, //删除列
        isEnableMergeCell: true, //合并单元格
        columns: columns,
      };
    },
    /**
     * 设置纸张大小
     * @param type [A3, A4, A5, B3, B4, B5, other]
     * @param value {width,height} mm
     */
    setPaper(type, value) {
      try {
        if (Object.keys(this.paperTypes).includes(type)) {
          this.curPaper = { type: type, width: value.width, height: value.height };
          hiprintTemplate.setPaper(value.width, value.height);
        } else {
          this.curPaper = { type: "other", width: value.width, height: value.height };
          hiprintTemplate.setPaper(value.width, value.height);
        }
      } catch (error) {
        this.$message.error(`操作失败: ${error}`);
      }
    },
    otherPaper() {
      let value = {};
      value.width = this.paperWidth;
      value.height = this.paperHeight;
      this.paperPopVisible = false;
      this.setPaper("other", value);
    },
    changeScale(big) {
      let scaleValue = this.scaleValue;
      if (big) {
        scaleValue += 0.1;
        if (scaleValue > this.scaleMax) scaleValue = 5;
      } else {
        scaleValue -= 0.1;
        if (scaleValue < this.scaleMin) scaleValue = 0.5;
      }
      if (hiprintTemplate) {
        // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
        hiprintTemplate.zoom(scaleValue);
        this.scaleValue = scaleValue;
      }
    },
    rotatePaper() {
      if (hiprintTemplate) {
        hiprintTemplate.rotatePaper();
      }
    },
    preView() {
      // 测试, 点预览更新拖拽元素
      hiprint.updateElementType("defaultModule.text", (type) => {
        type.title = "这是更新后的元素";
        return type;
      });
      // console.log('this.printData: ', this.printData);
      this.$refs.preView.show(hiprintTemplate, this.printApiData);
    },
    print() {
      hiprintTemplate.print(
        this.printApiData,
        {},
        {
          callback: () => {
            // console.log('callback')
            this.waitShowPrinter = false;
          },
        }
      );
    },
    clearPaper() {
      try {
        hiprintTemplate.clear();
      } catch (error) {
        this.$message.error(`操作失败: ${error}`);
      }
    },
    getJson() {
      let json = hiprintTemplate.getJson();
      json.curPaper = this.curPaper;
      let jsonOut = JSON.stringify(json || {});
      return jsonOut;
    },
  },
};
</script>

<style lang="less" scoped>
.ant-card{
  background: transparent;
  &.parent-card{
    background: #f0f0f0;
    height: 100%;
   
  }
}

// 拖拽
.drag_item_box {
  font-size: 16px;
  padding: 12px 0;
}

.drag_item_box > div {
  height: 100%;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.drag_item_box > div > a {
  text-align: center;
  text-decoration-line: none;
}

.drag_item_box > div > a > span {
  font-size: 28px;
}

.drag_item_box > div > a > p {
  margin: 0;
}

.drag_item_title {
  font-size: 16px;
  padding: 12px 6px 0 6px;
  font-weight: bold;
}

// 默认图片
/deep/ .hiprint-printElement-image-content {
  img {
    content: url("~@/assets/logo.png");
  }
}

// 辅助线样式
/deep/ .toplineOfPosition {
  border: 0;
  border-top: 1px dashed purple;
}

/deep/ .bottomlineOfPosition {
  border: 0;
  border-top: 1px dashed purple;
}

/deep/ .leftlineOfPosition {
  border: 0;
  border-left: 1px dashed purple;
}

/deep/ .rightlineOfPosition {
  border: 0;
  border-left: 1px dashed purple;
}

// 设计容器
.card-design {
  overflow: hidden;
  overflow-x: auto;
  overflow-y: auto;
  margin-top: 115px; 
  height: calc(100% - 125px);
}

// 左侧菜单固定
.left {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 60px;
  text-align: center;
  background: #fff;
  border-radius: 16px;
}

.content {
  width: calc(100% - 540px);
  margin-left: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
  height:100%;
  background: #fff;
  border-radius: 16px;
}

/deep/ .content .ant-card-bordered {
  border: none; 
}

.right {
  width: 460px;
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  height:100%;
  background: #fff;
  border-radius: 16px;
}

/deep/ .hiprintEpContainer .ant-card-body {
  padding: 0;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0; 
  padding: 20px; 
}
</style>
