<template>
  <div class="app-container">
    <!-- 工具栏 -->
    <el-row :gutter="10">
      <el-col :span="1.5" class="mb20">
        <el-button
          type="primary"
          :loading="submitLoading"
          size="mini"
          icon="el-icon-finished"
          :disabled="
            apiStatus === 1 ||
            apiStatus === 2 ||
            choiceStatus ||
            disableApproval ||
            (apiStatus === 0 && !tailSelected)
          "
          @click="handleTesting"
          >{{ apiStatus === -1 ? "送审" : "批核" }}</el-button
        >
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-check"
          :loading="saveLoading"
          :disabled="apiStatus !== -1"
          @click="handleSave()"
          >保存</el-button
        >
        <el-button
          v-hasPermi="['wms:material-item:update']"
          size="mini"
          type="primary"
          icon="el-icon-refresh"
          :disabled="apiStatus !== 0 || resetInspect"
          :loading="reLoading"
          @click="handleResetInspection"
          >重新检验</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-printer"
          :loading="printLoading"
          :disabled="apiStatus === -1 || apiStatus === 0"
          size="mini"
          @click="handlePrint"
          >检验单打印</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-thumb"
          :loading="submitLoading"
          :disabled="apiStatus !== -1 || ifModify > 0"
          size="mini"
          @click="handleApply"
          >申请修改检验标准</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-magic-stick"
          :loading="printLoading"
          :disabled="apiStatus !== -1"
          size="mini"
          @click="handleAllInspect"
          >一键检验</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:ipqc-actual-file:query']"
          type="primary"
          size="mini"
          icon="el-icon-upload2"
          :loading="printLoading"
          @click="handleUploadFile"
          >{{ apiStatus == -1 ? "上传附件" : "查看附件" }}</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-view"
          :loading="supplierLoading"
          @click="handleViewSupplierFile"
          >供应商附件</el-button
        >
      </el-col>
    </el-row>
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="formParams"
      size="small"
      label-width="98px"
      disabled
    >
      <!-- <el-descriptions
        class="margin-top mb10"
        :column="3"
        style="width: 100%;"
        border
      >
        <el-descriptions-item label="IQC编号">{{ formParams.materialLots }}</el-descriptions-item>
        <el-descriptions-item label="物料编码">{{ formParams.materialNo }}</el-descriptions-item>
        <el-descriptions-item label="物料名称">{{ formParams.materialName }}</el-descriptions-item>
        <el-descriptions-item label="来料数量">{{ formParams.receiptQty }} ({{ $route.query.unitCode }})</el-descriptions-item>
        <el-descriptions-item label="供应商">{{ formParams.supplierName }}</el-descriptions-item>
        <el-descriptions-item label="规格">{{ formParams.size }}</el-descriptions-item>
        <el-descriptions-item label="检验标准版本">{{ formParams.version || '草稿' }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ formParams.auditTimeStr }}</el-descriptions-item>
        <el-descriptions-item label="保质期">{{ formParams.validTillStr }}</el-descriptions-item>
        <el-descriptions-item label="送货批次">{{ formParams.deliverBatch }}</el-descriptions-item>
        <el-descriptions-item v-if="currentRows.length > 0 && (currentRows[0].checkCategory === '5' || currentRows[0].tool === '3')">
          <VueQr
            :text="formParams.materialLots+','+currentRows[0].id"
            :binarize="true"
            :size="65"
            :margin="5"
          />
        </el-descriptions-item>
      </el-descriptions> -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="IQC编号" prop="materialLots">
            <el-input
              v-model="formParams.materialLots"
              placeholder="请输入IQC编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料编码" prop="materialNo">
            <el-input
              v-model="formParams.materialNo"
              placeholder="请输入物料编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料名称" prop="materialName">
            <el-input
              v-model="formParams.materialName"
              placeholder="请输入物料名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="来料数量" prop="receiptQty">
            <el-input
              v-model="formParams.receiptQty"
              placeholder="请输入来料数量"
              clearable
              @keyup.enter.native="handleQuery"
            >
              <template slot="append">{{ $route.query.unitCode }}</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商" prop="supplierName">
            <el-input
              v-model="formParams.supplierName"
              placeholder="请输入供应商"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规格" prop="size">
            <el-input
              v-model="formParams.size"
              placeholder="请输入规格"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验标准版本" prop="version">
            <el-input
              v-model="formParams.version"
              placeholder="草稿"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核时间" prop="auditTimeStr">
            <el-input
              v-model="formParams.auditTimeStr"
              placeholder="请输入审核时间"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="保质期" prop="validTillStr">
            <el-input
              v-model="formParams.validTillStr"
              placeholder="请输入保质期"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="送货批次" prop="deliverBatch">
            <el-input
              v-model="formParams.deliverBatch"
              placeholder="请输入送货批次"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产日期" prop="produceDate">
            <el-input
              v-model="formParams.produceDate"
              placeholder="请输入送货批次"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="图号" prop="drawingNo">
            <el-input
              v-model="formParams.drawingNo"
              placeholder="请输入图号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户料号" prop="customerMaterialNo ">
            <el-input
              v-model="formParams.customerMaterialNo"
              placeholder="请输入客户料号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            v-if="
              currentRows.length > 0 &&
              (currentRows[0].checkCategory === '5' ||
                currentRows[0].tool === '3')
            "
          >
            <VueQr
              :text="formParams.materialLots + ',' + currentRows[0].id"
              :binarize="true"
              :size="65"
              :margin="5"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="检验详情" name="inspectDetails" lazy>
        <!-- 明细体 -->
        <el-table
          ref="table"
          v-loading="loading"
          :data="list"
          border
          size="mini"
          max-height="400"
          :span-method="arraySpanMethod"
          :cell-class-name="delLine"
          @selection-change="tableSelected"
        >
          <el-table-column type="selection" width="40" fixed="left" />
          <el-table-column
            label="检查内容"
            align="center"
            prop="checkCategoryStr"
          />
          <el-table-column
            label="检验项名称"
            align="center"
            prop="inspectionName"
            width="130"
            show-overflow-tooltip
          />
          <el-table-column
            label="检查规格/标准"
            align="center"
            width="120"
            prop="standard"
            show-overflow-tooltip
          />
          <!-- <el-table-column label="检查工具" align="center" prop="tool">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.tool === '4'"
                type="text"
                @click="handleToPeelingForce(scope.row)"
              >
                {{ scope.row.toolName }}
              </el-button>
              <span v-else>{{ scope.row.toolName }}</span>
            </template>
          </el-table-column> -->
          <el-table-column
            label="检查工具"
            align="center"
            prop="toolName"
            show-overflow-tooltip
          />

          <el-table-column
            label="检查数量"
            align="center"
            prop="checkQuantity"
            show-overflow-tooltip
          />
          <el-table-column
            label="检查记录(数据)"
            align="center"
            prop="checkQuantity"
          >
            <el-table-column label="NO.1" align="center" prop="actual1">
              <template slot-scope="scope">
                <span v-if="scope.row.inspectionModel === 1">{{
                  scope.row.measuredResults
                }}</span>
                <el-input
                  v-else
                  v-model="scope.row.actual1"
                  oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                  :disabled="apiStatus !== -1"
                  @blur="handleQualified(scope.row)"
                  @focus="handleQuadraticelement(scope.row, scope.column)"
                />
              </template>
            </el-table-column>
            <el-table-column label="NO.2" align="center" prop="actual2">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.actual2"
                  oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                  :disabled="apiStatus !== -1"
                  @blur="handleQualified(scope.row)"
                  @focus="handleQuadraticelement(scope.row, scope.column)"
                />
              </template>
            </el-table-column>
            <el-table-column label="NO.3" align="center" prop="actual3">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.actual3"
                  oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                  :disabled="apiStatus !== -1"
                  @blur="handleQualified(scope.row)"
                  @focus="handleQuadraticelement(scope.row, scope.column)"
                />
              </template>
            </el-table-column>
            <el-table-column label="NO.4" align="center" prop="actual4">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.actual4"
                  oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                  :disabled="apiStatus !== -1"
                  @blur="handleQualified(scope.row)"
                  @focus="handleQuadraticelement(scope.row, scope.column)"
                />
              </template>
            </el-table-column>
            <el-table-column label="NO.5" align="center" prop="actual5">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.actual5"
                  oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                  :disabled="apiStatus !== -1"
                  @blur="handleQualified(scope.row)"
                  @focus="handleQuadraticelement(scope.row, scope.column)"
                />
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column
            label="判定"
            align="center"
            prop="singleResultNum"
            width="140"
          >
            <template slot-scope="scope">
              <el-radio-group
                v-model="scope.row.singleResultNum"
                :disabled="
                  apiStatus !== -1 || scope.row.inspectionNo === 'IQCEXPERIOD'
                "
              >
                <el-radio :label="1">OK</el-radio>
                <el-radio :label="0">NG</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column
            label="不良项(不良代码)"
            align="center"
            prop="badName"
            width="130"
          >
            <template slot-scope="scope">
              <BadcodeSelect
                :key="`badCode+${scope.$index}`"
                v-model="scope.row.badName"
                clearable
                :disabled="
                  apiStatus !== -1 || scope.row.inspectionNo === 'IQCEXPERIOD'
                "
                @change="badCodeChange(scope.row, scope.row.badName)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="实测结果"
            align="center"
            prop="measuredResults"
            width="130"
          >
            <template slot-scope="scope">
              <el-input
                v-show="scope.row.inspectionModel === 1"
                v-model="scope.row.measuredResults"
                :disabled="
                  apiStatus !== -1 || scope.row.inspectionNo === 'IQCEXPERIOD'
                "
                placeholder="请输入实测结果"
              />
            </template>
          </el-table-column>
          <el-table-column label="附件" align="center" width="70">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-paperclip"
                size="mini"
                @click="openRowFile(scope.row)"
                >查看</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 表尾 -->
        <el-form
          v-show="apiStatus !== -1"
          ref="queryForm"
          :model="adjustForm"
          size="small"
          label-width="88px"
          class="mt20"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="合格" prop="noPassType">
                <el-radio
                  v-model="adjustForm.noPassType"
                  :disabled="apiStatus === 1 || apiStatus === 2"
                  label="0"
                  @change="noPassChange"
                  >合格</el-radio
                >
              </el-form-item>
            </el-col>
            <el-col v-if="adjustForm.noPassType !== '0'" :span="8">
              <el-form-item
                v-if="adjustForm.noPassType !== '0'"
                label="原因说明"
                prop="manage"
              >
                <el-input
                  v-model="adjustForm.manage"
                  placeholder="请输入原因说明"
                  @change="noPassChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="adjustForm.noPassType !== '0' ? 8 : 12">
              <el-form-item label="检验员" prop="inspector">
                <el-input
                  v-model="adjustForm.inspector"
                  placeholder="请输入检验员"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="不合格" prop="noPassType">
                <el-radio-group
                  v-model="adjustForm.noPassType"
                  @change="noPassChange"
                >
                  <el-radio
                    :disabled="apiStatus === 1 || apiStatus === 2"
                    label="1"
                    >特采</el-radio
                  >
                  <el-radio
                    :disabled="apiStatus === 1 || apiStatus === 2"
                    label="2"
                    >挑选</el-radio
                  >
                  <el-radio
                    :disabled="apiStatus === 1 || apiStatus === 2"
                    label="3"
                    >退货</el-radio
                  >
                  <el-radio
                    :disabled="apiStatus === 1 || apiStatus === 2"
                    label="4"
                    >报废</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审核员" prop="auditor">
                <el-input
                  v-model="adjustForm.auditor"
                  placeholder="请输入审核员"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 挑选入库 -->
        <el-table
          v-show="adjustForm.noPassType === '2'"
          v-loading="loading"
          :data="choiceList"
          border
          size="mini"
        >
          <el-table-column
            label="标签码"
            align="center"
            prop="qrCode"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column label="登记数量" align="center" prop="receiptQty" />
          <el-table-column label="合格数量" align="center" prop="qty" />
          <el-table-column label="不良数量" align="center" prop="badQty">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.badQty"
                oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,8})?).*$/g, '$1')"
                :disabled="apiStatus === 1 || apiStatus === 2"
                @change="badQtyInputChange"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="审批任务" name="approvalTask" lazy>
        <ApprovalTask
          v-if="
            formParams.bpmInstanceId !== null &&
            formParams.bpmInstanceId !== undefined
          "
          :id="formParams.bpmInstanceId"
          ref="approvalTask"
          :active-name="activeName"
          :query-paramspro="formParams"
        />
        <div v-else class="isNotApproval">暂未开启工作流</div>
      </el-tab-pane>
    </el-tabs>

    <!-- 检验结果 -->
    <EditInspectItem ref="editInspectItem" @complete="getList" />

    <!-- 修改检验标准 -->
    <UpdateInspection
      ref="updateInspection"
      @updateCase="getList"
      @addComplete="getList"
    />

    <!-- 单据打印 -->
    <IssuePrinit ref="issuePrinit" />
    <!-- 文件上传 -->
    <InspectFileUpload
      ref="inspectFileUpload"
      :process-no="$route.query.processNo"
      @uploadComplete="getHeadList"
    />
    <!-- 附件查看与上传 -->
    <InspectAttachmentUpload
      ref="inspectAttachmentUpload"
      :process-no="$route.query.processNo"
      :header-form="formParams"
      @uploadComplete="getHeadList"
    />
    <!-- 剥离力 -->
    <!-- <PeelingForce ref="peelingForce" /> -->
    <!-- 二次元 -->
    <!-- <QuadraticElement ref="quadraticElement" /> -->
  </div>
</template>

<script>
// finishMaterialItem
import {
  getMaterialItemPage,
  finishMaterialItem,
} from "@/api/wms/quality/inspectionCase";
import {
  getiqcInspectionHead,
  getIqcInspectionDetail_2,
  getIqcInspectionDetail_1,
} from "@/api/wms/quality/inspectionReport";
import { ifChangeMasterAdditional } from "@/api/wms/quality/inspectStandardApproval";
import {
  updateReinspection,
  getURL,
  updateAllForPCInspect,
  updateRowForPCIsQualified,
  getSupplierFileByMaterialLots,
} from "@/api/wms/quality/iqcInspectionExecute";
import BadcodeSelect from "../../components/BadCodeSelect.vue";

import { updateAuditStatus } from "@/api/wms/quality/inspectionResultApproval";
// 挑选入库
import {
  getLabelPrintDataDetail,
  updateBatchChoice,
} from "@/api/wms/incoming/register";
// 文件上传
import InspectFileUpload from "./InspectFileUpload.vue";
// 附件查看与上传
import InspectAttachmentUpload from "./InspectAttachmentUpload.vue";

// 审批任务
import ApprovalTask from "./ApprovalTaskNew.vue";
import EditInspectItem from "./EditInspectItem.vue";
import UpdateInspection from "./UpdateInspection.vue";
import IssuePrinit from "./IssuePrinit.vue";
import { parseTime } from "@/utils/ruoyi";
import { mapState } from "vuex";

// 审批流获取id接口
import { getModelPage } from "@/api/bpm/model";
// 开启审批流
// import { createProcessInstance } from '@/api/bpm/processInstance'
// 剥离力
import PeelingForce from "./PeelingForce.vue";
// 打印参数
const AccessTokenKey = "ACCESS_TOKEN";
// VUEQr
import VueQr from "vue-qr";
import QuotationTrendVue from "@/views/dashboard/QuotationTrend.vue";
import QuadraticElement from "./QuadraticElement.vue";

export default {
  components: {
    EditInspectItem,
    UpdateInspection,
    IssuePrinit,
    InspectFileUpload,
    ApprovalTask,
    BadcodeSelect,
    PeelingForce,
    InspectAttachmentUpload,
    VueQr,
    QuadraticElement,
  },
  data() {
    return {
      visible: false,
      // 遮罩
      finishOpen: false,
      open: false,
      loading: false,
      submitLoading: false,
      // 完成的loading
      buttonLoading: false,
      // 供应商附件遮罩层
      supplierLoading: false,
      activeName: "inspectDetails",
      // 挑选
      choiceStatus: false,
      finishChoice: false,
      saveLoading: false,
      disableApproval: false,

      reLoading: false,
      showSearch: true,
      // 方案id\additionalId
      wmsMaterialAdditionalId: "",
      wmsMaterialItemMasterId: "",
      // 非计量型禁用实测按钮
      // 总条数
      total: 0,
      // 品质检验执行主列表
      list: [],
      // 挑选查询列表
      choiceList: [],
      // 表体list
      list1: [],
      list2: [],
      valueList: [],
      // 是否允许修改检验标准
      ifModify: "",
      // 根据状态判断是否新增
      updateInspectStatus: "",
      // 版本
      version: "",
      // 根据审核状态判断调哪个接口
      apiStatus: "",
      formParams: {
        checkName: "",
      },
      // 批核结果参数
      adjustForm: {
        noPassType: "",
        manage: null,
      },
      // 单据打印参数
      tokens: "",
      baseUrl: "",
      reportId: "",
      printLoading: false,
      resetInspect: false,
      // 审批流
      processMessage: {},
      // 流程详细Id
      processDetailId: "",
      // 选中的
      currentRows: [],
      tailSelected: false,
      // 查询参数
      queryParams: {
        id: null,
        inspectionRegisterId: null,
        inspectionNo: null,
        inspectionResult: null,
        badNo: null,
        createTime: [],
        materialLots: null,
        materialNo: null,
        processNo: null,
      },
      // 校验规则
      rules: {
        noPassType: [
          {
            required: true,
            message: "请选择检验结果",
            trigger: "blur",
          },
        ],
      },
      // 挑选参数
      choiceParams: {
        materialLots: null,
      },
    };
  },
  computed: {
    ...mapState({
      routeLists: (state) => state.permission.addRoutes,
    }),
  },
  created() {
    this.getProcessIds();
    const {
      materialLots,
      materialNo,
      materialName,
      processNo,
      auditStatus,
      type,
      id,
    } = this.$route.query;
    this.queryParams.materialLots = materialLots;
    this.queryParams.id = id;
    this.queryParams.materialNo = materialNo;
    this.queryParams.processNo = processNo;
    this.apiStatus = parseInt(auditStatus);
    this.queryParams.name = materialName;
    this.queryParams.type = type;
    this.handleQuery();
    this.getHeadList();
    this.tokens = localStorage.getItem(AccessTokenKey);
    this.baseUrl = process.env.VUE_APP_REPORT_API;
  },
  methods: {
    /** 查询列表 */
    async getList() {
      this.loading = true;
      // 打印单据report Id
      this.reportId = this.$route.meta.reportId;
      try {
        // 执行查询
        this.formParams.auditTime = parseTime(this.formParams.auditTime);
        // 参数
        const params = {
          materialLots: this.queryParams.materialLots,
          showVoid: false,
          processNo: "PURCHASE",
        };
        // 表头表体列表
        const raw1 = await getIqcInspectionDetail_2(params);
        const raw2 = await getIqcInspectionDetail_1(params);
        // 添加安全检查，确保data数组存在
        const data1 = raw1.data || [];
        const data2 = raw2.data || [];
        const list = [...data2, ...data1];
        // page查询
        const rawData = await getMaterialItemPage(this.queryParams);
        // 添加安全检查，防止rawData.data为undefined
        const rawDataContent = rawData.data || {};
        this.ifModify = rawDataContent.ifModify;
        this.$refs.updateInspection.queryObj = rawDataContent.masterData || {};

        // 添加安全检查，确保list数组存在
        const rawValueList = rawDataContent.list || [];
        // 添加安全检查，确保maxMaterialAdditional对象存在
        const maxAdditional = rawDataContent.maxMaterialAdditional || {};
        this.wmsMaterialAdditionalId = maxAdditional.id || "";
        this.wmsMaterialItemMasterId =
          maxAdditional.wmsMaterialItemMasterId || "";
        this.updateInspectStatus = maxAdditional.status || "";

        const valueList = rawValueList.map((item) => {
          const { maxValue, minValue, standValue, id, badId } = item;
          return {
            id,
            maxValue,
            minValue,
            standValue,
            badId,
          };
        });

        // 合并
        this.list = list.reduce((acc, cur) => {
          const { id } = cur;
          const item = valueList.find((i) => i.id === id) || {};
          const { maxValue, minValue, standValue, badId } = item;
          const data = {
            ...{
              maxValue,
              minValue,
              standValue,
              badId,
            },
            ...cur,
          };
          if (data.tool === "拉力机") {
            this.handleQualified(data);
          }
          acc.push(data);
          return acc;
        }, []);
        // 审批重回QC录入
        const isShow = this.list.every(
          (show) =>
            show.singleResultNum !== null && show.singleResultNum !== undefined
        );
        if (!isShow) {
          this.disableApproval = true;
        } else {
          this.disableApproval = false;
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    // 挑选列表
    async getChoiceList() {
      this.loading = true;
      // 执行查询
      try {
        const { data } = await getLabelPrintDataDetail(this.choiceParams);
        // 添加安全检查，确保data对象存在
        const choiceData = data || {};
        this.choiceList = choiceData.list || [];
        this.total = choiceData.total || 0;
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    // 获取iqc报告表头
    getHeadList() {
      const params = {
        key: this.queryParams.materialLots,
        processNo: "PURCHASE",
      };
      getiqcInspectionHead(params).then((res) => {
        // 添加安全检查，确保res.data存在且为数组
        const headData = res.data || [];
        this.formParams = headData[0] || {};
        const { title, noPassType, inspector, manage, produceDate } =
          this.formParams;
        this.formParams.checkName = title;
        this.formParams.produceDate = parseTime(produceDate);
        this.adjustForm.noPassType =
          noPassType === null ? this.adjustForm.noPassType : noPassType;
        if (
          this.adjustForm.noPassType !== "" &&
          this.adjustForm.noPassType != null
        ) {
          this.tailSelected = true;
        }
        this.adjustForm.inspector = inspector;
        this.adjustForm.manage = manage;
        if (this.adjustForm.noPassType === "2") {
          const { materialLots } = this.queryParams;
          this.choiceParams.materialLots = materialLots;
          this.getChoiceList();
        }
        if (
          this.formParams.bpmInstanceId !== null &&
          this.formParams !== undefined
        ) {
          this.resetInspect = true;
        } else {
          this.resetInspect = false;
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
    },
    // 重置
    reset() {
      this.form = {
        manage: undefined,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNo = 1
      this.getList();
    },
    // 选择批核结果
    async noPassChange(v) {
      this.tailSelected = true;
      //  v === '2' --》挑选入库
      if (v === "2") {
        const { materialLots } = this.queryParams;
        this.choiceParams.materialLots = materialLots;
        await this.getChoiceList();
        const isEmpty = this.choiceList.some(
          (item) =>
            item.badQty === null ||
            item.badQty === undefined ||
            item.badQty === ""
        );
        // 只允许挑选一次，挑选完批核按钮高亮
        if (isEmpty) {
          this.choiceStatus = true;
          this.finishChoice = false;
        } else {
          this.choiceStatus = false;
          this.finishChoice = true;
        }
        this.handleFinishChoice();
      } else {
        this.handleFinishChoice();
      }
    },
    // 送审
    handleTesting() {
      // 开启工作流
      if (
        this.formParams.bpmInstanceId !== null &&
        this.formParams.bpmInstanceId !== undefined
      ) {
        this.activeName = "approvalTask";
      } else {
        // 普通审批流
        //  apiStatus === -1 为待检验 操作 送审
        if (this.apiStatus === -1) {
          this.$modal
            .confirm("您正在送审操作，是否继续？")
            .then(async () => {
              //   // 开启审批流
              if (
                this.processMessage !== null &&
                Object.keys(this.processMessage).length > 0
              ) {
                this.submitLoading = QuotationTrendVue;
                const params = {
                  materialNo: this.queryParams.materialNo,
                  materialLots: this.queryParams.materialLots,
                  version: this.formParams.version,
                  processNo: this.formParams.processNo,
                  bpmInstanceId: this.processDetailId.data,
                };
                finishMaterialItem(params)
                  .then((res) => {
                    this.handleSave();
                    this.$modal.msgSuccess("送审完成~");
                    this.$emit("complete");
                    this.getList();
                    this.visible = false;
                    this.open = false;
                    this.finishOpen = false;
                    this.submitLoading = false;
                    // 关闭当前窗口
                    this.$tab.closeOpenPage();
                    // this.$router.go(-1)
                    this.$router.push({
                      path: "/quality/iqcInspection/inspectionExecute",
                      query: { id: res.data },
                    });
                    this.reset();
                  })
                  .finally(() => {
                    this.submitLoading = false;
                    this.saveLoading = false;
                  });
              } else {
                const params = {
                  materialNo: this.queryParams.materialNo,
                  materialLots: this.queryParams.materialLots,
                  version: this.formParams.version,
                  processNo: this.formParams.processNo,
                };
                this.submitLoading = true;
                finishMaterialItem(params)
                  .then((res) => {
                    this.handleSave();
                    this.$modal.msgSuccess("送审完成~");
                    this.$emit("complete");
                    this.visible = false;
                    this.open = false;
                    this.finishOpen = false;
                    // 关闭当前窗口
                    this.$tab.closeOpenPage();
                    this.$router.go(-1);
                    this.reset();
                  })
                  .finally(() => {
                    this.submitLoading = false;
                    this.saveLoading = false;
                  });
              }
            })
            .catch((err) => {
              console.log(err);
              // this.$modal.msg('您已取消操作')
            });
        } else if (this.apiStatus === 0) {
          // apiStatus === 0 为待审核 操作批核
          const params = {
            noPassType: this.adjustForm.noPassType,
            id: this.queryParams.id,
            materialNo: this.queryParams.materialNo,
            materialLots: this.queryParams.materialLots,
            processNo: this.formParams.processNo,
          };
          updateAuditStatus(params)
            .then((res) => {
              this.$modal.msgSuccess("批核完成！");
              this.$emit("complete");
              this.visible = false;
              this.open = false;
              // 关闭当前窗口
              this.$tab.closeOpenPage();
              this.$router.go(-1);
              this.reset();
              this.submitLoading = false;
              this.finishOpen = false;
              this.queryParams.materialLots = undefined;
              this.queryParams.materialNo = undefined;
              this.queryParams.id = undefined;
            })
            .finally(() => {
              this.submitLoading = false;
              this.queryParams.materialLots = undefined;
              this.queryParams.materialNo = undefined;
              this.queryParams.id = undefined;
            });
        }
      }
    },
    // 重新检验
    handleResetInspection() {
      this.$modal
        .confirm("您正在执行重新检验操作，该操作会导致数据全部清空，是否继续？")
        .then(() => {
          const params = {
            id: this.queryParams.id,
            materialNo: this.queryParams.materialNo,
            materialLots: this.queryParams.materialLots,
            type: this.queryParams.type,
            processNo: this.formParams.processNo,
          };
          this.reLoading = true;
          updateReinspection(params).then((res) => {
            this.$modal.msgSuccess("操作成功");
            this.$emit("resetComplete");
            this.visible = false;
            this.getList();
            this.reLoading = false;
            // 关闭当前窗口
            this.$tab.closeOpenPage();
            this.$router.go(-1);
          });
        })
        .catch(() => {
          this.$modal.msg("您已取消操作");
        })
        .finally(() => {
          this.reLoading = false;
        });
    },
    // 申请修改
    handleApply() {
      // this.$refs.updateInspection.queryParams = this.formParams
      const { materialNo, materialName } = this.formParams;
      this.$refs.updateInspection.queryParams.name = materialName;
      this.$refs.updateInspection.queryParams.materialNo = materialNo;
      if (this.formParams.checkName !== null) {
        this.$refs.updateInspection.queryObj.name = this.formParams.checkName;
      }
      this.$refs.updateInspection.queryParams.wmsMaterialAdditionalId =
        this.wmsMaterialAdditionalId;
      this.$refs.updateInspection.queryParams.wmsMaterialItemMasterId =
        this.wmsMaterialItemMasterId;
      this.$refs.updateInspection.iqcInspectShow = true;
      this.$refs.updateInspection.queryParams.processNo = "PURCHASE";
      this.$refs.updateInspection.queryParams.type = 0;
      this.$refs.updateInspection.processNameShow = true;

      // page返回的status为0 检验标准详情按钮则为保存， 否则按钮为新增
      if (this.updateInspectStatus !== 0) {
        this.$refs.updateInspection.btnText = "add";
        this.$refs.updateInspection.commitDisable = true;
        this.$refs.updateInspection.refreshDisable = true;
      } else {
        this.$refs.updateInspection.btnText = "save";
        this.$refs.updateInspection.commitDisable = false;
        this.$refs.updateInspection.selectDisable = true;
        this.$refs.updateInspection.wmsMaterialAdditionalId =
          this.wmsMaterialAdditionalId;
        const changeParams = {
          id: this.wmsMaterialAdditionalId,
          code: this.formParams.materialNo,
        };
        // 判断方案是否为最新，不是最新则提示用户刷新
        ifChangeMasterAdditional(changeParams).then((res) => {
          if (res.data === false) {
            this.$refs.updateInspection.refreshDisable = true;
          } else {
            this.$modal.notifyWarning(
              "该方案或已被他人修改，如您需要最新方案，请点击刷新按钮获取！"
            );
            this.$refs.updateInspection.refreshDisable = false;
          }
        });
      }
      this.$refs.updateInspection.visible = true;
    },
    // 弹窗关闭
    dialogClose() {
      this.formParams = {};
      this.list = [];
      this.adjustForm.noPassType = "0";
    },
    // 表格列合并
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      const { inspectionModel } = row;
      // 合并列
      if (inspectionModel === 1) {
        if (columnIndex === 6) {
          return [1, 5];
        } else if (
          columnIndex === 7 ||
          columnIndex === 8 ||
          columnIndex === 9 ||
          columnIndex === 10
        ) {
          return [0, 0];
        }
      }
    },
    // 检验单打印
    handlePrint() {
      const materialLots = this.formParams.materialLots || "";
      const processNo = this.formParams.processNo;
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&materialLots=${materialLots}&processNo=${processNo}&key=${this.queryParams.materialLots}`;
      this.$refs.issuePrinit.dialogVisible = true;
      this.$refs.issuePrinit.src = src;
    },
    // 作废的数据添加删除线
    delLine({ row, column }) {
      const { voidOrNot } = row;
      if (voidOrNot === "1") {
        return "del_line";
      }
    },
    // 挑选完成
    async handleFinishChoice() {
      if (this.adjustForm.noPassType === "2") {
        const isEmpty = this.choiceList.some(
          (item) =>
            item.badQty === undefined ||
            item.badQty === "" ||
            item.badQty === null
        );
        if (isEmpty) {
          this.$modal.msgWarning("不良数量不能为空，请先填写不良数量!");
          return;
        }
      }
      this.buttonLoading = true;
      const choiceLists = this.choiceList.map((item) => {
        const { id, badQty } = item;
        return {
          id,
          badQty,
        };
      });
      const batchParams = {
        id: this.formParams.id,
        processNo: "PURCHASE",
        noPassType: this.adjustForm.noPassType,
        updateReqVOList: choiceLists,
        manage: this.adjustForm.manage,
      };
      updateBatchChoice(batchParams)
        .then(() => {
          this.$modal.msgSuccess("操作成功!");
          const { materialLots } = this.queryParams;
          this.choiceParams.materialLots = materialLots;
          this.getChoiceList();
          this.getList();
          this.$emit("choiceComplete");
          this.choiceStatus = false;
          this.buttonLoading = false;
        })
        .finally(() => {
          this.buttonLoading = false;
        });
    },
    // 合并一键通过
    handleAllInspect() {
      if (this.currentRows.length <= 0) {
        this.$modal.msgWarning("请选择您要检验的数据项!");
        return;
      }
      this.$refs.editInspectItem.form.id = this.currentRows[0].id;
      this.$refs.editInspectItem.inspectionModel = 0;
      this.$refs.editInspectItem.allInspectShow = false;
      this.$refs.editInspectItem.title = "一键检验结果";
      this.$refs.editInspectItem.visible = true;
      this.$refs.editInspectItem.selectRows = this.currentRows;
      this.$refs.editInspectItem.materialLots =
        this.formParams.materialLots || "";
    },
    // 选中的
    tableSelected(val) {
      this.currentRows = val;
    },
    // 上传文件/查看附件
    async handleUploadFile() {
      this.$refs.inspectFileUpload.wmsIncomingReceiptInspectionId =
        this.formParams.id;
      const params = {
        id: this.formParams.id,
        processNo: this.$route.query.processNo || null,
      };
      // await getURL(params).then(res => {
      //   this.$refs.inspectFileUpload.fileList = res.data
      // })
      const { data } = await getURL(params);
      this.$refs.inspectFileUpload.fileList = data;
      this.$refs.inspectFileUpload.isUploadShow = this.apiStatus;
      this.$refs.inspectFileUpload.visible = true;
    },
    // 获取开启审批流的id
    getProcessIds() {
      const params = {
        pageNo: 1,
        pageSize: 10,
        key: this.$route.meta.bpmnModelId,
      };
      getModelPage(params).then((res) => {
        const { processDefinition } = res.data.list[0];
        if (processDefinition) {
          if (
            Object.keys(processDefinition).length > 0 &&
            processDefinition !== null &&
            this.$route.meta.bpmnModelId !== ""
          ) {
            this.processMessage = processDefinition;
          }
        }
      });
    },
    // tab点击切换
    handleClick(tab, event) {
      this.activeName = tab.name;
    },
    badCodeChange(row, v) {
      row.badId = v;
    },
    // 保存
    async handleSave() {
      const saveList = this.list.map((item) => {
        item.actualList = [];
        item.completed = "0";
        item.materialLots = this.queryParams.materialLots;
        item.processNo = this.queryParams.processNo;
        const {
          id,
          singleResultNum: singleResultNum,
          measuredResults,
          inspectionModel,
          materialLots,
          processNo,
          badId,
          actual1,
          actual2,
          actual3,
          actual4,
          actual5,
          completed,
          actualList: actualListForPC,
        } = item;

        // 确保将null值转换为空字符串
        const convertToEmptyString = (value) =>
          value === null || value === undefined ? "" : value;

        actualListForPC.push(
          convertToEmptyString(actual1),
          convertToEmptyString(actual2),
          convertToEmptyString(actual3),
          convertToEmptyString(actual4),
          convertToEmptyString(actual5)
        );
        return {
          id,
          singleResultNum,
          inspectionModel,
          badId,
          completed,
          actualListForPC,
          materialLots,
          processNo,
          measuredResults,
        };
      });
      this.saveLoading = true;
      await updateAllForPCInspect(saveList);
      this.$modal.msgSuccess("保存成功！");
      this.getList();
      this.saveLoading = false;
    },
    // 根据输入的检查数据判断是否合格
    handleQualified(row) {
      const { id, actual1, actual2, actual3, actual4, actual5 } = row;
      const qualifyList = [];

      // 确保将null值转换为空字符串
      const convertToEmptyString = (value) =>
        value === null || value === undefined ? "" : value;

      qualifyList.push(
        convertToEmptyString(actual1),
        convertToEmptyString(actual2),
        convertToEmptyString(actual3),
        convertToEmptyString(actual4),
        convertToEmptyString(actual5)
      );
      const params = {
        id,
        actualListForPC: qualifyList,
      };
      updateRowForPCIsQualified(params).then((res) => {
        row.singleResultNum = res.data;
      });
    },
    // 查看剥离力
    handleToPeelingForce(row) {
      const { id } = row;
      this.$refs.peelingForce.queryParams.resultId = id;
      this.$refs.peelingForce.queryParams.materialLots =
        this.formParams.materialLots;
      this.$refs.peelingForce.sn = this.formParams.materialLots;
      this.$refs.peelingForce.open = true;
    },
    // 挑选不良数量
    badQtyInputChange(v) {
      const isChoiceComplete = this.choiceList.every(
        (item) =>
          item.badQty !== undefined &&
          item.badQty !== null &&
          item.badQty !== ""
      );
      if (isChoiceComplete) {
        this.handleFinishChoice();
      } else {
        this.$modal.msgWarning("不良数量不能为空，请检查是否全部填写完成!");
      }
    },
    // 查看供应商附件
    handleViewSupplierFile() {
      const { materialLots } = this.queryParams;
      const params = {
        materialLots,
      };
      getSupplierFileByMaterialLots(params).then((res) => {
        // 添加安全检查，确保res.data存在
        this.$refs.inspectFileUpload.fileList = res.data || [];
        this.$refs.inspectFileUpload.isUploadShow = 9;
        this.$refs.inspectFileUpload.visible = true;
      });
    },
    // 查看二次元
    handleQuadraticelement(row, column) {
      if (row.tool === "3") {
        const { property } = column;
        const { id } = row;
        const index =
          property === "actual1"
            ? 0
            : property === "actual2"
            ? 1
            : property === "actual3"
            ? 2
            : property === "actual4"
            ? 3
            : property === "actual5"
            ? 4
            : null;
        this.$refs.quadraticElement.queryParams.materialItemResultId = id;
        this.$refs.quadraticElement.queryParams.index = index;
        this.$refs.quadraticElement.open = true;
      }
    },
    // 直接利用行内 filesList 打开附件弹窗
    openRowFile(row) {
      // 把行内附件列表传给弹窗
      this.$refs.inspectAttachmentUpload.fileList = row.filesList || [];
      this.$refs.inspectAttachmentUpload.rowData = row;
      this.$refs.inspectAttachmentUpload.isUploadShow = -1; // 9=仅查看
      this.$refs.inspectAttachmentUpload.visible = true;
    },
    // openRowFile(row) {
    //   // 把行内附件列表传给弹窗
    //   this.$refs.inspectFileUpload.fileList = row.filesList || [];
    //   this.$refs.inspectFileUpload.isUploadShow = 9; // 9=仅查看
    //   this.$refs.inspectFileUpload.visible = true;
    // },
  },
};
</script>
<style scoped>
.stander {
  position: relative;
}
.standVal {
  position: absolute;
  top: 10px;
  left: -10px;
}
.max {
  height: 24px;
}
.line {
  display: block;
  height: 10px;
  margin-top: -14px;
}
.el-table /deep/ .del_line {
  text-decoration: line-through !important;
}
.isNotApproval {
  font-size: 18px;
  text-align: center;
  margin: 200px auto;
}
</style>
