<template>
  <div class="label-repair">
    <!-- 操作工具栏 -->
    <el-form ref="form" :model="form" size="small" label-width="98px" v-if="false">
      <el-row>
        <el-col :span="7">
          <el-form-item label="打印模板" prop="BtReportId">
            <el-select
              v-model="form.BtReportId"
              placeholder="请选择打印模板"
              @change="reportChange"
            >
              <el-option
                v-for="item in btTemplateList"
                :key="item.id"
                :label="item.originName"
                :value="item.id"
              >
                <el-row :gutter="10">
                  <el-col :span="12">{{ item.originName }}</el-col>
                  <el-col :span="12" class="text-right">{{
                    item.version
                  }}</el-col>
                </el-row>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button
            class="btn-class"
            type="primary"
            size="small"
            @click="handleBatchPrint"
            >批量打印</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="list"
      border
      size="mini"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        label="物料编码"
        align="center"
        min-width="150"
        prop="erpMaterialNo"
      />
      <el-table-column
        label="物料条码"
        align="center"
        prop="batchNumber"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="物料批次"
        align="center"
        width="130"
        prop="wmsIncomingReceiptMaterialLots"
      />
      <el-table-column
        label="数量"
        align="center"
        width="90"
        prop="receiptQty"
      />
      <el-table-column
        label="不良数量"
        align="center"
        width="90"
        prop="badQty"
      />
      <el-table-column
        label="长度（m）"
        align="center"
        width="100"
        prop="length"
      />
      <el-table-column
        label="宽度(mm)"
        align="center"
        prop="width"
        width="60"
        show-overflow-tooltip
      />
      <el-table-column
        label="厚度(mm)"
        align="center"
        prop="thickness"
        width="60"
        show-overflow-tooltip
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="80"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-printer"
            @click="handleRepairPrint(scope.row)"
            >补打</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 东苏发单据打印 -->
    <IssuePrinit ref="issuePrint" />
  </div>
</template>

<script>
import {
  getIncomingLabelPrintDetail,
  getLabelPrintData,
  getRegisterMaterialLabelPrintData,
} from "@/api/wms/incoming/register";
// import IssuePrinit from '../../output/productionIssue/issueDetails/IssuePrinit.vue'
import IssuePrinit from "@/views/wms/output/productionIssue/issueDetails/IssuePrinit.vue";
const AccessTokenKey = "ACCESS_TOKEN";
import { getAppendixTableData } from "@/api/system/appendix.js";
import { printLabel } from "@/api/common";

export default {
  components: {
    IssuePrinit,
  },
  data() {
    return {
      printData: [],
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // WMS 仓库 仓库区域列表
      list: [],
      // 存放多选标签码列表
      selectedQrCodeList: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        materialLots: null,
      },
      // 单据打印参数
      tokens: "",
      baseUrl: "",
      reportId: "",
      // 表单参数
      form: {
        printer: "Fabulous F-BP43i",
        BtReportId: "",
        BtReportUrl: "",
        BtReportName: "",
        reportType: "0",
        HicoreReportName: "",
      },
      nextIndex: 0,
      nextPrintState: false,
      preview: false,
      previewUrlList: [],
      // 表单校验
      rules: {},
      // bartender模板列表
      btTemplateList: [],
    };
  },
  created() {
    this.getTemplateList();
    // 打印单据reportId
    this.reportId = this.$route.meta.reportId;
  },
  mounted() {
    this.tokens = localStorage.getItem(AccessTokenKey);
    this.baseUrl = process.env.VUE_APP_REPORT_API;
  },
  methods: {
    // 多选
    handleSelectionChange(list) {
      let x = list.length;
      this.selectedQrCodeList = [];
      while (x > 0) {
        this.selectedQrCodeList.push(list[x - 1].qrCode);
        x--;
      }
    },
    // 获取BT打印模板
    getTemplateList() {
      getAppendixTableData({
        pageNum: 1,
        pageSize: 999,
        printFlag: "1",
        filesMenuId: "1000000000000000001",
      }).then(({ data }) => {
        this.btTemplateList = data?.list ?? [];
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getIncomingLabelPrintDetail(this.queryParams)
        .then((response) => {
          this.list = response.data.list;
          this.total = response.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 批量打印
    async handleBatchPrint() {
      if (this.selectedQrCodeList?.length === 0) {
        return this.$modal.msgError("请选择需要打印的标签");
      }
      if (!this.form.BtReportUrl || !this.form.BtReportName) {
        return this.$modal.msgError("请选择需要打印的模板");
      }
      const { data } = await getRegisterMaterialLabelPrintData({
        qrCode: this.selectedQrCodeList.toString(","),
      });

      // 打印参数
      const printParams = {
        printJson: JSON.stringify(data.data),
        fileUrl: this.form.BtReportUrl,
      };
      try {
        await printLabel(printParams); // 打印
        this.selectedQrCodeList = [];
      } catch (error) {
        console.log(error);
      } finally {
      }
    },
    // 标签补打
    async handleRepairPrint(row) {
      if (
        process.env.VUE_APP_TITLE === "麦禾田WMS管理系统"
      ) {
        if (!this.form.BtReportUrl || !this.form.BtReportName) {
          return this.$modal.msgError("请选择需要打印的模板");
        }
        try {
          const { qrCode } = row;
          const params = {
            qrCode,
          };
          const printDetailData = await getLabelPrintData(params);
          this.$modal.msgSuccess("正在进行标签补打...");
          const { data: productsDetails } = printDetailData;
          this.printData.push(...productsDetails);
          // 打印参数
          const printParams = {
            printJson: JSON.stringify(this.printData),
            fileUrl: this.form.BtReportUrl,
          };
          await printLabel(printParams); // 打印
          this.printData = [];
        } catch (error) {
          console.log(error);
        }
      } else {
        const { qrCode } = row;
        const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&materialLots=${qrCode}`;
        this.$refs.issuePrint.dialogVisible = true;
        this.$refs.issuePrint.title = "单据打印";
        this.$refs.issuePrint.src = src;
      }
    },
    // 模板选择
    reportChange(e) {
      const fdIndex = this.btTemplateList.findIndex((ret) => ret.id === e);
      this.form.HicoreReportName = this.btTemplateList[fdIndex].sysName;
      this.form.BtReportName = this.btTemplateList[fdIndex].originName;
      this.form.BtReportUrl = this.btTemplateList[fdIndex].url;
    },
    reLoading(timeout) {
      const loading = this.$loading({
        lock: true,
        text: "标签打印中，请勿重复操作",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        loading.close();
      }, timeout * 1000);
    },
  },
};
</script>
<style lang="scss" scoped>
.btn-class {
  margin-left: 12px;
}
</style>
