<template>
  <!-- 标签预览 -->
  <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>
</template>
<script>
// import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { ELabel } from "../eLabel";

export default {
  name: "Preview",
  // ElImageViewer
  components: { MegaDrawer, Icon },
  props: {
    previewDialog: { type: Boolean, default: false },
    queryData: { type: Object, default: () => null },
  },
  data() {
    return {
      previewUrl: "",
      drawerPreview: false,
      previewData: {
        labelName: "",
        ipAddress: "",
        printerName: "",
      },
      imgSrc: "", // 预览图片
      jsonMapData: [],
      showViewer: false,
      srcList: [],
      formRouls: {
        ipAddress: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      printerList: [], // 打印机列表
      labelTypeOptions: [], // 打印机列表
      eLabel: null, // elabel对象
      previewObj: {},
    };
  },
  computed: {
    previewRules() {
      return this.formRouls;
    },
  },
  watch: {
    previewDialog(newVal, oldVal) {
      if (newVal && this.queryData) {
        this.handlePreview(this.queryData);
      }
    },
  },
  methods: {
    close() {
      this.$emit("close", false);
    },
    // 标签预览调试
    handlePreview(row) {
      Promise.all([
        this.getDictByCode("DIC:CORE:PS_PARAM"),
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/sys/config/list`),
      ]).then(([dataA, dataB]) => {
        this.parameterNameData = dataA.data.data;
        this.previewData.labelName = `${row.labelFileName}`;
        this.drawerPreview = true;
        this.jsonMapData = [];
        const obj = {};
        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
          );
          this.jsonMapData.push({
            label:
              result && result.label
                ? `${result.label}(${result.value})`
                : `${element}`,
            code: element,
          });
        });
        if (dataB.data.data && dataB.data.data.DEFAULT_PRINT_ADDRESS) {
          this.previewData.ipAddress = dataB.data.data?.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.$emit("close", false);
      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;
    },
  },
};
</script>

<style lang="scss" scoped>
.common-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 72px;
}
.preview_box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding-top: 20px;
}
.preview_img {
  width: 70%;
  cursor: pointer;
}
/deep/ .el-drawer__body {
  margin-bottom: 40px;
  overflow-y: auto;
}
/deep/ .el-image-viewer__close {
  color: #fff;
}
/deep/ .drawer-footer {
  position: static;
  bottom: 120px;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
/deep/ .el-input-group__append button.el-button {
  color: #fff;
  background: #409eff;
  border: none;
}

/* 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;
}
.form-btns {
  .el-form-item__content {
    margin-left: 100px !important;
  }
}
.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>
