<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :action-buttons="actionButtons"
      :page.sync="page"
      :total="total"
      :show-enable-flag="true"
      @beforeSearch="beforeSearch"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="searchPageData"
      @enable="
        (record) =>
          handleStatus(
            { status: 'Y', id: record.id },
            'ENABLED',
            'ENABLED_DATA_INFO',
            'ENABLE_SUCCESS'
          )
      "
      @disable="
        (record) =>
          handleStatus(
            { status: 'N', id: record.id },
            'DISABLED',
            'DISABLED_DATA_INFO',
            'DISABLE_SUCCESS'
          )
      "
    >
      <a-row slot="toolbar">
        <!-- 新增 -->
        <a-button
          v-if="hasAuth('LABEL_MANAGEMENT:ADD')"
          type="success"
          @click="handleAdd('add')"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('LABEL_MANAGEMENT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </a-row>
      <span slot="labelType" slot-scope="labelType">
        {{ dictCodeFormat(labelType) }}
      </span>
      <span slot="attachmentUrl" slot-scope="attachmentUrl">
        <a :href="attachmentUrl" class="text-download" download="">
          {{ attachmentUrl }}
        </a>
      </span>
      <template slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ getAttrValue(stateList, text) }}
        </span>
      </template>
    </MomTable>
    <!-- 新增、编辑弹框 -->
    <MegaDrawer
      :visible.sync="drawer"
      :title="drawerType !== 'edit' ? `${$t('ADD')}` : `${$t('EDIT')}`"
      width="520"
      @close="handleCancel"
    >
      <div slot="main">
        <a-form-model
          ref="formRef"
          layout="vertical"
          :model="formData"
          :rules="rules"
          size="medium"
          @submit.native.prevent
        >
          <!-- 标签类型 -->
          <a-form-model-item :label="$t('LABEL_TYPE')" prop="labelType">
            <a-select
              v-model="formData.labelType"
              :placeholder="$t('PLACESELECT')"
              show-search
              :filter-option="filterOption"
            >
              <a-select-option
                v-for="(item, index) in labelList"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <!-- 标签号 -->
          <a-form-model-item :label="$t('LABEL_ID')" prop="labelCode">
            <a-input
              v-model="formData.labelCode"
              :disabled="drawerType == 'edit'"
              onkeyup="value=value.replace(/[^\w\.\/]/gi,'')"
            />
          </a-form-model-item>
          <!-- 标签說明 -->
          <a-form-model-item :label="$t('LABEL_DESC')" prop="remark">
            <a-input v-model="formData.remark" />
          </a-form-model-item>
          <!-- 标签文件 -->
          <a-form-model-item :label="$t('LABEL_FILE')">
            <div style="position: absolute; top: -7px; left: -83px; color: red">
              *
            </div>
            <a-upload
              :action="url"
              :headers="headers"
              limit="1"
              :file-list="fileList"
              accept=".megax"
              :data="fileData"
              :before-upload="beforeUpload"
              @change="uploadSuccess"
            >
              <a-button id="initSlide" type="primary">
                <a-icon type="upload" /> {{ $t("SELECT_FILE") }}
              </a-button>
              {{ $t("UPLOAD_ONLY") }}megax{{ $t("FILE") }}
            </a-upload>
            <a-button
              style="position: absolute; top: -8px; left: 0"
              type="primary"
              @click="xuanze"
              ><a-icon type="upload" />{{ $t("SELECT_FILE") }}</a-button
            >
          </a-form-model-item>
          <a-row>
            <a-col>
              <div class="text-center mt-5">
                <img
                  v-if="previewUrl"
                  style="
                    max-width: 400px;
                    max-height: 400px;
                    margin-bottom: 15px;
                  "
                  :src="'data:image/png;base64,' + previewUrl"
                />
              </div>
            </a-col>
          </a-row>
          <!-- 标签文件 -->
          <a-form-model-item :label="$t('ATTACHMENT')">
            <MegaUploader
              ref="MegaUploader"
              :options="upLoadOptions"
              :file-list="attachmentFile"
              @fileRemoved="fileRemoved"
              @fileSuccess="fileSuccess"
            >
              <a-button icon="upload">{{ $t("SELECT_FILE") }}</a-button>
            </MegaUploader>
          </a-form-model-item>
          <a-form-model-item :label="$t('SCRIPT_CODE')" prop="script">
            <a-input v-model="formData.script" rows="8" type="textarea" />
          </a-form-model-item>
        </a-form-model>
      </div>
      <template slot="footer">
        <a-button type="primary" @click="handleSave('formRef')">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="handleCancel">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </template>
    </MegaDrawer>

    <!-- 标签预览 -->
    <MegaDrawer
      :visible.sync="drawerPreview"
      :title="$t('PREVIEW')"
      width="520"
      class="isCancelBtn"
      @close="handlePreviewCancel"
    >
      <div slot="main">
        <a-form-model
          ref="previewRef"
          layout="vertical"
          :model="previewData"
          :rules="previewRules"
        >
          <div class="scroll-form">
            <!-- 标签名 -->
            <a-form-model-item :label="$t('LABEL_FILE')">
              <a-input v-model="previewData.labelName" :disabled="true" />
            </a-form-model-item>
            <!-- 服务地址 -->
            <a-form-model-item :label="$t('SERVICE_ADDRESS')" prop="ipAddress">
              <a-input v-model="previewData.ipAddress">
                <a-button
                  slot="addonAfter"
                  type="primary"
                  :disabled="!previewData.ipAddress"
                  class="service_input"
                  @click="handleConnect"
                >
                  {{ $t("CONNECT") }}
                </a-button>
              </a-input>
            </a-form-model-item>
            <!-- 打印机 -->
            <a-form-model-item :label="$t('PRINTER_NAME')">
              <i-table-select
                v-model="previewData.printerName"
                :options="printerList"
              />
            </a-form-model-item>
          </div>

          <div class="horizontal-line mt-20 mb-20">
            <div>
              {{ $t("PRINT_PARAMS_SETTING") }}
            </div>
          </div>
          <div
            class="scroll-form"
            style="width: 100%; max-height: 260px; overflow-y: auto"
          >
            <div v-for="(item, index) in jsonMapData" :key="index">
              <a-form-model-item :label="item.label">
                <a-input v-model="previewData[item.code]" :rows="8"></a-input>
              </a-form-model-item>
            </div>
          </div>
          <div class="drawer-footer">
            <!-- 预览 -->
            <a-button
              type="primary"
              :disabled="!(eLabel && eLabel.socketOpened)"
              @click="handleLabelPreview"
            >
              <Icon type="icon-cur-search" :size="16" /> {{ $t("PREVIEW") }}
            </a-button>
            <!-- 打印 -->
            <a-button
              type="primary"
              :disabled="
                !(eLabel && eLabel.socketOpened && previewData.printerName)
              "
              @click="handleLabelPrint"
            >
              <Icon type="icon-cur-printer" :size="16" /> {{ $t("PRINT") }}
            </a-button>
            <a-button @click="handlePreviewCancel">
              <Icon type="icon-dir-f-rollback" :size="16" /> {{ $t("CANCEL") }}
            </a-button>
          </div>
          <div v-if="imgSrc" class="preview_box">
            <img
              class="preview_img"
              :src="imgSrc"
              @click="handlePreviewImg()"
            />
            <!-- <el-image-viewer
            v-if="showViewer"
            :on-close="closeViewer"
            :url-list="srcList"
          /> -->
          </div>
        </a-form-model>
      </div>
      <div slot="footer"></div>
    </MegaDrawer>
  </div>
</template>

<script>
import {
  Drawer as MegaDrawer,
  Icon,
  Uploader as MegaUploader,
} from "@mega-design/ui-vue";
import debounce from "lodash/debounce";
import { v1 as uuidv1 } from "uuid";
import Settings from "@/config/settings";
import { fetchFileUrl } from "@/utils/file";
import ApiConstant from "@/api/ApiConstant";
import { mapState } from "vuex";
import { ELabel } from "../eLabel";
import { LABEL_AUDIT_STATUS, PS_LABEL_TYPE, PS_PARAM } from "../constant";

let audit = false;
// eslint-disable-next-line
let audit_status = [];

export default {
  name: "Label",
  components: {
    MegaDrawer,
    Icon,
    MegaUploader,
  },
  // components: { ElImageViewer },
  data() {
    return {
      queryForm: {
        labelType: "",
      },
      upLoadOptions: {
        target: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload/chunk`,
        singleFile: true,
        headers: {
          Authorization: this.$auth.getToken("local"),
          tenantId:
            this.$store.state.app.systemConfig.TENANT_OPEN === "true"
              ? this.$store.state.account.tenantId
              : "",
        },
      },
      showViewer: false,
      srcList: [],
      url: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload`, // 上传文件路径
      headers: {
        Authorization: this.$auth.getToken("local"),
        tenantId:
          this.$store.state.app.systemConfig.TENANT_OPEN === "true"
            ? this.$store.state.account.tenantId
            : "",
      },
      attachmentFile: [],
      fileData: {
        fileName: "",
        labelFileName: "",
        rename: false,
        subDir: "/ElabelTemplate",
        script: "",
      },
      previewUrl: "",
      // 查询sort
      sortParams: null,
      paramNames: [],
      tableData: [],
      jsonMapData: [],
      stateList: [],
      total: 0,
      page: 1,
      drawer: false,
      drawerPreview: false,
      drawerType: "add",
      formData: {
        id: "",
        labelType: "",
        labelCode: "",
        fileName: "",
        fileUrl: "",
        attachmentUrl: "",
        remark: "",
        script: "",
      },
      labelList: [],
      previewData: {
        labelName: "",
        ipAddress: "",
        printerName: "",
      },
      actionButtons: [
        (h, value) => (
          <span
            style="cursor: pointer;"
            type="text"
            onClick={() => this.handlePreview(value.record)}
          >
            <a-icon
              class="operation-icon text-edit-blue text-15"
              type="zoom-in"
              title={this.$t("VIEW")}
            />
          </span>
        ),
        this.hasAuth("LABEL_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("LABEL_MANAGEMENT:DELETE") && "delete",
      ],
      form: null,
      imgSrc: "", // 预览图片
      printerList: [], // 打印机列表
      labelTypeOptions: [], // 打印机列表
      eLabel: null, // elabel对象
      fileList: [], // 文件列表
      formRouls: {
        ipAddress: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      previewObj: {},
      selectedRowKeys: [],
    };
  },
  computed: {
    ...mapState({
      systemConfig: (state) => state.app.systemConfig,
    }),
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    // 查询配置
    queryFormItem() {
      return this.$observable("queryFormItem", {
        labelType: {
          label: () => this.$t("LABEL_TYPE"),
          itemType: "select",
          optionsProps: {
            label: "label",
            value: "value",
          },
          options: [],
        },
      });
    },
    tableColumns() {
      return [
        // 标签类型
        {
          dataIndex: "labelType",
          title: () => this.$t("LABEL_TYPE"),
          scopedSlots: { customRender: "labelType" },
          width: 200,
        },
        // 标签号
        {
          dataIndex: "labelCode",
          title: () => this.$t("LABEL_ID"),
          width: 330,
        },
        // 附件
        {
          dataIndex: "attachmentUrl",
          title: () => this.$t("ATTACH"),
          sorter: false,
          scopedSlots: { customRender: "attachmentUrl" },
          minWidth: 400,
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          width: 80,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          sorter: false,
          title: () => this.$t("UPDATE_BY"),
          width: 120,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
        },
      ];
    },
    rules() {
      return {
        labelType: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        labelCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
    previewRules() {
      return this.formRouls;
    },
    // 标签类型key=>value对象
    labelTypeMap() {
      const obj = {};
      this.queryFormItem.labelType.options.forEach((item) => {
        obj[item.value] = item.label;
      });
      return obj;
    },
    // 审核状态key=>value对象
    labelStatusMap() {
      const obj = {};
      if (audit) {
        this.queryFormItem.labelStatus.options.forEach((item) => {
          obj[item.value] = item.label;
        });
      }
      return obj;
    },
  },
  beforeMount() {
    this.$axios
      .get(`${ApiConstant.PREFIX_CORE}/api/print/label/is-audit`)
      .then((res) => {
        audit = res.data.data;
      });
    // 获取审核状态字典
    this.getDictByCode(LABEL_AUDIT_STATUS).then((res) => {
      if (res.data.data && res.data.data.length > 0) {
        // eslint-disable-next-line
        audit_status = res.data.data;
      }
    });
  },
  mounted() {},
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text
        .toLowerCase()
        .includes(input.toLowerCase());
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/print/label/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status?.toString());
      return result ? result.label : "";
    },
    xuanze() {
      // 判断是否有标签号
      if (!this.formData.labelCode) {
        this.$message.warning(this.$t("PLACEENTER") + this.$t("LABEL_ID"));
        return;
      }
      const e = document.createEvent("MouseEvents");
      e.initEvent("click", true, true);
      document.getElementById("initSlide").dispatchEvent(e);
    },
    fileRemoved(row) {
      this.formData.attachmentUrl = "";
      this.attachmentFile.forEach((item, index) => {
        if (item.name === row.name && item.url === row.url) {
          this.attachmentFile.splice(index, 1);
        }
      });
    },
    fileSuccess(file) {
      this.$axios
        .put(
          `${ApiConstant.PREFIX_CORE}/api/sys/file/merge-chunks/${file.name}/${file.size}`
        )
        .then((res) => {
          this.formData.attachmentUrl = res.data.data?.fileUrl;
          this.attachmentFile = [];
          this.attachmentFile.push({
            uid: uuidv1(),
            name: res.data.data?.fileName,
            isComplete: true,
            percent: 0,
            url: res.data.data?.fileUrl,
          });
          this.$message.success(this.$t("ATTACHMENT_SUCCESS"));
        });
    },
    dictCodeFormat(val) {
      return this.labelTypeOptions.find((item) => item.value === val)?.label;
    },
    // 查后台分页查询
    searchPageData(queryData) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/label/search`, {
          params: queryData,
        })
        .then((res) => {
          if (res.data.data.records && res.data.data.records.length > 0) {
            res.data.data.records.forEach((item) => {
              if (
                item.attachmentUrl != null ||
                item.attachmentUrl !== undefined
              ) {
                if (item.attachmentUrl) {
                  // eslint-disable-next-line
                  item.attachmentUrl = fetchFileUrl(item.attachmentUrl, this);
                }
              }
            });
          }
          this.tableData = res.data.data?.records;
          this.total = res.data.data?.total;
        });
    },
    // 初始化选项
    beforeSearch() {
      // 获取标签
      this.getDictByCode(PS_LABEL_TYPE).then((res) => {
        this.queryFormItem.labelType.options = res.data.data;
        this.labelList = res.data.data;
        this.labelTypeOptions = res.data.data;
      });
      // 获取参数
      this.getDictByCode(PS_PARAM).then((res) => {
        this.paramNames = res.data.data;
      });
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.stateList = res?.data?.data || [];
      });
    },
    // 编辑
    handleEdit(row) {
      this.formData = { ...row };
      this.previewUrl = row.previewImg;
      if (row.labelFileName) {
        this.$set(this, "fileList", [{ name: row.labelFileName }]);
        this.$set(this.fileData, "labelFileName", row.labelFileName);
      } else {
        this.$set(this, "fileList", []);
      }
      if (row.attachmentUrl && row.attachmentUrl != null) {
        this.$set(this, "attachmentFile", [
          {
            name: row.attachmentUrl,
            url: row.attachmentUrl,
            isComplete: true,
            percent: 0,
            id: "1",
          },
        ]);
      } else {
        this.$set(this, "attachmentFile", []);
      }
      this.drawerType = "edit";
      this.drawer = true;
    },
    // 修改标签号
    inputLabelId(e) {
      let labelCode = e;
      if (labelCode) {
        // eslint-disable-next-line
        labelCode = labelCode?.replace(/[^\w\.\/]/gi, "");
        this.formData.labelCode = labelCode;
      }
    },
    // 新增或者编辑
    handleAdd() {
      this.attachmentFile = [];
      this.previewUrl = "";
      this.formData = {
        id: "",
        labelType: this.queryForm?.labelType,
        labelCode: "",
        fileName: "",
        fileUrl: "",
        attachmentUrl: "",
        remark: "",
        script: "",
      };
      this.drawerType = "add";
      this.drawer = true;
      this.fileList = [];
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(
                `${ApiConstant.PREFIX_CORE}/api/print/label/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$refs.MomTable?.query();
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 删除
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/print/label/${row.id}`)
            .then((res) => {
              this.$refs.MomTable?.query();
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.page = 1;
            });
        },
      });
    },
    // 保存&修改 防抖
    save() {
      // 编辑状态下，文件非必选
      if (!this.form && this.drawerType === "edit") {
        this.form = new FormData();
      }
      // 校验是否选择文件
      if (this.fileList.length < 1) {
        this.$message.warning(`${this.$t("PLEASE_SELECT_FILE_FIRST")}!`);
        return;
      }
      // 请求头支持文件
      const config = { headers: { "Content-Type": "multipart/form-data" } };
      // 请求内容支持文件
      if (this.formData.id) {
        this.form.set("id", this.formData.id);
      }
      if (this.formData.script) {
        this.form.set("script", encodeURIComponent(this.formData.script));
      } else {
        this.form.set("script", this.formData.script);
      }
      this.form.set("labelType", this.formData.labelType);
      this.form.set("labelCode", this.formData.labelCode);
      this.form.set("fileName", this.formData.fileName);
      this.form.set("fileUrl", this.formData.fileUrl);
      this.form.set("remark", this.formData.remark);
      this.form.set("labelFileName", this.fileData.labelFileName);
      this.form.set("attachmentUrl", this.formData.attachmentUrl);
      // 组请求
      const operate =
        this.drawerType === "edit"
          ? this.$axios.put(
              `${ApiConstant.PREFIX_CORE}/api/print/label`,
              this.form,
              config
            )
          : this.$axios.post(
              `${ApiConstant.PREFIX_CORE}/api/print/label`,
              this.form,
              config
            );
      operate
        .then(() => {
          if (this.drawerType === "edit") {
            this.$message.success(this.$t("EDIT_SUCCESS"));
          } else {
            this.$message.success(this.$t("ADD_SUCCESS"));
          }
          this.$refs.MomTable?.query();
          // 清空文件
          this.handleRemove();
          this.form = null;
          this.drawer = false;
        })
        .catch(() => {
          // eslint-disable-next-line
          for (const key in this.formData) {
            this.form.delete(key);
          }
        });
    },
    delaySave: debounce(function () {
      this.save();
    }, Settings.DO_FUNC_DELAY_TIME),
    handleSave(ref) {
      this.$refs[ref].validate((valid) => {
        if (valid) {
          this.delaySave();
        }
      });
    },
    // 对话框取消
    handleCancel() {
      this.$refs.formRef.clearValidate();
      this.$refs.formRef.resetFields();
      this.form = null;
      this.drawer = false;
      this.fileList = [];
    },
    // 获取查询条件
    getSearchParams() {
      const req = {
        page: this.page,
        size: this.$store.state.pagination.pageSize,
      };
      return { ...req, ...this.queryForm };
    },
    // 标签预览调试
    handlePreview(row) {
      Promise.all([this.getDictByCode("DIC:CORE:PS_PARAM")]).then(([dataA]) => {
        this.parameterNameData = dataA.data.data;
        this.previewData.labelName = `${row.labelFileName}`;
        this.drawerPreview = true;
        this.jsonMapData = [];
        this.previewObj = {};
        row.attrMap &&
          Object.keys(row.attrMap).forEach((element) => {
            this.$set(this.previewObj, element, "");
            this.previewData = {
              ...this.previewData,
              ...this.previewObj,
            };
            const result = this.parameterNameData.find(
              (item) => item.value === element
            );
            result &&
              this.jsonMapData.push({
                label:
                  result && result.label
                    ? `${result.label}(${result.value})`
                    : `${element}`,
                code: element,
              });
          });
        if (this.systemConfig.DEFAULT_PRINT_ADDRESS) {
          this.previewData.ipAddress = this.systemConfig.DEFAULT_PRINT_ADDRESS;
          this.$nextTick(() => {
            this.handleConnect();
          });
        } else {
          // 对不起，系统尚未配置打印服务地址，请先去"系统管理-系统设置"中配置后再次尝试!
          this.$message.error(this.$t("PLEASE_SET_PRINT_URL"));
        }
      });
    },
    // 关闭预览
    handlePreviewCancel() {
      if (this.eLabel) {
        this.eLabel.disconnect();
      }
      this.eLabel = null;
      this.imgSrc = null;
      this.printerList = [];
      this.drawerPreview = false;
    },
    handleConnect() {
      // 如果未创建则新增
      if (!this.eLabel) {
        this.eLabel = new ELabel();
        this.eLabel.onData = (res) => {
          const obj = JSON.parse(res);
          // eslint-disable-next-line
          switch (obj.CMD) {
            case this.eLabel.ACTIONS.GETPRINTERLIST:
              this.printerList = obj.DATA.map((v) => {
                return {
                  label: v,
                  value: v,
                };
              });
              break;
            case this.eLabel.ACTIONS.PREVIEW:
              // 预览操作,预览为图片(Base64编码)
              this.imgSrc = obj.DATA;
              break;
            case this.eLabel.ACTIONS.ERROR:
              this.$message.error(obj.MSG);
              break;
          }
        };
        this.eLabel.onConnectSuccess = () => {
          // 连接成功
          this.$message.success(this.$t("CONNECT_SUCCESS"));
        };
      }
      // 建立连接
      this.eLabel.ipAddress = this.previewData.ipAddress;
      this.eLabel.connect();
      // 获取打印机列表
      setTimeout(this.eLabel.getPrinters, 500);
    },
    // 标签预览功能
    handleLabelPreview() {
      this.$refs.previewRef.validate((valid) => {
        if (!valid) {
          return;
        }
        // 初始化命令
        const command = this.eLabel.COMMAND;
        const previewObj = { ...this.previewData };
        command.Command = this.eLabel.ACTIONS.PREVIEW;
        command.LabelFile = this.previewData.labelName;
        command.ColumnName = Object.keys(previewObj);
        const tempArr = [];
        const tempItemArr = [];
        if (Object.values(previewObj).length > 0) {
          Object.values(previewObj).forEach((item) => {
            if (item) {
              if (Array.isArray(item) === true) {
                tempArr.push(item);
              } else {
                tempItemArr.push(item);
                tempArr.push(tempItemArr);
              }
              // tempArr.push(item)
            } else {
              tempItemArr.push(item);
              tempArr.push(tempItemArr);
            }
          });
        }
        command.ValueList = tempArr;
        // 请求
        this.eLabel.sendData(JSON.stringify(command));
      });
    },
    // 标签打印
    handleLabelPrint() {
      this.$refs.previewRef.validate((valid) => {
        if (!valid) {
          return;
        }
        // 初始化命令
        const command = this.eLabel.COMMAND;
        const previewObj = { ...this.previewData };
        command.Command = this.eLabel.ACTIONS.PRINT;
        command.PrinterName = this.previewData.printerName;
        command.LabelFile = this.previewData.labelName;
        command.ColumnName = Object.keys(previewObj);
        command.ValueList = [Object.values(previewObj)];
        // 请求
        this.eLabel.sendData(JSON.stringify(command));
      });
    },
    // 预览图片
    handlePreviewImg() {
      this.showViewer = true;
      this.srcList = [];
      this.srcList.push(this.imgSrc);
    },
    closeViewer() {
      this.showViewer = false;
    },
    // 文件上传
    uploadSuccess(info) {
      this.fileList = [];
      this.fileList = info.fileList;
      if (info.file.status === "done") {
        this.form = new FormData();
        this.form.set("file", info.file.originFileObj);
        this.formData.fileName = info.file.response.data.fileName;
        this.formData.fileUrl = info.file.response.data.fileUrl;
        this.$message.success(this.$t("UPLOAD_SUCCESS"));
        this.$axios
          .post(`${ApiConstant.PREFIX_CORE}/api/print/label/preview`, this.form)
          .then((res) => {
            this.previewUrl = res.data.data;
          });
      } else if (info.file.status === "error") {
        this.$message.error(this.$t(response.msg));
      }
    },
    // 上传文件之前校验
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        if (file && file.name) {
          // const fileName = file.name.substr(0, file.name.lastIndexOf('.')) // 获取文件名称
          const fileSuffix = file.name.substr(file.name.lastIndexOf(".")); // 获取文件后缀名
          if (fileSuffix !== ".megax") {
            this.$message.warning(
              `${this.$t("UPLOAD_ONLY")}megax${this.$t("FILE")}`
            );
            // eslint-disable-next-line prefer-promise-reject-errors
            reject(false);
          }
          const newDate = new Date();
          const curYear = newDate.getFullYear();
          let curMonth = newDate.getMonth() + 1;
          if (curMonth < 10) {
            curMonth = `0${curMonth}`;
          }
          let curDate = newDate.getDate();
          if (curDate < 10) {
            curDate = `0${curDate}`;
          }
          let curHours = newDate.getHours();
          if (curHours < 10) {
            curHours = `0${curHours}`;
          }
          let curMinutes = newDate.getMinutes();
          if (curMinutes < 10) {
            curMinutes = `0${curMinutes}`;
          }
          let curSeconds = newDate.getSeconds();
          if (curSeconds < 10) {
            curSeconds = `0${curSeconds}`;
          }
          const curMilliseconds = newDate.getMilliseconds();
          const curTime =
            curYear +
            curMonth +
            curDate +
            curHours +
            curMinutes +
            curSeconds +
            curMilliseconds;
          this.fileData.fileName =
            // eslint-disable-next-line
          `${this.formData.labelCode.toLowerCase()}_` + `1.0.0_${curTime}.html`;
          this.fileData.labelFileName =
            `${this.formData.labelCode.toLowerCase()}_` +
            `1.0.0_${curTime}${file.name.substr(file.name.lastIndexOf("."))}`;
        }
        const isLt2M = file.size / 1024 / 1024 < 100; // 判断文件大小是否小于100M
        if (!isLt2M) {
          this.$message.error(
            `${this.$t("UPLOAD_FILE_CANNOT_EXCEED") + 100}MB!`
          );
          // eslint-disable-next-line prefer-promise-reject-errors
          reject(false);
        }
        resolve(true);
      });
    },
    // 清空文件
    handleRemove(file, fileList) {
      this.fileList = [];
      this.formData.fileName = "";
      this.formData.fileUrl = "";
    },
  },
};
</script>

<style lang="less" scoped>
.common-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 72px;
  cursor: pointer;
}
.preview_box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding-top: 20px;
}
.preview_img {
  width: 70%;
  cursor: pointer;
}
/deep/.drawer-footer {
  position: static;
  bottom: 120px;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

/* CSS伪类用法 */
.horizontal-line {
  position: relative;
  width: 100%;
  margin: 15px auto;
  color: #999;
  font-weight: 400;
  font-size: 14px;
  text-align: center;
}
.horizontal-line div::after,
.horizontal-line div::before {
  position: absolute;
  top: 50%;
  width: 40%;
  height: 1px;
  background: #fff;
  border-top: 1px dashed #999;
  content: "";
}

/* 调整背景横线的左右距离 */
.horizontal-line div::before {
  left: 0;
}
.horizontal-line div::after {
  right: 0;
}
.text-center .el-form-item__content {
  text-align: center;
}
.scroll-form {
  max-height: 480px;
  padding-right: 30px;
}
.fix-form {
  padding-right: 30px;
  overflow: hidden;
}
.isCancelBtn {
  /deep/.mega-design-drawer__footer {
    padding-top: 0;
    padding-bottom: 0;
  }
  /deep/.ant-input-group-addon {
    padding: 0;
  }
  /deep/.service_input {
    border: none;
    height: 34px;
  }
}
</style>
