<template>
  <div>
    <el-card>
      <div>
        <el-menu mode="horizontal" :default-active="activeIndex" router>
          <el-menu-item index="/QualityManagement/CheckTask/final"
            >终检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/purchaseIncoming"
            >采购入库检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/salesReturn"
            >销售退货检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/materialReturn"
            >原材料退库检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/OtherInbound"
            >其他入库检</el-menu-item
          >
          <el-menu-item index="/QualityManagement/CheckTask/processReceive"
            >序检收检</el-menu-item
          >
        </el-menu>
      </div>
    </el-card>
    <el-card>
      <div class="search-container" @keyup.enter="searchTable">
        <span class="show-text">单据码:</span>
        <el-input
          v-model="ordercode"
          placeholder="请输入单据码"
          clearable
          style="width: 150px; margin-right: 10px"
          @change="searchTable()"
        />
        <span class="show-text">生产订单:</span>
        <el-input
          v-model="orderNo"
          placeholder="请输入生产订单"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">物料名称:</span>
        <el-input
          v-model="partName"
          placeholder="请输入物料名称"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">物料编码:</span>
        <el-input
          v-model="partNo"
          placeholder="请输入物料编号"
          clearable
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">检测日期:</span>
        <el-date-picker
          v-model="inspectionDate"
          :clearable="false"
          end-placeholder="结束时间"
          format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始时间"
          style="width: 280px; vertical-align: top"
          type="datetimerange"
          value-format="yyyy-MM-dd"
        />

        <br />
        <br />

        <span class="show-text">检测结果</span>
        <el-select
          v-model="inspectionResult"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option label="合格" value="1" />
          <el-option label="不合格" value="0" />
        </el-select>
        <span class="show-text">状态</span>
        <el-select
          v-model="taskstatus"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option label="已完成" value="1" />
          <el-option label="未完成" value="0" />
        </el-select>
        <span class="show-text">检测人:</span>
        <el-select
          v-model="checker"
          placeholder="请选择检测人"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in checkerList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button
          :disabled="loading"
          icon="el-icon-search"
          plain
          type="primary"
          @click="searchTable()"
          >查询
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        :height="'67vh'"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="50"
          fixed
        />
        <el-table-column
          align="center"
          label="单据码"
          width="100"
          prop="单据码"
        />
        <el-table-column
          align="center"
          label="生产订单"
          width="80"
          prop="计划号"
        />
        <el-table-column
          align="center"
          label="物料名称"
          width="150"
          prop="物料名称"
        />
        <el-table-column
          align="center"
          label="物料编码"
          width="150"
          prop="物料编码"
        />
        <el-table-column
          align="center"
          label="到货时间"
          width="160"
          prop="采购到货时间"
        />
        <el-table-column
          align="center"
          label="位置"
          width="120"
          prop="存放位置"
        />
        <el-table-column align="center" label="加急数量" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="Urgent(scope.row)">{{
              Number(scope.row.加急总数)
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="到货数量"
          width="80"
          prop="入库数量"
        />
        <el-table-column
          align="center"
          label="已检验数量"
          width="80"
          prop="已检验数量"
        />
        <el-table-column
          align="center"
          label="剩余待检"
          width="80"
          prop="剩余待检数量"
        />
        <el-table-column
          align="center"
          label="合格数"
          width="80"
          prop="合格数"
        />
        <el-table-column
          align="center"
          label="不合格数"
          width="80"
          prop="不合格数"
        />
        <el-table-column
          align="center"
          label="检验人"
          width="100"
          prop="检测人"
        />
        <el-table-column
          align="center"
          label="检验时间"
          width="150"
          prop="检验时间"
        />
        <el-table-column
          align="center"
          label="备注"
          width="150"
          prop="备注"
        />
        <el-table-column label="操作" align="center" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button
              class="operation-btn"
              type="primary"
              size="mini"
              @click="receiveCheck(scope.row)"
              >入库检</el-button
            >
            <el-button
              class="operation-btn"
              type="primary"
              size="mini"
              @click="getitemdraw(scope.row)"
              >图纸</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="block" style="margin-top: 10px">
      <el-pagination
        :current-page="pageCurrent"
        :page-sizes="[10, 20, 30, 40, 100]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChanges"
        @current-change="handleCurrentChanges"
      />
    </div>

    <!-- 入库检对话框 -->
    <el-dialog
      title="入库检"
      :visible.sync="receiveCheckVisible"
      width="60%"
      style="text-align: center"
      @close="resetReceiveCheckForm"
    >
      <el-form
        ref="receiveCheckForm"
        :model="receiveCheckData"
        :rules="receiveCheckRules"
        label-position="right"
        label-width="140px"
        size="mini"
      >
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">物料名称</span>
              <span class="info-value">{{ receiveCheckData.零件名称 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">物料编码</span>
              <span class="info-value">{{ receiveCheckData.零件编码 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">生产订单</span>
              <span class="info-value">{{ receiveCheckData.计划号 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">到货总数</span>
              <span class="info-value">{{ receiveCheckData.到货总数 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">已检验数量</span>
              <span class="info-value">{{ receiveCheckData.已检验数量 }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">剩余待检数量</span>
              <span class="info-value">{{ receiveCheckData.剩余待检数量 }}</span>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">本次检验数量</span>
              <el-input-number
                v-model="receiveCheckData.本次检验数量"
                size="mini"
                :min="0"
                :max="receiveCheckData.剩余待检数量"
                style="width: 200px"
                @change="handleInspectionChange"
              />
            </div>
            <div class="info-item">
              <span class="info-label">合格数</span>
              <el-input-number
                v-model="receiveCheckData.合格数"
                size="mini"
                :min="0"
                :max="receiveCheckData.本次检验数量"
                style="width: 200px"
                disabled
              />
              <!-- <span class="info-value" style="margin-left: 10px">
                (自动计算：{{ receiveCheckData.本次检验数量 - receiveCheckData.不合格数 }})
              </span> -->
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            
            <div class="info-item">
              <span class="info-label">不合格数</span>
              <el-input-number
                v-model="receiveCheckData.不合格数"
                size="mini"
                :min="0"
                :max="receiveCheckData.本次检验数量"
                style="width: 200px"
                @change="handleUnqualifiedChange"
              />
            </div>
            <div class="info-item">
              <span class="info-label">检验人</span>
              <el-select
                v-model="receiveCheckData.检测人"
                placeholder="请选择检验人"
                clearable
                style="width: 200px"
                filterable
              >
                <el-option
                  v-for="item in checkerList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">检验时间</span>
              <el-date-picker
                v-model="receiveCheckData.检测时间"
                type="datetime"
                placeholder="选择检验时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 200px"
              />
            </div>
            <div class="info-item">
              <span class="info-label">放行数量</span>
              <el-input-number
                v-model="receiveCheckData.放行数量"
                :min="0"
                :max="receiveCheckData.合格数"
                style="width: 200px"
              />
            </div>
          </div>
        </div>
        <div>
          <div class="info-container">
            <div class="info-item">
              <span class="info-label">检测说明</span>
              <el-input
                v-model="receiveCheckData.检测说明"
                type="textarea"
                :rows="2"
                placeholder="请输入检测说明"
                style="width: 100%"
              />
            </div>
          </div>
        </div>
      </el-form>

      <div slot="footer">
        <el-button type="primary" @click="confirmReceiveCheck">确 定</el-button>
        <el-button @click="receiveCheckVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 扫码对话框 -->
    <el-dialog
      title="扫码"
      :visible.sync="scanVisible"
      width="60%"
      style="text-align: center"
    >
      <div class="scanner-container">
        <div class="scanner-content">
          <div class="video-container">
            <video id="video" autoplay playsinline></video>
            <div class="scan-area">
              <div class="scan-line"></div>
            </div>
          </div>
          <div class="status" :class="statusClass" v-if="statusMessage">
            {{ statusMessage }}
          </div>
          <div class="result-container" v-if="scanResult">
            <div class="result-title">扫描结果：</div>
            <div class="result-content">{{ scanResult }}</div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 图纸弹框 -->
    <el-dialog
      :visible.sync="seeVisible"
      title="图纸"
      center
      width="1200px"
      overflow="scroll"
    >
      <div id="el-dialog__body" style="min-height: 500px"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="seeVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 加急明细框 -->
    <el-dialog
      :visible.sync="UrgentVisible"
      title="加急明细"
      width="1200px"
      center
      :close-on-click-modal="false"
    >
      <el-form ref="Urgentarr" :model="Urgentarr" size="mini">
        <el-form-item v-for="item in Urgentarr" :key="item.订单编号">
          <div class="info-container">
            <div class="info-item">
              <span class="info-label" style="width: 80px">生产订单</span>
              <span class="info-value">
                <el-input
                  v-model="item.订单编号"
                  size="mini"
                  readonly
                  style="width: 300px"
                />
              </span>
            </div>
            <div class="info-item">
              <span class="info-label" style="width: 80px">加急数量</span>
              <span class="info-value">
                <el-input
                  v-model="item.加急数量"
                  size="mini"
                  style="width: 150px"
                  readonly
                />
              </span>
            </div>
            <div class="info-item">
              <span class="info-label" style="width: 80px">物料编号</span>
              <span class="info-value">
                <el-input
                  v-model="item.物料编号"
                  size="mini"
                  style="width: 150px"
                  readonly
                />
              </span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="UrgentVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入xlsx库
import * as XLSX from "xlsx";
import { seepdf, initPDFKeyboardShortcuts, setZoom } from "@/utils/pdf";
import { MESDownFile } from "@/utils/request";
export default {
  data() {
    return {
      contractNo: "",
      orderNo: "",
      ordercode: "",
      partNo: "",
      partName: "",
      completionTime: "",
      inspectionDate: "",
      type: "",
      typeList: [],
      checker: "",
      checkerLabel: "",
      checkerList: [],
      inspectionResult: "",
      taskstatus: "0",
      tableData: [],
      loading: false,
      selectedRow: null,
      receiveCheckVisible: false,
      receiveCheckData: {
        // 基本信息
        零件名称: "",
        零件编码: "",
        计划号: "",
        行号: 0,
        订单类型: "",
        到货总数: 0,
        已检验数量: 0,
        剩余待检数量: 0,

        // 检验数据
        本次检验数量: 0,
        合格数: 0,
        不合格数: 0,
        检测人: "",
        检测时间: "",
        检测说明: "",
        放行数量: 0,
      },
      receiveCheckRules: {
        本次检验数量: [
          { required: true, message: "请输入检验数量", trigger: "blur" },
          { type: "number", min: 1, message: "检验数量必须大于0", trigger: "blur" },
        ],
        不合格数: [
          { required: true, message: "请输入不合格数", trigger: "blur" },
          { type: "number", min: 0, message: "不合格数不能小于0", trigger: "blur" },
        ],
        检测人: [
          { required: true, message: "请选择检验人", trigger: "change" },
        ],
        检测时间: [
          { required: true, message: "请选择检验时间", trigger: "change" },
        ],
      },
      total: 0, // 分页总数
      pageCurrent: 1, // 分页当前页
      pageSize: 20, // 分页每页显示条数

      //扫码相关
      video: null,
      canvas: null,
      context: null,
      isScanning: false,
      scanResult: "",
      statusMessage: "",
      statusClass: "info",
      stream: null,
      scanInterval: null,
      lastScanTime: 0,
      scanDelay: 300, // 扫描间隔(毫秒)
      showPerformanceWarning: false,
      scanVisible: false,
      seeVisible: false,
      downPDF: MESDownFile,
      UrgentVisible: false,
      Urgentarr: {},
    };
  },
  created() {
    this.getTypeList();
    this.getCheckerList();
    this.searchTable();
  },
  computed: {
    activeIndex() {
      return this.$route.path;
    },
  },
  mounted() {
    this.statusMessage = '点击"开始扫描"按钮启用摄像头';

    // 检测设备性能并调整扫描频率
    this.adjustPerformance();
  },

  beforeDestroy() {
    this.stopScanning();
  },
  methods: {
    Urgent(row) {
      var param = [];
      param.push(["物料编号", row.物料编码]);
      this.UrgentVisible = true;
      var Data = this.CreateData("11", "加急订单_加急明细查询", param);
      this.ExecDatabase(Data).then((response) => {
        this.Urgentarr = response.data;
      });
    },
    getitemdraw(row) {
      var param = [];
      param[0] = ["物料编号", row.物料编码];
      var Data = this.CreateData("11", "工艺管理_图纸维护_查看图纸", param);
      this.ExecDatabase(Data).then((response) => {
        console.log(response);
        if (response.data.length > 0) {
          var pdfSrc = "" + this.downPDF + "" + response.data[0].uid + ".pdf";

          window.open(pdfSrc, "_blank");
        } else {
          this.$message.error("未上传图纸");
        }
      });
    },
    startscan() {
      this.scanVisible = true;
      setTimeout(() => {
        this.startScanning(); // ✅ this 正确指向组件实例
      }, 500);
    },
    async startScanning() {
      // ✅ 每次开始扫描前，重新获取 video 元素（确保它已存在）
      const videoEl = document.getElementById("video");
      if (!videoEl) {
        this.statusMessage = "视频元素未就绪，请稍后再试";
        this.statusClass = "error";
        return;
      }

      this.video = videoEl; // 更新引用
      this.canvas = this.canvas || document.createElement("canvas");
      this.context = this.context || this.canvas.getContext("2d");
      this.statusMessage = "正在请求摄像头权限...";
      this.statusClass = "info";

      try {
        // 请求摄像头访问权限
        this.stream = await navigator.mediaDevices.getUserMedia({
          video: {
            facingMode: "environment", // 优先使用后置摄像头
            width: { ideal: 1280 },
            height: { ideal: 720 },
          },
        });

        this.video.srcObject = this.stream;
        this.isScanning = true;
        this.statusMessage = "摄像头已启用，请将二维码对准扫描框";
        this.statusClass = "info";
        this.scanResult = "";

        // 使用setInterval替代requestAnimationFrame，控制扫描频率
        this.scanInterval = setInterval(() => {
          this.scanQRCode();
        }, this.scanDelay);
      } catch (error) {
        console.error("无法访问摄像头:", error);
        this.statusMessage = "无法访问摄像头: " + error.message;
        this.statusClass = "error";
      }
    },

    stopScanning() {
      this.isScanning = false;
      if (this.scanInterval) {
        clearInterval(this.scanInterval);
        this.scanInterval = null;
      }
      if (this.stream) {
        this.stream.getTracks().forEach((track) => track.stop());
        this.stream = null;
      }
      this.statusMessage = "扫描已停止";
      this.statusClass = "info";
      this.scanVisible = false;
      this.searchTable();
    },

    scanQRCode() {
      if (!this.isScanning || !this.video.readyState === this.video.HAVE_ENOUGH_DATA)
        return;

      // 设置canvas尺寸与视频一致
      this.canvas.width = this.video.videoWidth;
      this.canvas.height = this.video.videoHeight;

      // 绘制当前视频帧到canvas
      this.context.drawImage(this.video, 0, 0, this.canvas.width, this.canvas.height);

      // 获取图像数据
      const imageData = this.context.getImageData(
        0,
        0,
        this.canvas.width,
        this.canvas.height
      );

      // 使用jsQR库识别二维码
      try {
        const code = jsQR(imageData.data, imageData.width, imageData.height, {
          inversionAttempts: "dontInvert",
        });

        if (code) {
          this.partNo = this.extractBeforePosition(code.data, 51);
          console.log(this.partNo);
          this.statusMessage = "二维码识别成功！";
          this.statusClass = "success";

          // 识别成功后可以继续扫描或停止扫描
          this.stopScanning();
        }
      } catch (error) {
        console.warn("二维码识别出错:", error);
      }
    },
    extractBeforePosition(str, posFrom1 = 51) {
      // 转为从0开始的索引
      const idx = posFrom1 - 1;

      // 从 idx 开始向前找第一个 '*'
      let i = idx;
      while (i >= 0 && str[i] !== "*") {
        i--;
      }

      // 提取 i+1 到 idx+1 之间的子串（因为 substring 是 [start, end)）
      return str.substring(i + 1, idx + 1);
    },
    adjustPerformance() {
      // 根据设备性能调整扫描频率
      const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
        navigator.userAgent
      );
      if (isMobile) {
        this.scanDelay = 500; // 移动设备上降低扫描频率
        this.showPerformanceWarning = true;
      }
    },
    handleSizeChanges(val) {
      this.pageCurrent = 1;
      this.pageSize = val;
      this.searchTable();
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val;
      this.searchTable();
    },
    getTypeList() {
      this.typeList = [];
      var Data = this.CreateData("11", "查询字典");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          if (response.data[i].数据类别 === "检测类型") {
            this.typeList.push({
              label: response.data[i].词条名称,
              value: response.data[i].词条编号,
            });
          }
        }
      });
    },
    getCheckerList() {
      this.checkerList = [];
      var Data = this.CreateData("11", "人员管理_人员信息查询_质检部门_查询");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.checkerList.push({
            label: response.data[i].Personnel_Name,
            value: response.data[i].Personnel_Number,
          });
        }
      });
    },
    tableRowClassName({ row, rowIndex }) {
      console.log(row.加急状态);
      const isUrgent = row.加急状态 == "1";
      if (isUrgent) {
        return "priority-row";
      }
      return "";
    },
    searchTable() {
      // 开始加载状态，清空表格数据和选中行
      this.loading = true;
      this.tableData = [];

      // 构建基础查询参数
      var param = [];
      param.push(["订单号", this.orderNo]);
      param.push(["零件编号", this.partNo]);
      param.push(["零件名称", this.partName]);
      // 添加检测日期范围参数
      param.push([
        "检测日期_Start",
        this.inspectionDate ? this.inspectionDate[0] : "",
      ]);
      param.push([
        "检测日期_End",
        this.inspectionDate ? this.inspectionDate[1] : "",
      ]);
      param.push(["状态", this.taskstatus]);
      param.push(["检测结果", this.inspectionResult]);
      const selectedChecker = this.checkerList.find(
        (item) => item.value === this.checker
      );
      param.push(["单据码", this.ordercode]);
      param.push(["检测人", selectedChecker ? selectedChecker.label : ""]);

      // 调用封装方法生成请求数据 - 使用新的存储过程名称
      var Data = this.CreateData(
        "11",
        "质量管理_质量检验_入库质检任务_查询",
        param,
        this.pageSize,
        this.pageCurrent
      );

      // 执行数据库请求
      this.ExecDatabase(Data)
        .then((response) => {
          this.loading = false;
          if (response.data.rows && response.data.rows.length !== 0) {
            this.tableData = response.data.rows;
            this.tableData.sort((a, b) => {
              const aIsUrgent = a.加急状态 === 1;
              const bIsUrgent = b.加急状态 === 1;

              if (aIsUrgent && !bIsUrgent) return -1;
              if (!aIsUrgent && bIsUrgent) return 1;
              return 0;
            });
            this.total = response.data.total;
          } else {
            this.tableData = [];
            this.$message.info("未查询到相关数据");
          }
        })
        .catch((error) => {
          this.loading = false;
          console.error("查询失败:", error);
          this.$message.error("查询失败");
        });
    },

    receiveCheck(row) {
      // 直接使用行数据中已包含的已检验数量和剩余待检数量
      const totalQty = row.入库数量 || 0; // 到货总数
      const checkedQty = row.已检验数量 || 0; // 已检验数量（从查询结果获取）
      const remainingQty = row.剩余待检数量 || totalQty - checkedQty; // 剩余待检数量

      // 填充数据
      this.receiveCheckData = {
        // 基本信息
        零件名称: row.物料名称 || "",
        零件编码: row.物料编码 || "",
        计划号: row.计划号 || "",
        行号: row.行号 || 0,
        订单类型: row.订单类型 || "",
        到货总数: totalQty,
        已检验数量: checkedQty,
        剩余待检数量: remainingQty,

        // 检验数据
        本次检验数量: remainingQty > 0 ? remainingQty : 0,
        合格数: remainingQty > 0 ? remainingQty : 0,
        不合格数: 0,
        检测人: "",
        检测时间: this.formatDateTime(new Date()),
        检测说明: "",
        放行数量: 0,
      };

      // 如果已经没有可检数量，提示用户
      if (remainingQty <= 0) {
        this.$message.warning("该订单已全部检验完成，无需再次检验");
        return;
      }

      this.receiveCheckVisible = true;
    },

    // 检验数量变化时
    handleInspectionChange(value) {
      if (value !== undefined && value !== null) {
        // 不合格数不能超过本次检验数量
        if (this.receiveCheckData.不合格数 > value) {
          this.receiveCheckData.不合格数 = value;
        }
        // 自动更新合格数
        this.receiveCheckData.合格数 = value - this.receiveCheckData.不合格数;
        // // 放行数量不能超过合格数
        // if (this.receiveCheckData.放行数量 > this.receiveCheckData.合格数) {
        //   this.receiveCheckData.放行数量 = this.receiveCheckData.合格数;
        // }
      }
    },

    // 不合格数变化时
    handleUnqualifiedChange(value) {
      if (value !== undefined && value !== null) {
        // 不合格数不能超过本次检验数量
        if (value > this.receiveCheckData.本次检验数量) {
          this.receiveCheckData.不合格数 = this.receiveCheckData.本次检验数量;
          this.$message.warning("不合格数不能超过本次检验数量");
        }
        // 自动计算合格数
        this.receiveCheckData.合格数 = this.receiveCheckData.本次检验数量 - this.receiveCheckData.不合格数;
        // // 放行数量不能超过合格数
        // if (this.receiveCheckData.放行数量 > this.receiveCheckData.合格数) {
        //   this.receiveCheckData.放行数量 = this.receiveCheckData.合格数;
        // }
      }
    },

    confirmReceiveCheck() {
      // 验证表单
      this.$refs.receiveCheckForm.validate((valid) => {
        if (!valid) {
          return false;
        }

        // 验证合格数+不合格数是否等于检验数量
        console.log(this.receiveCheckData.合格数,this.receiveCheckData.不合格数,this.receiveCheckData.本次检验数量)
        if (
          Number(this.receiveCheckData.合格数) + Number(this.receiveCheckData.不合格数) !==
          Number(this.receiveCheckData.本次检验数量)
        ) {
          this.$message.warning("合格数加不合格数必须等于本次检验数量");
          return;
        }
        if(this.receiveCheckData.检测人==''){
          this.$message.warning("检验人不能为空");
          return;
        }
        // 调用存储过程保存数据
        this.receiveCheckVisible = false;
        this.saveReceiveCheck();
      });
    },

    saveReceiveCheck() {
      var param = [];
      param.push(["检测类型编号", 5]);
      param.push(["质检类型", "来料检验"]);
      param.push(["零件名称", this.receiveCheckData.零件名称]);
      param.push(["零件编码", this.receiveCheckData.零件编码]);
      param.push(["计划号", this.receiveCheckData.计划号]);
      param.push(["检测数量", this.receiveCheckData.本次检验数量]);
      param.push(["合格数", this.receiveCheckData.合格数]);
      param.push(["不合格数", this.receiveCheckData.不合格数]);
      param.push(["检测人", this.receiveCheckData.检测人]);
      param.push(["检测时间", this.receiveCheckData.检测时间]);
      param.push(["检测说明", this.receiveCheckData.检测说明]);
      param.push(["行号", this.receiveCheckData.行号]);
      param.push(["订单类型", this.receiveCheckData.订单类型]);
      param.push(["到货数", this.receiveCheckData.到货总数]);
      param.push(["放行数量", this.receiveCheckData.放行数量]);

      var Data = this.CreateData("12", "质量管理_来料检验_更新", param);

      this.ExecDatabase(Data)
        .then((response) => {
          if (response.data && response.data[0] && response.data[0].result === '1') {
            this.$message.success(response.data[0].message || "检验记录保存成功");
            this.receiveCheckVisible = false;
            // 刷新表格数据
            this.searchTable();
          } else {
            this.$message.error("检验记录保存失败");
          }
        })
        .catch((error) => {
          console.error("检验记录保存失败:", error);
          this.$message.error("检验记录保存失败");
        });
    },

    resetReceiveCheckForm() {
      this.$refs.receiveCheckForm && this.$refs.receiveCheckForm.resetFields();
    },

    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 导出Excel功能
    exportToExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning("没有数据可导出");
        return;
      }

      try {
        // 准备导出数据
        const exportData = this.tableData.map((item, index) => {
          return {
            序号: index + 1,
            合同号: item.内部合同号 || "",
            订单编号: item.计划号 || "",
            零件名称: item.零件名称 || "",
            零件编码: item.零件编码 || "",
            工序名称: item.工序名称 || "",
            计划生产数: item.计划生产数 || 0,
            检验数量: item.检验数量 || 0,
            检验合格数量: item.合格数 || 0,
            检验不合格数量: item.不合格数 || 0,
            检验操作人: item.检测人 || "",
            检验时间: item.检测时间 || "",
          };
        });

        // 创建工作簿
        const wb = XLSX.utils.book_new();

        // 创建工作表
        const ws = XLSX.utils.json_to_sheet(exportData);

        // 设置列宽
        const colWidth = [
          { wch: 8 }, // 序号
          { wch: 15 }, // 合同号
          { wch: 15 }, // 订单编号
          { wch: 20 }, // 零件名称
          { wch: 15 }, // 零件编码
          { wch: 12 }, // 工序名称
          { wch: 12 }, // 计划生产数
          { wch: 10 }, // 检验数量
          { wch: 15 }, // 检验合格数量
          { wch: 15 }, // 检验不合格数量
          { wch: 12 }, // 检验操作人
          { wch: 20 }, // 检验时间
        ];
        ws["!cols"] = colWidth;

        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, "序检收检记录");

        // 生成文件名（包含当前时间）
        const fileName = `序检收检记录_${this.formatDateForFileName(new Date())}.xlsx`;

        // 导出文件
        XLSX.writeFile(wb, fileName);

        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("导出失败");
      }
    },

    // 格式化日期用于文件名
    formatDateForFileName(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}${month}${day}_${hours}${minutes}${seconds}`;
    },
  },
};
</script>
<style scoped>
::v-deep .priority-row {
  background-color: #f56c6c !important;
  color: #000000 !important;
}
::v-deep .priority-row td {
  background-color: #f56c6c !important;
  color: #000000 !important;
  border: #f56c6c;
}
</style>
<style>
.search-container {
  margin-bottom: 20px;
}
.show-text {
  margin-right: 5px;
  line-height: 32px;
}
.operation-cell {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.operation-btn {
  flex: 1;
  margin: 0 5px;
  padding: 0;
  min-width: 0;
}
.active {
  color: skyblue;
  margin-left: 5px;
}

.info-container {
  border: 1px solid #ccc;
  display: flex;
}

.info-item {
  display: flex;
  flex: 1;
  border-right: 1px solid #ccc;
}

.info-item:last-child {
  border-right: none;
}

.info-label {
  width: 30%;
  padding: 8px;
  background-color: #f5f7fa;
  border-right: 1px solid #ccc;
}

.info-value {
  flex: 1;
  padding: 5px;
}

.info-label,
.info-value {
  display: flex;
  align-items: center;
}
</style>
<style>
.scanner-container {
  width: 100%;
  max-width: 800px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}
.scanner-header {
  background: linear-gradient(to right, #4a00e0, #8e2de2);
  color: white;
  padding: 20px;
  text-align: center;
}
.scanner-header h1 {
  font-size: 1.8rem;
  margin-bottom: 10px;
}
.scanner-header p {
  opacity: 0.9;
}
.scanner-content {
  padding: 30px;
}
.video-container {
  position: relative;
  width: 100%;
  margin-bottom: 20px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}
#video {
  width: 100%;
  height: auto;
  display: block;
  background-color: #000;
}
.scan-area {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 70%;
  height: 200px;
  border: 2px solid #4a00e0;
  border-radius: 10px;
  box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
}
.scan-line {
  width: 100%;
  height: 2px;
  background: #4a00e0;
  position: absolute;
  animation: scan 2s linear infinite;
}
@keyframes scan {
  0% {
    top: 0;
  }
  50% {
    top: calc(100% - 2px);
  }
  100% {
    top: 0;
  }
}
.controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 25px;
}
button {
  padding: 12px 25px;
  border: none;
  border-radius: 50px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}
.btn-primary {
  background: linear-gradient(to right, #4a00e0, #8e2de2);
  color: white;
}
.btn-primary:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(142, 45, 226, 0.4);
}
.btn-secondary {
  background: #f0f0f0;
  color: #333;
}
.btn-secondary:hover {
  background: #e0e0e0;
}
.result-container {
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
  margin-top: 20px;
  border-left: 4px solid #4a00e0;
}
.result-title {
  font-weight: 600;
  margin-bottom: 10px;
  color: #4a00e0;
}
.result-content {
  word-break: break-all;
  background: white;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}
.status {
  text-align: center;
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 15px;
}
.status.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}
.status.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}
.status.info {
  background-color: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}
.instructions {
  background-color: #e8f4fd;
  border-radius: 10px;
  padding: 15px;
  margin-top: 20px;
  font-size: 0.9rem;
}
.instructions h3 {
  color: #4a00e0;
  margin-bottom: 10px;
}
.instructions ul {
  padding-left: 20px;
}
.instructions li {
  margin-bottom: 8px;
}
.icon {
  width: 20px;
  height: 20px;
}
</style>