<!--取制样交接 -->
<template>
  <div class="examination">
    <div class="common-head-search">
      <el-form
        :inline="true"
        @submit.native.prevent
        ref="searchForm"
        :model="searchForm"
        class="demo-form-inline sui-search-form"
      >
        <el-form-item label="物料名称">
          <el-input
            v-model="searchForm.matName"
            @keyup.enter.native="searchData()"
            size="small"
            placeholder="请输入查询内容"
            style="width: 150px"
          ></el-input>
        </el-form-item>
        <el-form-item label="样品类型">
          <el-select
            v-model="searchForm.sampleTypeCode"
            clearable
            filterable
            collapse-tags
            size="small"
            style="width: 150px"
            placeholder="请选择查询内容"
          >
            <el-option
              v-for="item in sampleTypeNameType"
              :key="item.baseName"
              :label="item.baseName"
              :value="item.baseCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交样日期">
          <el-date-picker
            v-model="searchForm.times"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            style="width: 300px"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            icon="el-icon-search"
            type="goon"
            size="mini"
            @click="searchData"
            >查询</el-button
          >
          <el-button
            icon="el-icon-refresh"
            type="info"
            plain
            size="mini"
            @click="resetData"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-row>
      <el-col :span="24">
        <div class="common-title-div" style="height: auto">
          <div class="common-title-name">
            <img
              style="width: 25px; height: 25px"
              src="../../../../assets/img/imgScreen/logo.png"
            />交样信息
          </div>
          <div>
            <el-input
              v-model="values"
              ref="autoInput"
              size="mini"
              style="display: inline-block; width: 150px"
              clearable
              @input="autoSubmit()"
              placeholder="扫码交接样"
              :disabled="inputLoading"
            ></el-input>
            <!-- <el-button icon="el-icon-check" type="goon" size="mini">交接样</el-button> -->
            <el-button
              icon="el-icon-printer"
              type="goon"
              :loading="printLoading"
              @click="printQRCode"
              size="mini"
              >打印标签</el-button
            >
            <!-- <el-button icon="el-icon-back" type="danger" size="mini">取消交接样</el-button> -->
          </div>
        </div>
        <div class="common-table-div">
          <el-table
            ref="table1"
            :height="theight1"
            v-loading="tableLoading1"
            :data="tableData1"
            :summary-method="getSummaries2"
            show-summary
            border
            @row-click="saveClickRow"
            @selection-change="searchFollow"
            :header-cell-style="tableHeaderCellStyle"
            highlight-current-row
            :icorePanelShown="100"
            :icore-filter-flag="icoreFilterFlag"
            :exchangeFilterMap="{ lock_flag: { '0': '未锁定', '1': '已锁定' } }"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="NO"
              align="center"
            ></el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              sortable
              min-width="100"
              align="center"
              prop="matName"
              label="物料名称"
            ></el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              sortable
              min-width="120"
              align="center"
              prop="showCode"
              label="样品号"
            ></el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              sortable
              min-width="80"
              align="center"
              prop="carNo"
              label="车号"
            ></el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              sortable
              min-width="80"
              align="center"
              prop="sampleTypeName"
              label="样品类型"
            ></el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              sortable
              min-width="80"
              align="center"
              prop="sndMan"
              label="交样人"
            ></el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              sortable
              min-width="140"
              align="center"
              prop="sndTime"
              label="交样时间"
            ></el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              sortable
              min-width="80"
              align="center"
              prop="acptMan"
              label="接样人"
            ></el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              sortable
              min-width="140"
              align="center"
              prop="acptTime"
              label="接样时间"
            ></el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              sortable
              min-width="80"
              align="center"
              prop="memo"
              label="备注"
            ></el-table-column>
          </el-table>
        </div>
        <div class="common-foot-style">
          <el-pagination
            @size-change="handleSizeChangeMain"
            @current-change="handleCurrentChangeMain"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 30, 40, 100, 200]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total_main"
            background
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
    <div
      id="printContainer2"
      v-show="false"
      style="margin-left: 20px; margin-top: 3px"
    >
      <div id="printContent">
        <div
          v-for="(item, index) in printData"
          :key="index"
          style="width: 374px"
        >
          <div style="text-align: center; margin-top: 6px">
            <strong style="font-size: 18px">广西北港新材料有限公司</strong><br />
          </div>
          <div style="margin-top: 6px">
            <div style="font-size: 16px; line-height: 18px; margin-left: 35px">
              物料名称：{{ saveDepRow.matName
              }}<span v-if="item">({{ item }})</span>
            </div>
            <div style="font-size: 16px; line-height: 18px; margin-left: 35px">
              加密编号：{{ saveDepRow.newMarkNo }}
            </div>
            <div
              style="font-size: 16px; line-height: 18px; margin-left: 35px"
              v-if="saveDepRow.sampleTypeCode == '480101'"
            >
              <div style="display: inline-block">
                是否配批：{{ saveDepRow.isBatchName }}
              </div>
              <div style="margin-left: 30px; display: inline-block">
                是否商检：{{ saveDepRow.isCiqName }}
              </div>
            </div>
            <div
              v-if="saveDepRow.isCiqName === '是'"
              style="margin-left: 35px;"
            >
              到货批次：{{ saveDepRow.lotsNo }}
            </div>
            <div style="font-size: 16px; line-height: 18px; margin-left: 35px">
              交样时间：{{ saveDepRow.acptTimeName }}
            </div>
            <div style="font-size: 16px; line-height: 18px; margin-left: 35px">
              备注：{{ saveDepRow.planMemo ? saveDepRow.planMemo : "" }}
            </div>
          </div>
          <div style="text-align: center; margin-bottom: 0">
            <img width="88%" :id="`barcode${index}`" />
          </div>
          <div style="page-break-after: always"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getCookie, formatDate } from "@/utils/util.js";
import { cookieUserId, cookieUserName } from "@/config/config.js";
import JsBarcode from "jsbarcode";
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
export default {
  data () {
    return {
      searchForm: {
        times: "",
        matName: "",
        sampleTypeCode: "",
        eqpNo: "",
      },
      saveDepRow: {},
      clickRow: {},
      printLoading: false,
      values: "",
      total_main: 0,
      pageIndex: 1,
      pageSize: 50,
      inputLoading: false,
      saveMainData: [],
      sampleLoading: false,
      sampleTypeNameType: [],
      theight1: 0,
      tableLoading1: false,
      tableData1: [],
      icoreFilterFlag: true,
      activeMenu: "",
      timeId: null,
      printData: [""]
    };
  },
  created () {
    this.theight2 = window.innerHeight - 230;
    this.theight3 = window.innerHeight - 230;
    this.theight1 = window.innerHeight - 190;
    this.searchForm.times = [this.getYNM(new Date()), this.getYNM(new Date())];
    this.activeMenu = window.top.localStorage.getItem("activeMenu");
  },
  mounted () {
    this.axios
      .post(
        "pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",
        { validFlag: 1, baseCode: 4801 },
        { individualType: "json" }
      )
      .then((res) => {
        this.sampleTypeNameType = res.data;
      });
    this.searchData();
  },
  methods: {
    getYNM (date) {
      let year = date.getFullYear().toString();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      return `${year}-${month}-${day}`;
    },
    getSummaries2 (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
        }
        if (index === 1) {
          sums[index] = data.length;
        } else if (column.property === "quantity") {
          let val = 0;
          for (let i in data) {
            val = this.floatComputed(
              data[i].quantity ? data[i].quantity : 0,
              val,
              "+"
            );
          }
          sums[index] = val;
        } else if (column.property === "factweight") {
          let val = 0;
          for (let i in data) {
            val = this.floatComputed(
              data[i].factweight ? data[i].factweight : 0,
              val,
              "+"
            );
          }
          sums[index] = val;
        }
      });
      return sums;
    },
    saveClickRow (row) {
      this.clickRow = row;
    },
    // 打印条形码
    printQRCode () {
      if (JSON.stringify(this.clickRow) === "{}") {
        this.$message.warning("请点击您要打印的数据");
        return;
      }
      this.runPrint(this.clickRow);
    },
    runPrint (obj) {
      if (JSON.stringify(obj) === "{}") {
        this.$message.warning("请点击您要打印的数据");
        return;
      }
      this.saveDepRow = Object.assign({}, obj);
      let newStr = this.saveDepRow.markNo.replace('-U', '(筛上)').replace('-D', '(筛下)').replace('-B', '(边)')
        .replace('-Z', '(中)').replace('-T', '(2mm)').replace('-H', '(合金)').replace('-R', '(熔渣)');
      this.saveDepRow.newMarkNo = newStr
      this.printLoading = true;
      this.saveDepRow.isBatchName = this.saveDepRow.isBatch == 0 ? "否" : this.saveDepRow.isBatch == 1 ? "是" : ''
      this.saveDepRow.isCiqName = this.saveDepRow.isCiq == 0 ? "否" : this.saveDepRow.isCiq == 1 ? "是" : ''
      this.saveDepRow.acptTimeName = this.saveDepRow.acptTime
        ? formatDate(this.saveDepRow.acptTime, "yyyy-MM-dd")
        : "";
      this.printLoading = true;
      this.printData = [''];
      this.axios.get("pass/testManagement/v1/limssampleacpts/getFyDefaultValueByTkId?tkId=" + obj.tkId).then((res) => {
        if (res.code == 0 || res.code == 200) {
          if (res.data) {
            this.printData = res.data.replace(/，/g, ",").replace(/\s+/g, "").split(',');
          }
        }
        setTimeout(() => {
          this.printData.forEach((item, index) => {
            JsBarcode(`#barcode${index}`, this.saveDepRow.markNo, {
              format: 'CODE128',
              lineColor: '#000',
              background: '#fff',
              width: 1,
              height: 15,
              displayValue: false
            })
          })
          setTimeout(() => {
            this.printLoading = false
            // this.printPage('printContent');
            this.printCode()
          }, 1000)
        }, 100);
      }).catch(err => {
        this.printLoading = false;
        this.$message.error(err.message)
      })
    },
    autoSubmit (val) {
      if (!this.values) {
        this.$message.warning("请先用扫码枪扫描标签");
        return;
      }
      if (!this.timeId) {
        this.timeId = setTimeout(() => {
          this.inputLoading = true
          this.axios.post('pass/testManagement/v1/limssampleacpts/sampleAcptToScan', { encryNo: this.values }, { individualType: 'json' }).then(res => {
            if (res.code == 0 || res.code == 200) {
              this.$message.success(res.message);
              this.runPrint(res.data)
              this.searchData()
            } else {
              this.$message.error(res.message)
            }
            this.$nextTick(() => {
              this.$refs.autoInput.focus()
            })
            this.values = ''
            this.inputLoading = false
          }).catch(e => {
            this.$nextTick(() => {
              this.$refs.autoInput.focus()
            })
            this.values = ''
            this.inputLoading = false
            this.$message.error(e.message)
          })
          this.timeId = null;
        }, 1000);
      }
    },
    resetData () {
      this.searchForm.matName = "";
      this.searchForm.sampleTypeCode = "";
      this.searchForm.eqpNo = "";
      this.searchForm.times = [
        this.getYNM(new Date()),
        this.getYNM(new Date()),
      ];
      this.searchData();
    },
    //勾选多条数据
    searchFollow (val) {
      this.saveMainData = val;
    },
    //接样
    recSample () {
      if (this.saveMainData.length < 1) {
        this.$message.warning("请先勾选您要接样的数据");
        return;
      }
      this.sampleLoading = true;
      this.axios
        .post(
          "pass/testManagement/v1/limssampletests/pickUpSample",
          this.saveMainData,
          { individualType: "json" }
        )
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            this.$message.success(res.message);
            this.searchData();
          } else {
            this.$message.error(res.message);
          }
          this.sampleLoading = false;
        })
        .catch((err) => {
          this.sampleLoading = false;
          this.$message.error(err.message);
        });
    },
    //查询操作
    searchData () {
      this.pageIndex = 1;
      this.pageSize = 100;
      this.DataMain();
    },
    printCode () {
      var iframe = document.createElement('iframe');
      document.body.appendChild(iframe);
      var doc = iframe.contentWindow.document;
      doc.write('<div>' + $('#printContent').html() + '</div>');
      doc.close();
      iframe.contentWindow.focus();
      iframe.contentWindow.document.execCommand('print');
      document.body.removeChild(iframe);
      var t = setTimeout(() => {
        this.$refs.autoInput.focus();
        clearTimeout(t)
      }, 500)
    },
    //查询样品信息表格
    DataMain () {
      this.clickRow = {};
      let startTime = "";
      let endTime = "";
      if (!this.searchForm.times) {
        startTime = "";
        endTime = "";
      } else {
        startTime = this.searchForm.times[0] + " 00:00:00";
        endTime = this.searchForm.times[1] + " 23:59:59";
      }
      let obj = {
        object: {
          sampleTypeCode: this.searchForm.sampleTypeCode,
          // createNo: userId,
          matName: this.searchForm.matName,
          createStartTime: startTime,
          createEndTime: endTime,
        },
        pageSize: this.pageSize,
        pageIndex: this.pageIndex,
      };
      this.tableLoading1 = true;
      this.axios.post("pass/testManagement/v1/limssampleacpts/queryLimsSampleAcptPage", obj, { individualType: "json" }).then((res) => {
        if (res.code == 0 || res.code == 200) {
          this.tableData1 = res.data.list;
          this.tableData1.forEach((item) => {
            item.showCode =
              item.sampleTypeCode == "480101" ? item.markNo : item.sampleNo;
          });
          this.total_main = res.data.total;
        } else {
          this.$message.error(res.message);
        }
        this.tableLoading1 = false;
      }).catch((err) => {
        this.tableLoading1 = false;
        this.$message.error(err.message);
      });
    },
    handleSizeChangeMain (pageSize) {
      this.pageIndex = 1;
      this.pageSize = pageSize;
      this.DataMain();
    },
    handleCurrentChangeMain (pageIndex) {
      this.pageIndex = pageIndex;
      this.DataMain();
    },
    tableHeaderCellStyle () {
      return 'color: rgb(255,255,255);border-bottom: 1px solid #DCDFE7;'
    },
  },
};
</script>
<style  scoped>
</style>
