<template>
  <div class="print-page">
    <a-form-model ref="formRef" :model="formData" :rules="rules">
      <a-row>
        <a-col :span="8">
          <a-form-model-item
            class="info"
            prop="request"
            style="width: 100%; height: 100%"
            :label="$t('RESQUEST_DATA')"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
            <!-- 请求数据 -->
            <a-input v-model="formData.request" type="textarea" :rows="30" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <div class="info">
            <!-- 返回数据 -->
            <a-form-model-item
              class="info"
              prop="request"
              style="width: 100%; height: 100%"
              :label="$t('RESPONSE_DATA')"
              :label-col="{ span: 4 }"
              :wrapper-col="{ span: 20 }"
            >
              <!-- 请求数据 -->
              <a-input v-model="response" readonly type="textarea" :rows="30" />
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="8" style="padding-left: 30px">
          <div class="info">
            <!-- 返回数据 -->
            <a-form-model-item
              class="info"
              :label-col="{ span: 1 }"
              :wrapper-col="{ span: 23 }"
              style="width: 100%; height: 100%"
            >
              <!-- 请求数据 -->
              <a-input
                v-model="eLabelResponse"
                readonly
                type="textarea"
                :rows="30"
              />
            </a-form-model-item>
          </div>
        </a-col>
      </a-row>
      <div class="info">
        <!-- 操作 -->
        <span class="label" />
        <span class="value">
          <!-- 打印 -->
          <a-button
            v-if="hasAuth('PRINT_DEBUGGING:PRINT')"
            type="primary"
            @click="handleLabelPrint"
          >
            {{ $t("PRINT") }}
          </a-button>
        </span>
      </div>
    </a-form-model>
  </div>
</template>

<script>
import { validateJson } from "@mega-apps/utils";
import ApiConstant from "@/api/ApiConstant";
import { PS_PARAM } from "../constant";
import { ELabel } from "../utils/eLabel";

export default {
  name: "Print",
  data() {
    return {
      formData: {
        request: "",
      },
      response: "",
      eLabelResponse: "",
      paramNames: [],
      eLabel: null, // elabel对象
    };
  },
  computed: {
    rules() {
      return {
        request: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            validator: validateJson,
            message: this.$t("JSON_ERROR"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  mounted() {
    // 获取参数
    this.getDictByCode(PS_PARAM).then((res) => {
      this.paramNames = res.data.data;
      const obj = {};
      this.paramNames.forEach((item) => {
        obj[item.value] = item.label;
      });
      // 获取厂别
      const factoryLocale = localStorage.getItem("factoryLocale");
      if (factoryLocale && factoryLocale !== "undefined") {
        const nowfactory = JSON.parse(factoryLocale);
        obj.FACTORY = nowfactory.factoryCode;
      }
      // 打印数量
      obj.PRINT_QTY = 1;
      // 打印标签类别
      obj.LABEL_TYPE = "C";
      obj.PRINT_TYPE = "WP";
      obj.SYSTEM_NAME = "MES";
      obj.REPLICATE_QTY = "1";
      this.formData.request = JSON.stringify(obj, null, "\t");
    });
  },
  methods: {
    handleLabelPrint() {
      const requestData = JSON.parse(this.formData.request);
      this.$axios
        .post(`${ApiConstant.PREFIX_CORE}/api/print`, requestData)
        .then((res) => {
          if (res.data.code === 200) {
            this.response = JSON.stringify(res.data.data, null, "\t");
            if (!res.data.data.PRINT_NAME) {
              this.$message.error(this.$t("PRINTER_CONNECTION_FAILED"));
              return;
            }
            if (!res.data.data.PRINT_IP_PORT) {
              this.$message.error(this.$t("PRINTER_CONNECTION_FAILED"));
              return;
            }
            if (!res.data.data.LABEL_FILE) {
              this.$message.error(this.$t("NO_TEMPLATE_FILE"));
              return;
            }
            this.callELabel(res.data.data);
          }
        });
    },
    // 调用ELabel
    callELabel(data) {
      // 如果未创建则新增
      if (!this.eLabel) {
        this.eLabel = new ELabel();
        this.eLabel.onData = (res) => {
          this.eLabelResponse = res;
          // this.eLabel.disconnect()
        };
        // 建立连接
        this.eLabel.ipAddress = data.PRINT_IP_PORT;
        this.eLabel.connect();
        // 初始化命令
        const command = this.eLabel.COMMAND;
        command.Command = this.eLabel.ACTIONS.PRINT;
        command.PrinterName = data.PRINT_NAME;
        command.LabelFile = data.LABEL_FILE;
        command.ColumnName = Object.keys(data);
        command.ValueList = this.transfer(Object.values(data));
        // 请求
        setTimeout(() => {
          this.eLabel.sendData(JSON.stringify(command));
        }, 500);
      } else if (this.eLabel.ipAddress === data.PRINT_IP_PORT) {
        // 初始化命令
        const command = this.eLabel.COMMAND;
        command.Command = this.eLabel.ACTIONS.PRINT;
        command.PrinterName = data.PRINT_NAME;
        command.LabelFile = data.LABEL_FILE;
        command.ColumnName = Object.keys(data);
        command.ValueList = this.transfer(Object.values(data));
        // 请求
        this.eLabel.sendData(JSON.stringify(command));
      } else {
        this.eLabel.disconnect();
        this.eLabel = null;
        this.eLabel = new ELabel();
        this.eLabel.onData = (res) => {
          this.eLabelResponse = res;
          // this.eLabel.disconnect()
        };
        // 建立连接
        this.eLabel.ipAddress = data.PRINT_IP_PORT;
        this.eLabel.connect();
        // 初始化命令
        const command = this.eLabel.COMMAND;
        command.Command = this.eLabel.ACTIONS.PRINT;
        command.PrinterName = data.PRINT_NAME;
        command.LabelFile = data.LABEL_FILE;
        command.ColumnName = Object.keys(data);
        command.ValueList = this.transfer(Object.values(data));
        // 请求
        setTimeout(() => {
          this.eLabel.sendData(JSON.stringify(command));
        }, 500);
      }
    },
    // 数据处理
    transfer(list) {
      // 计算请求长度
      let length = 1;
      list.forEach((item) => {
        if (Array.isArray(item)) {
          length = item.length;
        }
      });
      // 组成数据
      const result = [];
      // eslint-disable-next-line
      for (let i = 0; i < length; i++) {
        result.push(
          list.map((item) => {
            if (Array.isArray(item)) {
              return item[i];
            }
            return item.toString();
          })
        );
      }
      return result;
    },
  },
};
</script>

<style lang="less" scoped>
.print-page {
  height: 60%;
  padding: 20px;
  .info {
    display: flex;
    line-height: 70px;
    .label {
      width: 80px;
      text-align: center;
    }
    .value {
      width: 360px;
      font-weight: bold;
    }
  }
}
</style>
