<template>
  <div>

    <el-form :model="formData" :rules="formRules" ref="dataForm">
      <el-row type="flex" justify="end">
        <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px;margin-top: -10px">
          <el-button
            type="primary"
            @click.native="generateQRCodeText()"
            :loading="loading"
          >生成内部码
          </el-button
          >

          <el-button
            type="primary"
            @click.native="printStockOrderDetailPDF()"

            :loading="loading"
          >打印全部
          </el-button
          >
        </el-button-group>
      </el-row>


      <el-row :gutter="20">
        <el-col :span="3">
          <div class="ao-text">
            <span>单据号：</span>
          </div>
        </el-col>
        <el-col :span="7">
          <el-form-item prop="billNo">
            <el-input v-model="formData.recordKey" auto-complete="off" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <div class="ao-text">
            <span>单据日期：</span>
          </div>
        </el-col>
        <el-col :span="7">
          <el-form-item prop="createTime">
            <el-input v-model="formData.createTime" auto-complete="off" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <el-table v-loading="loading" :data="codeArray" style="width: 100%;" max-height="350" height="350"
                highlight-current-row
                border
                ref="multipleTable">
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="码" prop="udiCode"></el-table-column>

        <el-table-column label="状态" width="120">
          <template slot-scope="scope">
            <span>{{ statusMap[scope.row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="时间"
          width="200"
          prop="create_time"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签数量">
          <template slot-scope="scope">
            <el-input size="small" v-model="scope.row.count" placeholder="请输入打印标签数量" style="width: 50%"
                      oninput="value=value.replace(/[^\d]/g,'')"></el-input>
            <!--                            <span>{{ scope.row.reCount }}</span>-->
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native="printStockOrderDetailPDF(scope.row)"
            >标签打印
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>


      <div class="block">
        <pagination
          v-show="total>0"
          :total="total"
          :limit.sync="query.limit"
          :page.sync="query.page"
          @pagination="handleCurrentChange"
        ></pagination>
      </div>
    </el-form>
    <el-dialog
      title="标签打印文件列表"
      :visible.sync="labelPrintVisible"
      width="60%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      v-if="labelPrintVisible"
    >
      <el-button-group style="display: flex">
        <el-button
          type="primary"
          @click.native="refeshLabel()"
          style="margin: -50px 60px 10px auto; height: 35px"
        >刷新
        </el-button
        >
      </el-button-group>
      <el-table :data="lableFileLsit" style="width: 100%" border>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column
          label="文件名称"
          prop="fileName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="生成状态"
          prop="status"
          show-overflow-tooltip
        >
          <template slot-scope="scope">

            <el-tag :type="(scope.row.status) | statusFilterType">
              {{ printMap[scope.row.status] }}
            </el-tag>

          </template>

        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="printLabel(scope.row)">标签打印</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="labltotal>0"
        :total="labltotal"
        :limit.sync="refreshQuery.limit"
        :page.sync="refreshQuery.page"
        @pagination="handleLableChange"
      ></pagination>
    </el-dialog>
  </div>
</template>

<script>
import {stockQRCodeText, filterPrint, generateInnerQRCodeText} from "@/api/inout/innerOrderQRCode";
import draggable from "vuedraggable";
import {
  filterTemp, inspectionStockQRCodeTextPDFFromTemplateFile,
  stockQRCodeTextPDFFromTemplateFile, stockQRCodeTextPDFFromTemplateFileMax
} from "@/api/itextpdf/itextpdf";


export default {
  name: "innerCodeDetail",
  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    inQuery: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      BASE_URL: process.env.VUE_APP_BASE_API,
      code: "",
      query: {
        sOrderId: null,
        orderIdFk: "",
        page: 1,
        limit: 10,
        orderId: "",
      },
      labelPrintVisible: false,
      formData: {},
      codeArray: [],
      total: 0,
      lableFileLsit: [],
      loading: false,
      index: null,
      formLoading: false,
      formVisible: false,
      deleteLoading: false,
      orderNo: null,
      statusMap: {
        0: "未打印",
        1: "已打印",
      },
      refreshQuery: {
        page: 1,
        limit: 10,
        printCodeIdFk: null,
        stockOrderFk: null,
      },
      labltotal: null,
      printMap: {
        0: "正在生成",
        1: "已生成",
        2: "生成失败"
      },
      pdffileUrl: null,
    };
  },
  components: {
    draggable,
  },
  methods: {

    refeshLabel() {
      filterTemp(this.refreshQuery).then((response) => {
        if (response.code == 20000) {
          this.lableFileLsit = response.data.list;
          this.labelPrintVisible = true;
          this.labltotal = response.data.total || 0;
        }
      }).catch(() => {
        this.loading = false;
      });
    },

    printLabel(row) {
      window.open(this.pdffileUrl + row.fileName, '_blank');
    },

    // 刷新表单
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
      }
    },
    getInputFocus(event) {
      event.currentTarget.select();
    },
    tableSelection() {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleAllSelection();
    },
    handleCurrentChange(val) {
      this.query.page = val.page;
      this.getOrderQRCodeTextList();
    },


    handleLableChange(val) {
      this.refreshQuery.page = val.page;
      this.refeshLabel();
      this.getOrderQRCodeTextList();
    },

    getOrderQRCodeTextList() {
      this.loading = true;
      filterPrint(this.query) //查找该单号下的所有条码
        .then((response) => {
          console.log(response)
          this.codeArray = response.data.list || [];
          this.total = response.data.total || 0;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    printStockOrderDetailPDF(row) {
      let tQuery = {
        queryId: null,
        orderId: null,
        countList: [],
        moduleId: 6,
      };
      if (row == null) {
        tQuery.orderId = this.formData.id;
      } else {
        if (row.reCount <= 0) {
          return this.$message.error('数量错误');
        }
        tQuery.queryId = row.id;
      }

      this.loading = true;
      inspectionStockQRCodeTextPDFFromTemplateFile(tQuery).then((response) => {
        if (response.code === 20000) {
          if (row != null) {
            tQuery.id = row.id;
            tQuery.rowCount = row.reCount;
            let data = {
              queryId: row.id,
              rowCount: row.count
            }
            tQuery.countList.push(data);
          } else {
            for (let i = 0; i < this.codeArray.length; i++) {
              let data = {
                queryId: this.codeArray[i].id,
                rowCount: this.codeArray[i].count
              }
              tQuery.countList.push(data);
            }
          }
          let count = 0;
          for (let i = 0; i < tQuery.countList.length; i++) {

            count = count + tQuery.countList[i].rowCount;
            console.log(count);
          }
          console.log(count);
          if (count > 100) {
            stockQRCodeTextPDFFromTemplateFileMax(tQuery).then((response) => {
              if (response.code == 20000) {
                this.lableFileLsit = response.data.list;
                this.labltotal = response.data.total || 0;
                this.labelPrintVisible = true;
                this.refreshQuery = {
                  page: 1,
                  limit: 10,
                  printCodeIdFk: tQuery.queryId,
                  stockOrderFk: tQuery.orderId,
                }
                this.loading = false;
                this.$message.warning("打印文件正在生成中，请点击刷新按钮查看进度，请勿关闭按钮重复打印！");
              }
            }).catch(() => {
              this.loading = false;
            });

          } else
            stockQRCodeTextPDFFromTemplateFile(tQuery).then((response) => {
              //将pdf文件转换为url。
              const binaryData = [];
              binaryData.push(response);
              //获取blob链接。
              let url = window.URL.createObjectURL(
                new Blob(binaryData, {type: "application/pdf"})
              );
              this.loading = false;
              window.open(url);//打开新标签页，预览pdf。
            }).catch(() => {
              this.loading = false;
            });
        } else {
          this.loading = false;
          this.$message.error(response.message);
        }
      }).catch(() => {
        this.loading = false;
      });
    },

    generateQRCodeText() {
      this.$confirm("确定生成内部码?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loading = true;
        generateInnerQRCodeText({orderIdFk: this.formData.id})
          .then(response => {
            this.loading = false;
            if (response.code === 20000) {
              this.$message.success("生成成功！");
              this.getOrderQRCodeTextList();
              this.detailList = [];
            } else {
              this.$message.error(response.message);
            }
          })
          .catch(() => {
            this.loading = false;
          })
      }).catch(() => {

      });
    },


    intentBack() {
      this.$router.go(-1);
    },
    getPrintList(tQuery) {

    }
  },
  filters: {

    statusFilterType(status) {
      const statusMap = {
        0: "warning",
        1: "success",
        2: "danger"
      };
      return statusMap[status];
    }
    ,

  },
  mounted() {
  },
  created() {
    this.formData = {};
    this.codeArray = [];
    this.pdffileUrl = this.BASE_URL + "/spms/donwload/pdf?fileName=";
    if (this.$isNotBlank(this.inQuery.id)) {
      this.formData = this.inQuery.formData;
      this.query.orderId = this.inQuery.id;
      this.query.orderIdFk = this.formData.id;
      this.query.sOrderId = this.inQuery.id;
      this.getOrderQRCodeTextList();
    }
  },
};
</script>
<style>

.ao-text {
  width: 100%;
  font-size: 13px;
  font-family: "Microsoft YaHei";
  float: right;
  text-align: right;
  margin-top: 10px;
}

</style>



