<template>
    <div>

        <el-form :model="formData" :rules="formRules" ref="dataForm" label-width="100px">
          <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-switch style="margin-left: 50px;" v-model="filterUDIType" active-text="过滤已有UDI码的产品"></el-switch>
            </el-button-group>
          </el-row>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="单据号" prop="billNo">
                        <el-input v-model="formData.billNo" style="width: 90%" 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.createTime" style="width: 90%" 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.customerName" style="width: 90%" auto-complete="off" :disabled="true"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="业务类型" prop="billTypeName">
                      <el-input v-model="formData.billTypeName" style="width: 90%" 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"
                    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="状态">
                    <template slot-scope="scope">
                        <span>{{ statusMap[scope.row.status] }}</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="时间" 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="操作"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 {filterPrint} from "@/api/inout/innerOrderQRCode";
import {getLocalJoinBusType} from "@/api/basic/busLocalType";
import draggable from "vuedraggable";
import {
  filterTemp,
  inspectionOrderDetailPDFFromTemplateFile,
  inspectionStockQRCodeTextPDFFromTemplateFile,
  orderDetailPDFFromTemplateFile, stockQRCodeTextPDFFromTemplateFile, stockQRCodeTextPDFFromTemplateFileMax
} from "@/api/itextpdf/itextpdf";
import {generateInCodeQRCodeText, generateInnerQRCodeText} from "@/api/inout/innerOrderQRCode";

export default {
    name: "idQuery",
    props: {
        closeDialog: {
            type: Function,
            required: true,
        },
        idQuery: {
            type: Object,
            required: true,
        },
    },
    data() {
        return {
            code: "",
            BASE_URL: process.env.VUE_APP_BASE_API,
            query: {
                sOrderId: null,
                orderIdFk: "",
                page: 1,
                limit: 10,
            },
            busTypes: [],
            formData: {},
            codeArray: [],
            total: 0,
            loading: false,
            index: null,
            formLoading: false,
            formVisible: false,
            deleteLoading: false,
            orderNo: null,
            labelPrintVisible: false,
            lableFileLsit: [],
            labltotal: null,
            refreshQuery: {
              page: 1,
              limit: 10,
              printCodeIdFk: null,
              stockOrderFk: null,
            },
            filterUDIType:false,
            statusMap: {
                0: "未打印",
                1: "已打印",
            },
          printMap: {
            0: "正在生成",
            1: "已生成",
            2: "生成失败"
          },
        };
    },
    components: {
        draggable,
    },
    methods: {
        // 刷新表单
        resetForm() {
            if (this.$refs["dataForm"]) {
                // 清空验证信息表单
                this.$refs["dataForm"].clearValidate();
                // 刷新表单
                this.$refs["dataForm"].resetFields();
                this.getList();
            }
        },
      printLabel(row) {
        window.open(this.pdffileUrl + row.fileName, '_blank');
      },
        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;
          });
        },
        handleCurrentChange(val) {
            this.query.page = val.page;
            this.getStockQRCodeTextList();
        },
        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;
                });
        },
      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;
          });
      },
      generateQRCodeText() {
        this.$confirm("确定生成内部码?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.loading = true;
          generateInCodeQRCodeText({orderIdFk:this.formData.billNo,chack:this.filterUDIType})
            .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(() => {

        });
      },
      printStockOrderDetailPDF(row) {
        let tQuery = {
          queryId: null,
          orderId: null,
          countList: [],
        };
        if (row == null) {
          tQuery.orderId = this.formData.orderIdFk;
        } 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;
        });
      },
        getBusType() {
            let query = {
                enabled: true,
            };
            getLocalJoinBusType(query)
                .then((response) => {
                    this.busTypes = response.data.list || [];
                    this.filterQuery.billAction = this.busTypes[0].action;
                    // this.getList();
                })
                .catch(() => {
                });
        },
    },
    filters: {
      statusFilterType(status) {
        const statusMap = {
          0: "warning",
          1: "success",
          2: "danger"
        };
        return statusMap[status];
      }},
    mounted() {
        document.body.ondrop = function (event) {
            event.preventDefault();
            event.stopPropagation();
        };
    },
    created() {
        // this.getBusType();
        this.pdffileUrl = this.BASE_URL + "/spms/donwload/pdf?fileName=";
        this.formData = {};
        this.codeArray = [];
        if (this.$isNotBlank(this.idQuery.id)) {
          debugger
            this.formData = this.idQuery.formData;
            this.query.orderIdFk=this.formData.billNo;
            this.query.sOrderId = this.formData.orderIdFk;
            this.getStockQRCodeTextList();
        }
    },
};
</script>
<style>

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

</style>



