<template>
  <div class="page-wrapper role-add">
    <div class="page-container">
      <a-form-model
        ref="addForm"
        :layout="'horizontal'"
        :model="searchForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        class="addForm"
      >
        <a-collapse
          v-model="activeName"
          :bordered="false"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row :gutter="24">
              <a-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
                <!-- 标签类型 -->
                <a-form-model-item :label="$t('LABEL_TYPE')" prop="tagId">
                  <a-select
                    v-model="searchForm.tagId"
                    :placeholder="$t('PLACESELECT')"
                    show-search
                    :filter-option="filterOption"
                    @change="choose"
                  >
                    <a-select-option
                      v-for="(item, index) in tagList"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <a-collapse
          v-model="activeNameB"
          :bordered="false"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="b" :header="$t('LABEL_INPUT_INFO')">
            <a-form-model
              ref="ruleForm"
              :layout="'horizontal'"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
              :model="searchForm"
            >
              <a-row :gutter="24">
                <a-col
                  v-for="(item, index) in dataArr"
                  :key="index"
                  :xs="12"
                  :sm="12"
                  :md="8"
                  :lg="8"
                  :xl="8"
                >
                  <a-form-model-item
                    style="width: 100%"
                    :label="item.labelName + '(' + item.parameterName + ')'"
                    :prop="searchForm[item.parameterName]"
                  >
                    <a-input
                      v-if="item.dataType === 'PARAM'"
                      :ref="item.parameterName"
                      v-model="searchForm[item.parameterName]"
                      :name="item.parameterName"
                      :placeholder="$t('PLACEENTER')"
                      @input="onInput()"
                      @keyup.enter.native="judgeKey($event, item.parameterName)"
                    />

                    <a-select
                      v-else
                      :ref="item.parameterName"
                      v-model="searchForm[item.parameterName]"
                      filterable
                      :placeholder="$t('PLACESELECT')"
                      :clearable="true"
                      @change="chooseP($event, item.parameterName)"
                      @keyup.enter.native="judgeKey($event, item.parameterName)"
                    >
                      <a-select-option
                        v-for="ele in item.tempArr"
                        :key="ele.value"
                        :value="ele.value"
                      >
                        {{ ele.label + `(${ele.value})` }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </a-collapse-panel>
        </a-collapse>
        <a-collapse
          v-model="activeNameC"
          :bordered="false"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="c" :header="$t('PRINT')">
            <a-form-model
              ref="formRef"
              :layout="'horizontal'"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
              :model="searchForm"
            >
              <a-row :gutter="24">
                <a-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
                  <!-- 标签类型 -->
                  <a-form-model-item :label="$t('	PRINT_NUM')">
                    <a-input-number
                      v-model="searchForm.PRINT_QTY"
                      style="width: 100%"
                      :min="1"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <!-- 标签类型 -->
                  <a-form-model-item :label="$t('PAPER_NUM')">
                    <a-input-number
                      v-model="searchForm.REPLICATE_QTY"
                      style="width: 100%"
                      :min="1"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <!-- 标签类型 -->
                  <a-form-model-item :label="$t('PRINTER_NAME')">
                    <a-select
                      v-model="searchForm.printerName"
                      :placeholder="$t('PLACESELECT')"
                    >
                      <a-select-option
                        v-for="(item, index) in printerList"
                        :key="index"
                        :value="item.value"
                      >
                        {{ item.label }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <a-button type="primary" :disabled="ifTrue" @click="printPreview1">
        <Icon type="icon-cur-search" :size="16" />
        {{ $t("PREVIEW") }}
      </a-button>

      <a-button
        v-if="hasAuth('OFFLINE_PRINT:PRINT')"
        type="primary"
        :disabled="ifTrue"
        @click="printPreview2"
      >
        <Icon type="icon-cur-printer" :size="16" />
        {{ $t("PRINT") }}
      </a-button>
    </div>
    <MegaModal
      :width="1200"
      :visible="modalVisible"
      :title="$t('PREVIEW')"
      @cancel="handleCancel"
    >
      <div
        v-if="imgSrc"
        class="preview_box"
        style="margin: auto auto 60px auto; text-align: center"
      >
        <img class="preview_img" :src="imgSrc" @click="handlePreviewImg()" />
      </div>
      <template slot="footer">
        <a-button @click="handleCancel">{{ $t("CANCEL") }}</a-button>
      </template>
    </MegaModal>
    <ImgViewer ref="megeIMg" :img-option="imgOption" :imgs="img">
      <img :imgs="img" />
    </ImgViewer>
  </div>
</template>
<script>
import {
  Drawer as MegaDrawer,
  Icon,
  Button,
  ImgViewer,
  Modal as MegaModal,
} from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { mapState } from "vuex";
import { ELabel } from "../eLabel";

let indexNext = 0;
export default {
  name: "Printall",
  components: {
    // eslint-disable-next-line vue/no-unused-components
    Button,
    ImgViewer,
    MegaModal,
    // eslint-disable-next-line vue/no-unused-components
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      activeName: "a",
      activeNameB: "b",
      activeNameC: "c",
      modalVisible: false,
      ifShowInputInfo: false,
      ifChoose: false,
      factoryIDD: "",
      tagListFac: [],
      ifTrue: true,
      printerList: [],
      isView: true,
      srcList: [],
      imgSrc: false, // 预览图片
      showViewer: false,
      linkAddress: "",
      getNames: [],
      searchForm: {
        tagId: "",
        PRINT_QTY: 1,
        REPLICATE_QTY: 1,
        PRINT_TYPE: "WP",
      },
      tagList: [],
      tempList: [],
      queryForm: {
        tagId: "",
      },
      dataArr: [],
      previewData: [],
      img: "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=85690711,3884201894&fm=27&gp=0.jpg",
      imgOption: {
        button: false,
        navbar: 0,
        title: false,
        toolbar: 0,
        isImgViewer: false,
      },
    };
  },
  computed: {
    ...mapState({
      systemConfig: (state) => state.app.systemConfig,
    }),
  },
  mounted() {
    this.init();
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text
        .toLowerCase()
        .includes(input.toLowerCase());
    },
    judgeKey(event, name) {
      /* eslint-disable-next-line */
      const _this = this;
      if (event.keyCode === 13) {
        // event.keyCode = 9;
        _this.dataArr.forEach((item, index) => {
          if (item.parameterName === name) {
            if (index === _this.dataArr.length - 1) {
              indexNext = 0;

              if (_this.dataArr[indexNext]) {
                _this.$refs[_this.dataArr[indexNext].parameterName][0].focus();
              }
              if (_this.$refs[name][0]) {
                setTimeout(() => {
                  _this.$refs[name][0].blur();
                }, 50);
              }
            } else {
              // eslint-disable-next-line no-plusplus
              ++indexNext;

              if (_this.dataArr[indexNext]) {
                _this.$refs[_this.dataArr[indexNext].parameterName][0].focus();
              }
              if (_this.$refs[name][0]) {
                setTimeout(() => {
                  _this.$refs[name][0].blur();
                }, 50);
              }
            }
          }
        });
      }
    },
    // 预览图片
    handlePreviewImg() {
      this.img = this.imgSrc;
      this.$refs.megeIMg.showImg();
    },
    closeViewer() {
      this.showViewer = false;
    },
    printPreview1() {
      this.isView = true;
      if (this.factoryIDD === "" && this.ifChoose) {
        this.$message.warning("请选择厂区", 2000);
        return;
      }
      this.printPreviewOrPrint1();
    },
    printPreview2() {
      this.isView = false;
      if (this.factoryIDD === "" && this.ifChoose) {
        this.$message.warning("请选择厂区", 2000);
        return;
      }
      this.printPreviewOrPrint2();
    },
    printPreviewOrPrint1() {
      if (!this.searchForm.tagId) {
        this.$message.warning("请选择标签号", 2000);
        return;
      }

      this.searchForm.isRoll = false;
      this.searchForm.LABEL_CODE = this.searchForm.tagId;
      this.searchForm.LABEL_TYPE = this.convertToType(this.searchForm.tagId);
      this.searchForm.LABEL_VERSION = this.convertToVerison(
        this.searchForm.tagId
      );
      this.searchForm.PRINT_IP_PORT = this.linkAddress;
      this.searchForm.PRINT_NAME = "";
      this.searchForm.factoryCode = this.factoryIDD;
      this.searchForm.SYSTEM_NAME = "MEGA_PLATFORM";
      this.$axios
        .post(
          `${ApiConstant.PREFIX_CORE}/api/print/get-result-view`,
          this.searchForm
        )
        .then((res) => {
          this.previewData = res.data.data;
          this.toShowPreview();
        })
        .catch(() => {
          // this.$message.warning('请完善所有信息',2000)
        });
    },
    printPreviewOrPrint2() {
      if (!this.searchForm.tagId) {
        this.$message.warning("请选择标签号", 2000);
        return;
      }
      if (!this.searchForm.printerName) {
        this.$message.warning("请选择打印机名称", 2000);
        return;
      }
      this.searchForm.isRoll = true;
      this.searchForm.LABEL_CODE = this.searchForm.tagId;
      this.searchForm.LABEL_TYPE = this.convertToType(this.searchForm.tagId);
      this.searchForm.LABEL_VERSION = this.convertToVerison(
        this.searchForm.tagId
      );
      this.searchForm.PRINT_IP_PORT = this.linkAddress;
      this.searchForm.factoryCode = this.factoryIDD;
      this.searchForm.SYSTEM_NAME = "MEGA_PLATFORM";
      this.$axios
        .post(
          `${ApiConstant.PREFIX_CORE}/api/print/get-result`,
          this.searchForm
        )
        .then((res) => {
          this.previewData = res.data.data;
          this.tohandleLabelPrint();
        })
        .catch(() => {});
    },
    onInput() {
      this.$forceUpdate();
    },
    // 数据处理
    transfer(list) {
      // 计算请求长度
      let length = 1;
      list.forEach((item) => {
        if (Array.isArray(item)) {
          length = item.length;
        }
      });
      // 组成数据
      const result = [];
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < length; i++) {
        result.push(
          list.map((item) => {
            if (Array.isArray(item)) {
              return item[i];
            }
            return item.toString();
          })
        );
      }
      return result;
    },
    // handleLabelPrint() {

    // },
    //
    tohandleLabelPrint() {
      // 初始化命令
      const command = this.eLabel.COMMAND;
      const previewObj = { ...this.previewData };
      command.Command = this.eLabel.ACTIONS.PRINT;
      command.PrinterName = this.previewData.printerName;
      command.LabelFile = this.previewData.labelFile;
      command.ColumnName = Object.keys(previewObj);
      // command.ValueList = [Object.values(previewObj)];
      command.ValueList = this.transfer(Object.values(previewObj));
      // command.ValueList = this.transfer(Object.values(data));
      const len = command.ValueList.length;
      const arr = [];
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < len; i++) {
        // eslint-disable-next-line no-plusplus
        for (let j = 0; j < previewObj.REPLICATE_QTY; j++) {
          arr.push(command.ValueList[i]);
        }
      }
      command.ValueList = arr;
      try {
        // 请求
        setTimeout(() => {
          this.eLabel.sendData(JSON.stringify(command));
          // this.factoryIDD = '';
        }, 500);
      } catch (error) {
        // this.factoryIDD = ''
      }

      // });
    },
    // 预览
    toShowPreview() {
      // 初始化命令
      const command = this.eLabel.COMMAND;
      const previewObj = { ...this.previewData };
      command.Command = this.eLabel.ACTIONS.PREVIEW;
      command.LabelFile = this.previewData.labelFile;
      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;
      // 请求
      try {
        this.eLabel.sendData(JSON.stringify(command));
        // this.factoryIDD = ''
      } catch (error) {
        // this.factoryIDD = ''
      }

      // });
    },
    convertToType(code) {
      let val = "";
      this.getNames.forEach((item, index) => {
        if (item.labelId === code) {
          val = item.labelType;
        }
      });
      return val;
    },
    convertToVerison(code) {
      let val = "";
      this.getNames.forEach((item, index) => {
        if (item.labelId === code) {
          val = item.labelVersion;
        }
      });
      return val;
    },
    init() {
      return Promise.all([
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/print/label/all`), // 标签管理
      ]).then(([labelRes]) => {
        this.tagList = [];
        this.getNames = labelRes.data.data;
        labelRes.data.data.forEach((item, index) => {
          this.tagList.push({
            label: item.labelCode,
            value: item.labelCode,
          });
        });
        this.linkAddress = this.systemConfig.DEFAULT_PRINT_ADDRESS;
        this.toLink();
      });
    },
    // 创建连接
    toLink() {
      // 如果未创建则新增
      if (!this.eLabel) {
        this.eLabel = new ELabel();
        this.eLabel.onData = (res) => {
          const obj = JSON.parse(res);
          // eslint-disable-next-line default-case
          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;
              this.modalVisible = true;
              break;
            case this.eLabel.ACTIONS.ERROR:
              this.$message.error(obj.MSG);
              // this.ifTrue = true;
              break;
          }
        };
        this.eLabel.onConnectSuccess = () => {
          // 连接成功
          this.ifTrue = false;
          this.$message.success(this.$t("CONNECT_SUCCESS"));
        };
      }
      // 建立连接
      this.eLabel.ipAddress = this.linkAddress; // this.previewData.ipAddress;
      this.eLabel.connect();
      // 获取打印机列表
      setTimeout(this.eLabel.getPrinters, 500);
    },
    chooseFac(e) {
      this.factoryIDD = e;
      this.$forceUpdate();
    },
    choose(e) {
      this.factoryIDD = "";
      this.searchForm.factoryId = "";
      this.searchForm = {
        tagId: e,
        PRINT_QTY: 1,
        REPLICATE_QTY: 1,
        PRINT_TYPE: "WP",
      };
      /* eslint-disable-next-line */
      const _this = this;
      // let params1 = {
      const labelId = e || "";
      // }
      // getResult
      if (e === "") {
        this.ifChoose = false;
        this.ifShowInputInfo = false;
        return;
      }

      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/find-site-code/${labelId}`)
        .then((res) => {
          this.tagListFac = [];
          if (res.data.data.length > 0) {
            this.ifChoose = true;
          } else {
            this.ifChoose = false;
            return;
          }

          res.data.data.forEach((item, index) => {
            this.tagListFac.push({
              label: item,
              value: item,
            });
          });
          if (res.data.data.length > 0) {
            this.searchForm.factoryId = this.tagListFac[0].value;
            this.factoryIDD = this.tagListFac[0].value;
          }
          this.ifChoose = true;
        })
        .catch(() => {
          // this.$message.warning('请完善所有信息',2000)
        });

      const params = {
        labelCode: e,
      };
      if (!e) {
        this.searchForm = {
          tagId: "",
          PRINT_QTY: 1,
          REPLICATE_QTY: 1,
          PRINT_TYPE: "WP",
        };
        return;
      }
      this.$nextTick(() => {
        _this.$refs.ruleForm.clearValidate();
      });

      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/attribute/get-input-value`, {
          params,
        })
        .then((res) => {
          // let arr = res.dada.data
          this.dataArr = res.data.data;
          if (this.dataArr.length > 0) {
            // 切换标签清空之前的组件记录
            this.ifShowInputInfo = true;
            // this.$refs.ruleForm.resetFields();
            // this.ifShowInputInfo = true
            this.dataArr.forEach((item, index) => {
              this.searchForm[item.parameterName] = "";

              if (item.dataType === "DICTIONARY") {
                const tempName = item.parameterName;
                // this.getParams(tempName)
                this.$axios
                  .get(
                    `${ApiConstant.PREFIX_CORE}/api/sys/dictData/${tempName}`
                  )
                  // eslint-disable-next-line no-shadow
                  .then((res) => {
                    const tem = res.data.data;
                    this.$set(item, "tempArr", tem);
                  });
                this.searchForm[item.parameterName] = item.defaultValue;
              }
            });
            // this.$forceUpdate()
          } else {
            this.ifShowInputInfo = false;
          }
        });
    },
    chooseP(event, item) {
      /* eslint-disable-next-line */
      const _this = this;
      _this.$set(_this.searchForm, item, event);
      _this.$forceUpdate();
    },
    handleCancel() {
      this.modalVisible = false;
    },
  },
};
/* eslint-enable */
</script>

<style lang="less" scoped>
/deep/.ant-form-item-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.container {
  display: flex;
  justify-content: space-between;
  height: auto;
  background-color: #f0f2f5;
  border-bottom: 10px solid #f0f2f5;
  &-left {
    width: 100%;
    background-color: #fff;
    &-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 57px;
      padding: 0 20px;
      border-bottom: 1px solid #e8e8e8;
      &-title {
        position: relative;
        height: auto;
        padding-left: 10px;
        font-size: 16px;
        line-height: 1;
      }
      &-right {
        display: flex;
        align-items: center;
        i {
          margin-top: 2px;
          color: #0ea8d0;
        }
        span {
          color: #999;
          font-size: 14px;
        }
      }
      &-description {
        i {
          font-size: 14px;
        }
        span {
          display: inline-block;
          width: 61px;
          height: 22px;
          margin-right: 12px;
          text-align: center;
          border-radius: 5px;
          opacity: 1;
        }
        span:nth-child(1) {
          color: #000;
          background: rgba(14, 168, 208, 0.12);
          border: 1px solid #0ea8d0;
        }
        span:nth-child(2) {
          color: #fff;
          background: #0ea8d0;
          border: 1px solid #0ea8d0;
        }
        span:nth-child(3) {
          color: #ff6126;
          background: rgba(14, 168, 208, 0.12);
          border: 1px solid #0ea8d0;
        }
      }
      &-title::before {
        position: absolute;
        top: 0;
        left: 0;
        display: block;
        width: 4px;
        height: 100%;
        background: linear-gradient(to bottom, #00caff, #0ea8d0);
        content: "";
      }
    }
    &-bottom {
      height: 450px;
      padding-right: 30px;
      overflow: auto;
      background: #e0eef2;
      background-image: repeating-linear-gradient(
          0deg,
          transparent,
          transparent 9px,
          #d1e1e5 9px,
          #d1e1e5 10px
        ),
        repeating-linear-gradient(
          -90deg,
          transparent,
          transparent 9px,
          #d1e1e5 9px,
          #d1e1e5 10px
        );
      background-size: 10px 10px;
      border: 20px solid #fff;
      .label-overview {
        position: relative;
        width: 700px;
        height: 386px;
        margin: 40px;
        background: rgba(255, 255, 255, 0.55);
        border: 2px solid #ccc;
        border-radius: 8px;
        box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.16);
      }
    }
  }
  &-right {
    width: 35%;
    background-color: #fff;
    border-left: 10px solid #f0f2f5;
    &-bottom {
      padding: 20px;
    }
    .left-container {
      height: 100%;
      overflow: auto;
    }
  }
}

/* CSS伪类用法 */
.horizontal-line {
  position: absolute;
  top: -48px;
  width: 100%;
  margin: 15px auto;
  color: #0ea8d0;
  font-weight: 400;
  font-size: 14px;
  text-align: center;
  border-right: 1px solid #0ea8d0;
  border-left: 1px solid #0ea8d0;
}
.horizontal-line div::after,
.horizontal-line div::before {
  position: absolute;
  top: 50%;
  width: 43%;
  height: 1px;
  background: #0ea8d0;
  content: "";
}

/* 调整背景横线的左右距离 */
.horizontal-line div::before {
  left: 0;
}
.horizontal-line div::after {
  right: 0;
}
.vertical-line {
  position: absolute;
  left: -32px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 100%;
  color: #0ea8d0;
  font-weight: 400;
  font-size: 14px;
  text-align: center;
  border-top: 1px solid #0ea8d0;
  border-bottom: 1px solid #0ea8d0;
  .title {
    display: inline-block;
    transform: rotate(-90deg);
  }
}
.vertical-line div::after,
.vertical-line div::before {
  position: absolute;
  left: 50%;
  width: 1px;
  height: 40%;
  background: #0ea8d0;
  content: "";
}

/* 调整背景横线的左右距离 */
.vertical-line div::before {
  top: 0;
}
.vertical-line div::after {
  bottom: 0;
}
.edited-color {
  color: #0fd19c;
}
.noedited-color {
  color: #0ea8d0;
}
.label-context {
  cursor: pointer;
}
.label-status {
  display: inline-block;
  width: 14px;
}
.QRCode {
  display: flex;
  flex-direction: column;
}
.edited {
  color: #000;
  background: #fff;
}
.not-edited {
  box-sizing: border-box;
  color: #ff6126 !important;
  background: #fff;
  border: 1px solid #ff6126 !important;
}
.active-code {
  background: #fff !important;
  border: 1px solid #0ea8d0 !important;
}
.active-text {
  color: #fff !important;
  background: #0ea8d0 !important;
  border: 1px solid #0ea8d0 !important;
}
</style>
