<template>
  <div>

    <el-form :model="formData" :rules="formRules" ref="dataForm">
      <el-button-group style="display: flex">
        <el-button
          type="primary"
          @click.native="printStockOrderDetailPDF()"
          style="margin: -50px 60px 10px auto; height: 35px"
          :loading="loading"
        >打印全部
        </el-button
        >
      </el-button-group>

      <el-row>
        <el-col :span="11">
          <el-form-item label="单据号" prop="billNo">
            <el-input v-model="formData.billNo" auto-complete="off" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="单据日期" prop="billdate">
            <el-input v-model="formData.billdate" auto-complete="off" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="供应商名称" prop="corpName">
            <el-input v-model="formData.corpName" auto-complete="off" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="业务类型" prop="billType">
            <el-select v-model="formData.billType" placeholder="请选择业务类型" clearable="true" disabled="true">
              <el-option
                v-for="item in busTypes"
                :key="item.localName"
                :label="item.localName"
                :value="item.localAction">
                <span style="float: left">{{ item.localName }}</span>
                <!--<span style="float: right; color: #8492a6; font-size: 13px">{{ item.action }}</span>-->
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>


      <el-table v-loading="loading" :data="codeArray" style="width: 100%;" max-height="350" border height="350" highlight-current-row 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.printStatus] }}</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="操作" fixed="right" 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%">
        <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">
            <span>{{ printMap[scope.row.status] }}</span>
          </template>

        </el-table-column>

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

      <el-pagination
        :page-size="refreshQuery.limit"
        @current-change="handleLableChange"
        layout="prev, pager, next"
        :total="labltotal"
        :current-page="refreshQuery.page"
      >
      </el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import {
  stockOrderDetail,
  submitStockOrder,
  submitStockOrderError,
  uploadStockOrderDetailCount,
} from "@/api/inout/stockOrder";
import {stockQRCodeText, filterPrint} from "@/api/inout/stockQRCode";
import draggable from "vuedraggable";
import {
  inspectionOrderDetailPDFFromTemplateFile, filterTemp,
  inspectionStockQRCodeTextPDFFromTemplateFile,
  orderDetailPDFFromTemplateFile, stockQRCodeTextPDFFromTemplateFile, stockQRCodeTextPDFFromTemplateFileMax
} from "@/api/itextpdf/itextpdf";
import {getLocalJoinBusType} from "@/api/basic/busLocalType";


export default {
  name: "idQuery",
  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    idQuery: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      code: "",
      query: {
        sOrderId: null,
        orderIdFk: "",
        page: 1,
        limit: 10,
      },
      labelPrintVisible: false,
      busTypes: [],
      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: "已生成",
      },
      pdffileUrl: null,
    };
  },
  components: {
    draggable,
  },
  methods: {
    submit(formName) {
      if (this.total < 1) {
        this.$message.error('未选择条码');
        return;
      }
      this.$confirm("是否提交？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let tQuery = {
          id: this.idQuery.id
        }
        this.loading = true;
        submitStockOrder(tQuery)
          .then((response) => {
            this.loading = false;
            if (response.code === 20000) {
              this.$message.success("提交成功");
              this.closeDialog(true);
            } else {
              this.$message.error(response.message);
            }
          });
      }).catch(() => {
        this.loading = false;
      });
    },

    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();
        this.getList();
      }
    },
    getInputFocus(event) {
      event.currentTarget.select();
    },
    tableSelection() {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleAllSelection();
    },
    handleSizeChange(val) {
      this.query.limit = val;
      // this.getStockOrderDetailList();
      this.getStockQRCodeTextList();
    },
    handleCurrentChange(val) {
      this.query.page = val.page;
      // this.getStockOrderDetailList();
      this.getStockQRCodeTextList();
    },


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


    getStockOrderDetailList() {
      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;
        });
    },
    getBusType() {
      let query = {
        enabled: true,
      };
      getLocalJoinBusType(query)
        .then((response) => {
          this.busTypes = response.data.list || [];
        })
        .catch(() => {
        });
    },
    getStockQRCodeTextList() {
      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: [],
      };
      if (row == null) {
        tQuery.orderId = this.query.sOrderId;
      } 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;
      });
    },
    intentBack() {
      this.$router.go(-1);
    },
    getPrintList(tQuery) {

    }
  },
  filters: {},
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
  },
  created() {
    this.getBusType();
    this.formData = {};
    this.codeArray = [];
    this.pdffileUrl = BASE_URL + "/spms/donwload/pdf?fileName=";
    if (this.$isNotBlank(this.idQuery.id)) {

      this.formData = this.idQuery.formData;
      // this.query.orderIdFk = this.idQuery.id;
      // this.getStockOrderDetailList();
      this.query.orderId = this.idQuery.id;
      this.query.sOrderId = this.idQuery.id;
      console.log(this.query.sOrderId);
      this.getStockQRCodeTextList();
    }
  },
};
</script>
<style scoped>

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

</style>



