<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" >
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工序名称" prop="processName">
              <el-input v-model="queryParams.processName" placeholder="请输入工序名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工位名称" prop="stationName">
              <el-input v-model="queryParams.stationName" placeholder="请输入工位名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="质检结果" prop="result">
              <el-select v-model="queryParams.result" placeholder="请选择质检结果" clearable >
                <el-option v-for="dict in qc_result" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
<!--            <el-form-item label="检测类别" prop="inspectionType" v-if='inspectionTypeVisible'>-->
<!--              <el-select v-model="queryParams.qcInspectionType" placeholder="请选择检测类别" >-->
<!--                <el-option v-for="dict in qc_inspection_type" :key="dict.value" :label="dict.label" :value="dict.value"/>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择单据状态" clearable >
                <el-option v-for="dict in qc_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
<!--            <el-form-item label="检验时间" prop="inspectionTime">-->
<!--              <el-date-picker clearable-->
<!--                              v-model="queryParams.inspectionTime"-->
<!--                              type="date"-->
<!--                              value-format="YYYY-MM-DD"-->
<!--                              placeholder="请选择检验时间"-->
<!--              />-->
<!--            </el-form-item>-->
            <el-form-item label="检验开始时间" label-width="100px">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['qms:QcInspectionMain:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['qms:QcInspectionMain:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['qms:QcInspectionMain:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['qms:QcInspectionMain:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="QcInspectionMainList"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- 自动序号 -->
        <el-table-column label="序号" align="center" type="index" width="55" v-if="columns[0].visible"/>
        <el-table-column label="检测单号/卡号" align="center" prop="inspectionNo" v-if="columns[1].visible"/>
        <el-table-column label="模板主表名称" align="center" prop="templateName" v-if="columns[2].visible"/>
        <el-table-column label="物料编码" align="center" prop="materialCode" v-if="columns[3].visible"/>
        <!-- <el-table-column label="物料类型" align="center" prop="materialType" v-if="columns[4].visible"/> -->
        <el-table-column label="物料名称" align="center" prop="materialName" v-if="columns[4].visible"/>
        <el-table-column label="工序名称" align="center" prop="processName" v-if="columns[5].visible"/>
        <el-table-column label="工位名称" align="center" prop="stationName" v-if="columns[6].visible"/>
        <el-table-column label="质检数量" align="center" prop="inspectionQty" v-if="columns[7].visible"/>
        <el-table-column label="合格数" align="center" prop="qualifiedQty" v-if="columns[8].visible"/>
        <el-table-column label="不合格数" align="center" prop="unqualifiedQty" v-if="columns[9].visible"/>
        <el-table-column label="质检结果" align="center" prop="result" v-if="columns[10].visible">
          <template #default="scope">
            <dict-tag :options="qc_result" :value="scope.row.result"/>
          </template>
        </el-table-column>
        <el-table-column label="车间" align="center" prop="workshop" v-if="columns[11].visible"/>
        <el-table-column label="检测类别" align="center" prop="typeName" v-if="columns[12].visible" />
        <el-table-column label="单据状态" align="center" prop="status" v-if="columns[13].visible">
          <template #default="scope">
            <dict-tag :options="qc_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="检测人员" align="center" prop="inspector" v-if="columns[14].visible"/>
        <el-table-column label="班次" align="center" prop="shift" v-if="columns[15].visible"/>
        <el-table-column label="班组" align="center" prop="team" v-if="columns[16].visible"/>
        <el-table-column label="检验时间" align="center" prop="inspectionStartTime" width="180" v-if="columns[17].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.inspectionStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="检验结束时间" align="center" prop="inspectionEndTime" width="180" v-if="columns[18].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.inspectionEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="业务来源单号" align="center" prop="productionOrder" v-if="columns[19].visible"/>
        <el-table-column label="批次号" align="center" prop="batchNo" v-if="columns[20].visible"/>
        <el-table-column label="条码号" align="center" prop="barcode" v-if="columns[21].visible"/>
        <el-table-column label="供应商名称" align="center" prop="supplierName" v-if="columns[22].visible"/>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[23].visible"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['qms:QcInspectionMain:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['qms:QcInspectionMain:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 子表显示区域 -->
    <el-card v-if="selectedInspectionId" shadow="never" class="mt-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3>质检结果子表 - {{ selectedInspectionNo }}</h3>
          <el-button type="primary" size="small" icon="Plus" @click="handleAddInspectionResult" v-hasPermi="['qms:qcInspectionResult:add']">
            新增质检结果
          </el-button>
        </div>
      </template>

      <!-- 子表搜索区域 -->
      <div class="mb-4">
        <el-form :model="inspectionResultQueryParams" :inline="true" label-width="100px">
          <el-form-item label="检测结果" prop="detectResult">
            <el-select v-model="inspectionResultQueryParams.detectResult" placeholder="请选择检测结果" clearable>
              <el-option v-for="dict in qc_result" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="检测方式" prop="detectType">
            <el-select v-model="inspectionResultQueryParams.detectType" placeholder="请选择检测方式" clearable>
              <el-option v-for="dict in detect_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getInspectionResultList">搜索</el-button>
            <el-button icon="Refresh" @click="resetInspectionResultQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 子表数据表格 -->
      <el-table v-loading="inspectionResultLoading" :data="inspectionResultList" @selection-change="handleInspectionResultSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="55" />
        <el-table-column label="关联检测项" align="center" prop="itemName" />
        <el-table-column label="检测结果" align="center" prop="detectResult">
          <template #default="scope">
            <dict-tag :options="qc_result" :value="scope.row.detectResult"/>
          </template>
        </el-table-column>
        <el-table-column label="定量检测值" align="center" prop="detectValue" />
        <el-table-column label="规格质检值" align="center" prop="specInspection" />
        <el-table-column label="定性不合格明细" align="center" prop="problemDetail" />
        <el-table-column label="检测项编码" align="center" prop="itemCode" />
        <el-table-column label="检测位置" align="center" prop="inspectionPosition" />
        <el-table-column label="检测项目类别" align="center" prop="categoryName" />
        <el-table-column label="检测方式" align="center" prop="detectType">
          <template #default="scope">
            <dict-tag :options="detect_type" :value="scope.row.detectType"/>
          </template>
        </el-table-column>
        <el-table-column label="控制类型" align="center" prop="controlType">
          <template #default="scope">
            <dict-tag :options="control_type" :value="scope.row.controlType"/>
          </template>
        </el-table-column>
        <el-table-column label="标准值" align="center" prop="standardValue" />
        <el-table-column label="控制上限" align="center" prop="upperLimit" />
        <el-table-column label="控制下限" align="center" prop="lowerLimit" />
        <el-table-column label="规格名称" align="center" prop="specName" />
        <el-table-column label="规格上限" align="center" prop="specUpper" />
        <el-table-column label="规格下限" align="center" prop="specLower" />
        <el-table-column label="检测项说明" align="center" prop="description" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdateInspectionResult(scope.row)" v-hasPermi="['qms:qcInspectionResult:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDeleteInspectionResult(scope.row)" v-hasPermi="['qms:qcInspectionResult:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="inspectionResultTotal > 0" :total="inspectionResultTotal" v-model:page="inspectionResultQueryParams.pageNum" v-model:limit="inspectionResultQueryParams.pageSize" @pagination="getInspectionResultList" />
    </el-card>

    <!-- 添加或修改质检任务对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <el-form ref="QcInspectionMainFormRef" :model="form" :rules="rules" label-width="120px">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检测单号/卡号" prop="inspectionNo">
              <el-input v-model="form.inspectionNo" placeholder="请输入检测单号/卡号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联模板主表" prop="templateId">
              <el-select v-model="form.templateId" placeholder="请选择关联模板主表">
                <el-option
                  v-for="dict in QcInspectionTemplateList"
                  :key="dict.templateId"
                  :label="dict.templateName"
                  :value="dict.templateId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">物料信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请点击检索物料" @click="handleMaterialAdd" readonly>
                <template #append>
                  <el-button icon="Search"></el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="物料名称" prop="materialName">-->
<!--              <el-input v-model="form.materialName" placeholder="请点击检索物料" @click="handleMaterialAdd" readonly />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-divider content-position="left">位置信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工序名称" prop="processName">
              <el-select v-model="selectedProcessId" placeholder="请选择工序" filterable clearable @change="handleBaseProcessInfoChange" style="width: 100%;">
                <el-option v-for="item in baseProcessInfoList" :key="item.processId" :label="item.processName" :value="item.processId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工位名称" prop="stationName">
              <el-select v-model="selectedStaionId" placeholder="请选择工位" filterable clearable @change="handleBaseStationInfoChange" style="width: 100%;">
                <el-option v-for="item in baseStationInfoList" :key="item.stationId" :label="item.stationName" :value="item.stationId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">数量信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="质检数量" prop="inspectionQty">
              <el-input v-model="form.inspectionQty" placeholder="请输入质检数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格数" prop="qualifiedQty">
              <el-input v-model="form.qualifiedQty" placeholder="请输入合格数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="不合格数" prop="unqualifiedQty" v-if="form.result == 1">
              <el-input v-model="form.unqualifiedQty" placeholder="请输入不合格数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检结果" prop="result">
              <el-select v-model="form.result" placeholder="请选择质检结果">
                <el-option
                  v-for="dict in qc_result"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">其他信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车间" prop="workshop">
              <el-input v-model="form.workshop" placeholder="请输入车间" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测类别" prop="inspectionType">
              <el-select v-model="form.inspectionType" placeholder="请选择检测类别">
                <el-option
                  v-for="dict in qc_inspection_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in qc_status"
                  :key="dict.value"
                  :value="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测人员" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入检测人员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次" prop="shift">
              <el-input v-model="form.shift" placeholder="请输入班次" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班组" prop="team">
              <el-input v-model="form.team" placeholder="请输入班组" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验开始时间" prop="inspectionStartTime">
              <el-date-picker clearable
                              v-model="form.inspectionStartTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择检验时间"
                              style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验结束时间" prop="inspectionEndTime">
              <el-date-picker clearable
                              v-model="form.inspectionEndTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择检验结束时间"
                              style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产订单号" prop="productionOrder">
              <el-input v-model="form.productionOrder" placeholder="请输入生产订单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-model="form.batchNo" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="条码号" prop="barcode">
              <el-input v-model="form.barcode" placeholder="请输入条码号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改质检结果子表对话框 -->
    <el-dialog :title="inspectionResultDialog.title" v-model="inspectionResultDialog.visible" width="1200px" append-to-body>
      <el-form ref="inspectionResultFormRef" :model="inspectionResultForm" :rules="inspectionResultRules" label-width="120px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="检测单号" prop="inspectionNo">
              <el-input v-model="selectedInspectionNo" placeholder="检测单号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关联检测项" prop="itemId">
              <el-select v-model="inspectionResultForm.itemId" placeholder="请选择关联检测项" style="width: 100%;" @change="handleItemChange">
                <el-option v-for="item in qcInspectionItemList" :key="item.itemId" :label="item.itemName" :value="item.itemId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测项编码" prop="itemCode">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="inspectionResultForm.itemCode" placeholder="检测项编码" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测项名称" prop="itemName">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="inspectionResultForm.itemName" placeholder="检测项名称" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="检测位置" prop="inspectionPosition">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="inspectionResultForm.inspectionPosition" placeholder="检测位置" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测项目类别" prop="categoryName">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="inspectionResultForm.categoryName" placeholder="检测项目类别" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测方式" prop="detectType">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-select v-model="inspectionResultForm.detectType" placeholder="检测方式" style="width: 100%;" :disabled="true">
                  <el-option v-for="dict in detect_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="控制类型" prop="controlType">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-select v-model="inspectionResultForm.controlType" placeholder="控制类型" style="width: 100%;" :disabled="true">
                  <el-option v-for="dict in control_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="标准值" prop="standardValue">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="inspectionResultForm.standardValue" placeholder="标准值" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="控制上限" prop="upperLimit">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="inspectionResultForm.upperLimit" placeholder="控制上限" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="控制下限" prop="lowerLimit">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="inspectionResultForm.lowerLimit" placeholder="控制下限" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格名称" prop="specName">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input v-model="inspectionResultForm.specName" placeholder="规格名称" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="规格上限" prop="specUpper">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="inspectionResultForm.specUpper" placeholder="规格上限" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格下限" prop="specLower">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input-number v-model="inspectionResultForm.specLower" placeholder="规格下限" style="width: 100%;" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测结果" prop="detectResult">
              <el-select v-model="inspectionResultForm.detectResult" placeholder="请选择检测结果">
                <el-option v-for="dict in qc_result" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="定量检测值" prop="detectValue">
              <el-input-number v-model="inspectionResultForm.detectValue" placeholder="定量检测值" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格质检值" prop="specInspection">
              <el-input v-model="inspectionResultForm.specInspection" placeholder="规格质检值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="定性不合格明细" prop="problemDetail">
              <el-input v-model="inspectionResultForm.problemDetail" placeholder="定性不合格明细" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="检测项说明" prop="description">
              <el-tooltip content="此字段由关联检测项自动填充，不可编辑" placement="top">
                <el-input type="textarea" v-model="inspectionResultForm.description" placeholder="检测项说明" :disabled="true" />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="inspectionResultButtonLoading" type="primary" @click="submitInspectionResultForm">确 定</el-button>
          <el-button @click="cancelInspectionResult">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加物料信息对话框 -->
    <el-dialog title="选择物料信息" v-model="materialOpen" width="1200px" append-to-body>
      <MaterialSelect ref="materialSelectRef" v-if="materialOpen"></MaterialSelect>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
          <el-button @click="materialOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="QcInspectionMain" lang="ts">
import { listQcInspectionMain, getQcInspectionMain, delQcInspectionMain, addQcInspectionMain, updateQcInspectionMain } from '@/api/qms/QcInspectionMain';
import { QcInspectionMainVO, QcInspectionMainQuery, QcInspectionMainForm } from '@/api/qms/QcInspectionMain/types';
import {getQcInspectionTemplateList} from "@/api/qms/qcInspectionTemplate";
import { listQcInspectionResult, getQcInspectionResult, delQcInspectionResult, addQcInspectionResult, updateQcInspectionResult } from '@/api/qms/qcInspectionResult';
import { QcInspectionResultVO, QcInspectionResultQuery, QcInspectionResultForm } from '@/api/qms/qcInspectionResult/types';
import { getQcInspectionItemList } from '@/api/qms/qcInspectionItem';
import { getProcessInfoList } from '@/api/qms/baseProcessInfo';
import { getStationInfoList } from '@/api/qms/baseStationInfo';

import MaterialSelect from "@/views/mes/baseMaterialInfo/addMaterialInQMS.vue";
import { useRouter, useRoute } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { qc_inspection_type, qc_result, qc_status, material_type, detect_type, control_type } = toRefs<any>(proxy?.useDict('qc_inspection_type', 'qc_result', 'qc_status', 'material_type', 'detect_type', 'control_type'));

const QcInspectionMainList = ref<QcInspectionMainVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 子表相关状态
const selectedInspectionId = ref<string | number | null>(null);
const selectedInspectionNo = ref<string>('');
const inspectionResultList = ref<QcInspectionResultVO[]>([]);
const inspectionResultLoading = ref(false);
const inspectionResultTotal = ref(0);
const inspectionResultIds = ref<Array<string | number>>([]);
const inspectionResultSingle = ref(true);
const inspectionResultMultiple = ref(true);
const inspectionResultButtonLoading = ref(false);

// 物料、工序、工位相关
const selectedProcessId = ref(null);
const selectedStaionId = ref(null);
const materialOpen = ref(false);
const materialSelectRef = ref();

const queryFormRef = ref<ElFormInstance>();
const QcInspectionMainFormRef = ref<ElFormInstance>();
const inspectionResultFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const inspectionResultDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});


//路由：inspectionType = 1产品检 2原材料检 3入库检
const inspectionType = ref();
const getInspectionType = async () => {
  const route = useRoute();
  inspectionType.value = route.query.inspectionType;
  if (inspectionType.value == 2){
    queryParams.value.inspectionType = '2';
  } else if (inspectionType.value == 3){
    queryParams.value.inspectionType = '3';
  } else {
    queryParams.value.inspectionType = '1';
  }
};

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `序号`, visible: true },
  { key: 1, label: `检测单号/卡号`, visible: true },
  { key: 2, label: `关联模板主表`, visible: true },
  { key: 3, label: `物料编码`, visible: true },
  // { key: 4, label: `物料类型`, visible: true },
  { key: 4, label: `物料名称`, visible: true },
  { key: 5, label: `工序名称`, visible: true },
  { key: 6, label: `工位名称`, visible: true },
  { key: 7, label: `质检数量`, visible: true },
  { key: 8, label: `合格数`, visible: true },
  { key: 9, label: `不合格数`, visible: true },
  { key: 10, label: `质检结果`, visible: true },
  { key: 11, label: `车间`, visible: true },
  { key: 12, label: `检测类型`, visible: true },
  { key: 13, label: `单据状态`, visible: true },
  { key: 14, label: `检测人员`, visible: true },
  { key: 15, label: `班次`, visible: true },
  { key: 16, label: `班组`, visible: true },
  { key: 17, label: `检验开始时间`, visible: true },
  { key: 18, label: `检验结束时间`, visible: true },
  { key: 19, label: `业务来源单号`, visible: true },
  { key: 20, label: `批次号`, visible: true },
  { key: 21, label: `条码号`, visible: true },
  { key: 22, label: `供应商名称`, visible: true },
  { key: 23, label: `备注`, visible: true },
]);

const initFormData: QcInspectionMainForm = {
  inspectionId: undefined,
  inspectionNo: undefined,
  templateId: undefined,
  materialCode: undefined,
  materialType: undefined,
  materialName: undefined,
  processName: undefined,
  stationName: undefined,
  inspectionQty: undefined,
  qualifiedQty: undefined,
  unqualifiedQty: undefined,
  result: undefined,
  workshop: undefined,
  inspectionType: undefined,
  status: undefined,
  inspector: undefined,
  shift: undefined,
  team: undefined,
  inspectionStartTime: undefined,
  inspectionEndTime: undefined,
  productionOrder: undefined,
  batchNo: undefined,
  barcode: undefined,
  supplierName: undefined,
  remark: undefined,
}

const initInspectionResultFormData: QcInspectionResultForm = {
  resultId: undefined,
  inspectionId: undefined,
  itemId: undefined,
  detectResult: undefined,
  detectValue: undefined,
  specInspection: undefined,
  problemDetail: undefined,
  itemCode: undefined,
  itemName: undefined,
  inspectionPosition: undefined,
  categoryName: undefined,
  typeId: undefined,
  detectType: undefined,
  controlType: undefined,
  standardValue: undefined,
  upperLimit: undefined,
  lowerLimit: undefined,
  specName: undefined,
  specUpper: undefined,
  specLower: undefined,
  description: undefined,
}

const data = reactive<PageData<QcInspectionMainForm, QcInspectionMainQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inspectionId: undefined,
    inspectionNo: undefined,
    templateId: undefined,
    materialCode: undefined,
    materialType: undefined,
    materialName: undefined,
    processName: undefined,
    stationName: undefined,
    inspectionQty: undefined,
    qualifiedQty: undefined,
    unqualifiedQty: undefined,
    result: undefined,
    workshop: undefined,
    inspectionType: undefined,
    status: undefined,
    inspector: undefined,
    shift: undefined,
    team: undefined,
    inspectionStartTime: undefined,
    inspectionEndTime: undefined,
    productionOrder: undefined,
    batchNo: undefined,
    barcode: undefined,
    supplierName: undefined,
    params: {
    }
  },
  rules: {
  }
});

// 子表数据
const inspectionResultForm = ref<QcInspectionResultForm>({...initInspectionResultFormData});
const inspectionResultQueryParams = ref<QcInspectionResultQuery>({
  pageNum: 1,
  pageSize: 10,
  resultId: undefined,
  inspectionId: undefined,
  itemId: undefined,
  detectResult: undefined,
  detectValue: undefined,
  specInspection: undefined,
  problemDetail: undefined,
  itemCode: undefined,
  itemName: undefined,
  inspectionPosition: undefined,
  categoryName: undefined,
  typeId: undefined,
  detectType: undefined,
  controlType: undefined,
  standardValue: undefined,
  upperLimit: undefined,
  lowerLimit: undefined,
  specName: undefined,
  specUpper: undefined,
  specLower: undefined,
  description: undefined,
  params: {}
});

const inspectionResultRules = ref({
  itemId: [
    { required: true, message: "关联检测项不能为空", trigger: "blur" }
  ],
  detectResult: [
    { required: true, message: "检测结果不能为空", trigger: "blur" }
  ],
});

const { queryParams, form, rules } = toRefs(data);

const dateRange = ref([]);

/** 查询质检任务列表 */
const getList = async () => {
  loading.value = true;
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.params = {
      ...queryParams.value.params,
      beginInspectionStartTime: dateRange.value[0],
      endInspectionStartTime: dateRange.value[1]
    };
  } else {
    if (queryParams.value.params) {
      delete queryParams.value.params.beginInspectionStartTime;
      delete queryParams.value.params.endInspectionStartTime;
    }
  }
  const res = await listQcInspectionMain(queryParams.value);
  QcInspectionMainList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 查询质检结果子表列表 */
const getInspectionResultList = async () => {
  if (!selectedInspectionId.value) return;

  inspectionResultLoading.value = true;
  // 设置inspectionId过滤条件
  inspectionResultQueryParams.value.inspectionId = selectedInspectionId.value;
  const res = await listQcInspectionResult(inspectionResultQueryParams.value);
  inspectionResultList.value = res.rows;
  inspectionResultTotal.value = res.total;
  inspectionResultLoading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  QcInspectionMainFormRef.value?.resetFields();
  selectedProcessId.value = null;
  selectedStaionId.value = null;
}

/** 子表取消按钮 */
const cancelInspectionResult = () => {
  resetInspectionResult();
  inspectionResultDialog.visible = false;
}

/** 子表表单重置 */
const resetInspectionResult = () => {
  inspectionResultForm.value = {...initInspectionResultFormData};
  inspectionResultFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
  dateRange.value = [];
}

/** 重置子表搜索 */
const resetInspectionResultQuery = () => {
  inspectionResultQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    resultId: undefined,
    inspectionId: selectedInspectionId.value,
    itemId: undefined,
    detectResult: undefined,
    detectValue: undefined,
    specInspection: undefined,
    problemDetail: undefined,
    itemCode: undefined,
    itemName: undefined,
    inspectionPosition: undefined,
    categoryName: undefined,
    typeId: undefined,
    detectType: undefined,
    controlType: undefined,
    standardValue: undefined,
    upperLimit: undefined,
    lowerLimit: undefined,
    specName: undefined,
    specUpper: undefined,
    specLower: undefined,
    description: undefined,
    params: {}
  };
  getInspectionResultList();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: QcInspectionMainVO[]) => {
  ids.value = selection.map(item => item.inspectionId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 子表多选框选中数据 */
const handleInspectionResultSelectionChange = (selection: QcInspectionResultVO[]) => {
  inspectionResultIds.value = selection.map(item => item.resultId);
  inspectionResultSingle.value = selection.length != 1;
  inspectionResultMultiple.value = !selection.length;
}

/** 行点击事件 */
const handleRowClick = (row: QcInspectionMainVO) => {
  selectedInspectionId.value = row.inspectionId;
  selectedInspectionNo.value = row.inspectionNo || '';
  // 刷新子表数据
  nextTick(() => {
    getInspectionResultList();
  });
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getBaseProcessList();
  getBaseStationList();
  dialog.visible = true;
  dialog.title = "添加质检任务";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: QcInspectionMainVO) => {
  reset();
  getBaseProcessList();
  getBaseStationList();
  const _inspectionId = row?.inspectionId || ids.value[0]
  const res = await getQcInspectionMain(_inspectionId);
  Object.assign(form.value, res.data);


  dialog.visible = true;
  dialog.title = "修改质检任务";
}

/** 新增质检结果 */
const handleAddInspectionResult = () => {
  resetInspectionResult();
  inspectionResultForm.value.inspectionId = selectedInspectionId.value;
  inspectionResultDialog.visible = true;
  inspectionResultDialog.title = "添加质检结果";
}

/** 修改质检结果 */
const handleUpdateInspectionResult = async (row?: QcInspectionResultVO) => {
  resetInspectionResult();
  const _resultId = row?.resultId || inspectionResultIds.value[0];
  const res = await getQcInspectionResult(_resultId);
  Object.assign(inspectionResultForm.value, res.data);
  handleItemChange(inspectionResultForm.value.itemId);
  inspectionResultDialog.visible = true;
  inspectionResultDialog.title = "修改质检结果";
}

/** 删除质检结果 */
const handleDeleteInspectionResult = async (row?: QcInspectionResultVO) => {
  const _resultIds = row?.resultId || inspectionResultIds.value;
  await proxy?.$modal.confirm('是否确认删除质检结果编号为"' + _resultIds + '"的数据项？').finally(() => inspectionResultLoading.value = false);
  await delQcInspectionResult(_resultIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getInspectionResultList();
  await getList(); // 新增
}

/** 提交按钮 */
const submitForm = () => {
  QcInspectionMainFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.inspectionId) {
        await updateQcInspectionMain(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addQcInspectionMain(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 子表提交按钮 */
const submitInspectionResultForm = () => {
  inspectionResultFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      inspectionResultButtonLoading.value = true;
      if (inspectionResultForm.value.resultId) {
        await updateQcInspectionResult(inspectionResultForm.value).finally(() => inspectionResultButtonLoading.value = false);
      } else {
        await addQcInspectionResult(inspectionResultForm.value).finally(() => inspectionResultButtonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      inspectionResultDialog.visible = false;
      await getInspectionResultList();
      await getList(); // 新增
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: QcInspectionMainVO) => {
  const _inspectionIds = row?.inspectionId || ids.value;
  await proxy?.$modal.confirm('是否确认删除质检任务编号为"' + _inspectionIds + '"的数据项？').finally(() => loading.value = false);
  await delQcInspectionMain(_inspectionIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('qms/QcInspectionMain/export', {
    ...queryParams.value
  }, `QcInspectionMain_${new Date().getTime()}.xlsx`)
}

/** 获取检测模板列表*/
let QcInspectionTemplateList = ref([]);
const getInspectionTemplateList = async () => {
  const res = await getQcInspectionTemplateList(null);
  QcInspectionTemplateList.value = res.data;
};

//获取检测项列表（不分页，获取全部）
let qcInspectionItemList = ref([]);
const getInspectionItemList = async () => {
  const res = await getQcInspectionItemList(null);
  qcInspectionItemList.value = res.data;
}

/** 关联检测项定义选择变化 */
const handleItemChange = (value) => {
  const selected = qcInspectionItemList.value.find(item => item.itemId === value);
  if (selected) {
    inspectionResultForm.value.itemCode = selected.itemCode;
    inspectionResultForm.value.itemName = selected.itemName;
    inspectionResultForm.value.detectType = selected.detectType;
    inspectionResultForm.value.controlType = selected.controlType;
    inspectionResultForm.value.categoryName = selected.categoryName || '';
    // inspectionResultForm.value.inspectionType = selected.inspectionType;
    inspectionResultForm.value.inspectionPosition = selected.inspectionPosition;
    inspectionResultForm.value.standardValue = selected.standardValue;
    inspectionResultForm.value.upperLimit = selected.upperLimit;
    inspectionResultForm.value.lowerLimit = selected.lowerLimit;
    inspectionResultForm.value.specName = selected.specName;
    inspectionResultForm.value.specUpper = selected.specUpper;
    inspectionResultForm.value.specLower = selected.specLower;
    inspectionResultForm.value.description = selected.description;
  } else {
    // Optionally reset fields
  }
}

// 获取工序列表（不分页，获取全部）
let baseProcessInfoList = ref([]);
const getBaseProcessList = async () => {
  const res = await getProcessInfoList(null);
  baseProcessInfoList.value = res.data;
}

// 获取工位列表（不分页，获取全部）
let baseStationInfoList = ref([]);
const getBaseStationList = async () => {
  const res = await getStationInfoList(null);
  baseStationInfoList.value = res.data;
}

/*工序名称选择变化 */
const handleBaseProcessInfoChange = (value) => {
  const selected = baseProcessInfoList.value.find(item => item.processId === value);
  if (selected) {
    form.value.processName = selected.processName;
  } else {
    form.value.processName = '';
  }
}

/* 工位名称选择变化 */
const handleBaseStationInfoChange = (value) => {
  const selected = baseStationInfoList.value.find(item => item.stationId === value);
  if (selected) {
    form.value.stationName = selected.stationName;
  } else {
    form.value.stationName = ''
  }
}

/** 物料选择弹窗 */
const handleMaterialAdd = () => {
  materialOpen.value = true;
};

/** 确定按钮 */
const submitMaterialForm = () => {
  const selected = materialSelectRef.value.tableRef.store.states.currentRow.value;
  if (selected) {
    form.value.materialName = selected.materialName;
    form.value.materialCode = selected.materialCode;
    form.value.materialType = selected.matrialTypeName;
  }
  materialOpen.value = false;
};

onMounted(() => {
  getInspectionType();
  getInspectionTemplateList();
  getInspectionItemList();
  getList();
});
</script>
