src/views/qualityManagement/finalInspection/components/formDia.vue
@@ -49,16 +49,85 @@
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="单位:" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="数量:" prop="quantity">
              <el-input-number :step="0.01" :min="0" style="width: 100%" v-model="form.quantity" placeholder="请输入" clearable :precision="2"/>
            <el-form-item label="批号:" prop="batchNo">
              <el-input
                v-model="form.batchNo"
                placeholder="请输入"
                clearable
                :disabled="operationType === 'edit'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="UID码:" prop="uidNo">
              <el-input v-model="form.uidNo" placeholder="请输入" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="检品数量:" prop="inspectedQuantity">
              <el-input-number :step="0.01" :min="0" style="width: 100%" v-model="form.inspectedQuantity" placeholder="请输入" clearable :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总数量:" prop="quantity">
              <el-input-number :step="0.01" :min="0" style="width: 100%" v-model="form.quantity" placeholder="请输入" clearable :precision="2" :disabled="quantityDisabled"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="检品数量:" prop="inspectedQuantity">
              <el-input-number :step="0.01" :min="0" style="width: 100%" v-model="form.inspectedQuantity" placeholder="请输入,不大于总数量" clearable :precision="2" :disabled="quantityDisabled"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验用粉剂/液情况:" prop="inspectMaterialCondition">
              <el-radio-group v-model="form.inspectMaterialCondition">
                <el-radio label="检验用粉剂情况">检验用粉剂情况</el-radio>
                <el-radio label="检验用液剂情况">检验用液剂情况</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="生产日期:" prop="productionDate">
              <el-date-picker
                  v-model="form.productionDate"
                  type="date"
                  placeholder="请选择日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  clearable
                  style="width: 100%"
                  @change="calculateValidityDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期:" prop="validityDate">
              <el-date-picker
                  v-model="form.validityDate"
                  type="date"
                  placeholder="自动计算或手动选择"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  clearable
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
@@ -108,9 +177,51 @@
            :tableLoading="tableLoading"
            height="400"
         >
            <template #slot="{ row }">
               <el-input v-model="row.testValue" clearable/>
            </template>
            <template #instrument="{ row }">
          <el-select
              v-model="row.instrument"
              placeholder="请选择或输入"
              filterable
              allow-create
              default-first-option
              clearable
              style="width: 100%"
              @change="handleInstrumentChange(row)"
          >
            <el-option label="目测" value="目测" />
            <el-option
                v-for="item in deviceList"
                :key="item.id"
                :label="item.deviceName + (item.deviceModel ? ' / ' + item.deviceModel : '')"
                :value="item.deviceName"
            />
          </el-select>
        </template>
        <template #deviceStatus="{ row }">
          <el-select
              v-model="row.deviceStatus"
              placeholder="请选择"
              default-first-option
              clearable
              style="width: 100%"
          >
            <el-option label="正常" value="正常" />
            <el-option label="停机" value="停机" />
            <el-option label="运行" value="运行" />
            <el-option label="维修" value="维修" />
            <el-option label="/" value="/" />
          </el-select>
        </template>
        <template #result="{ row }">
          <el-input v-model="row.result" placeholder="请输入" clearable />
        </template>
        <template #resultJudgment="{ row }">
          <el-select v-model="row.resultJudgment" placeholder="请选择" clearable style="width: 100%">
            <el-option label="合格" value="合格" />
            <el-option label="不合格" value="不合格" />
            <el-option label="/" value="/" />
          </el-select>
        </template>
         </PIMTable>
      <template #footer>
        <div class="dialog-footer">
@@ -123,18 +234,28 @@
</template>
<script setup>
import {ref, reactive, toRefs, getCurrentInstance, nextTick} from "vue";
import {ref, reactive, toRefs, computed, getCurrentInstance, nextTick} from "vue";
import {getOptions} from "@/api/procurementManagement/procurementLedger.js";
import {modelList, productTreeList} from "@/api/basicData/product.js";
import {qualityInspectAdd, qualityInspectUpdate} from "@/api/qualityManagement/rawMaterialInspection.js";
import {userListNoPage} from "@/api/system/user.js";
import {qualityInspectDetailByProductId, getQualityTestStandardParamByTestStandardId} from "@/api/qualityManagement/metricMaintenance.js";
import {qualityInspectParamInfo} from "@/api/qualityManagement/qualityInspectParam.js";
import {deviceList as qualityInspectParamDeviceList} from "@/api/energyManagement/index.js";
const { proxy } = getCurrentInstance()
const emit = defineEmits(['close'])
const dialogFormVisible = ref(false);
const operationType = ref('')
const validateBatchNo = (rule, value, callback) => {
  if (value === undefined || value === null || String(value).trim() === '') {
    callback(new Error('请输入批号'));
    return;
  }
  callback();
};
const data = reactive({
  form: {
    checkTime: "",
@@ -146,7 +267,14 @@
    model: "",
    testStandardId: "",
    unit: "",
    uidNo: "",
    batchNo: "",
    inspectedQuantity: "",
    quantity: "",
    inspectedQuantity: "",
    inspectMaterialCondition: "",
    productionDate: "",
    validityDate: "",
    checkCompany: "",
    checkResult: "",
  },
@@ -158,36 +286,83 @@
    productModelId: [{ required: true, message: "请选择", trigger: "change" }],
    testStandardId: [{required: false, message: "请选择指标", trigger: "change"}],
    unit: [{ required: false, message: "请输入", trigger: "blur" }],
    inspectedQuantity: [{ required: true, message: "请输入", trigger: "blur" }],
    quantity: [{ required: true, message: "请输入", trigger: "blur" }],
    inspectedQuantity: [
      { required: true, message: "请输入检品数量", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value !== '' && value !== null && value !== undefined) {
            const qty = Number(form.value.quantity);
            const inspectedQty = Number(value);
            if (!isNaN(qty) && !isNaN(inspectedQty) && inspectedQty > qty) {
              callback(new Error("检品数量不能大于总数量"));
            } else {
              callback();
            }
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    checkCompany: [{ required: false, message: "请输入", trigger: "blur" }],
    batchNo: [{ required: true, validator: validateBatchNo, trigger: "blur" }],
    checkResult: [{ required: true, message: "请输入", trigger: "change" }],
  },
});
const { form, rules } = toRefs(data);
// 编辑时:productMainId 或 purchaseLedgerId 任一有值则数量置灰
const quantityDisabled = computed(() => {
  const v = form.value || {};
  return !!(v.productMainId != null || v.purchaseLedgerId != null);
});
const supplierList = ref([]);
const productOptions = ref([]);
const tableColumn = ref([
   {
      label: "指标",
      label: "检测项目",
      prop: "parameterItem",
      width: 150
   },
   {
      label: "单位",
      prop: "unit",
   },
   {
      label: "标准值",
      label: "标准要求",
      prop: "standardValue",
      width: 180
   },
  {
    label: "单位",
    prop: "unit",
    width: 70
  },
  {
    label: "检测器具",
    prop: "instrument",
    dataType: 'slot',
    slot: 'instrument',
    width: 220
  },
  {
    label: "设备状态",
    prop: "deviceStatus",
    dataType: 'slot',
    slot: 'deviceStatus',
    width: 120
  },
  {
    label: "检测结果",
    prop: "result",
    dataType: 'slot',
    slot: 'result',
    width: 150
  },
   {
      label: "内控值",
      prop: "controlValue",
   },
   {
      label: "检验值",
      prop: "testValue",
      label: "结果判断",
      prop: "resultJudgment",
      dataType: 'slot',
      slot: 'slot',
      slot: 'resultJudgment',
      width: 120
   },
]);
const tableData = ref([]);
@@ -196,75 +371,108 @@
const currentProductId = ref(0);
const testStandardOptions = ref([]); // 指标选择下拉框数据
const modelOptions = ref([]);
const deviceList = ref([]);
// 打开弹框
const openDialog = async (type, row) => {
  operationType.value = type;
  dialogFormVisible.value = true;
  getOptions().then((res) => {
    supplierList.value = res.data;
  });
   let userLists = await userListNoPage();
   userList.value = userLists.data;
   form.value = {}
  // 先清空表单验证状态,避免闪烁
  await nextTick();
  proxy.$refs.formRef?.clearValidate();
  // 加载设备台账列表
  loadDeviceList();
  // 并行加载基础数据
  const [userListsRes] = await Promise.all([
    userListNoPage(),
    getProductOptions(),
    getOptions().then((res) => {
      supplierList.value = res.data;
    })
  ]);
  userList.value = userListsRes.data;
  form.value = {}
  testStandardOptions.value = [];
  tableData.value = [];
  getProductOptions();
  if (operationType.value === 'edit') {
    // 先保存 testStandardId,避免被清空
    const savedTestStandardId = row.testStandardId;
    // 先设置表单数据,但暂时清空 testStandardId,等选项加载完成后再设置
    form.value = {...row, testStandardId: ''}
      currentProductId.value = row.productId || 0
      // 编辑模式下,先加载指标选项,然后加载参数列表
      if (currentProductId.value) {
         // 先加载指标选项
         let params = {
            productId: currentProductId.value,
            inspectType: 2
         }
         qualityInspectDetailByProductId(params).then(res => {
            testStandardOptions.value = res.data || [];
            // 使用 nextTick 和 setTimeout 确保选项已经渲染到 DOM
            nextTick(() => {
               setTimeout(() => {
                  // 如果编辑数据中有 testStandardId,则设置并加载对应的参数
                  if (savedTestStandardId) {
                     // 确保类型匹配(item.id 可能是数字或字符串)
                     const matchedOption = testStandardOptions.value.find(item =>
                        item.id == savedTestStandardId || String(item.id) === String(savedTestStandardId)
                     );
                     if (matchedOption) {
                        // 确保使用匹配项的 id(保持类型一致)
                        form.value.testStandardId = matchedOption.id;
                        // 编辑场景保留已有检验值,直接拉取原参数数据
                        getQualityInspectParamList(row.id);
                     } else {
                        // 如果找不到匹配项,尝试直接使用原值
                        console.warn('未找到匹配的指标选项,testStandardId:', savedTestStandardId, '可用选项:', testStandardOptions.value);
                        form.value.testStandardId = savedTestStandardId;
                        getQualityInspectParamList(row.id);
                     }
                  } else {
                     // 否则使用旧的逻辑
                     getQualityInspectParamList(row.id);
                  }
               }, 100);
            });
         });
      } else {
         getQualityInspectParamList(row.id);
      }
    currentProductId.value = row.productId || 0
    // 清空验证状态,避免数据加载过程中的校验闪烁
    nextTick(() => {
      proxy.$refs.formRef?.clearValidate();
    });
    // 编辑模式下,并行加载规格型号和指标选项
    if (currentProductId.value) {
      // 设置产品名称
      form.value.productName = findNodeById(productOptions.value, currentProductId.value);
      // 并行加载规格型号和指标选项
      const params = {
        productId: currentProductId.value,
        inspectType: 2
      };
      Promise.all([
        modelList({ id: currentProductId.value }),
        qualityInspectDetailByProductId(params)
      ]).then(([modelRes, testStandardRes]) => {
        // 设置规格型号选项
        modelOptions.value = modelRes || [];
        // 如果表单中已有 productModelId,设置对应的 model 和 unit
        if (form.value.productModelId && modelOptions.value.length > 0) {
          const selectedModel = modelOptions.value.find(item => item.id == form.value.productModelId);
          if (selectedModel) {
            form.value.model = selectedModel.model || '';
            form.value.unit = selectedModel.unit || '';
            form.value.uidNo = selectedModel.uidNo || '';
          }
        }
        // 设置指标选项
        testStandardOptions.value = testStandardRes.data || [];
        // 设置 testStandardId 并加载参数列表
        nextTick(() => {
          if (savedTestStandardId) {
            // 确保类型匹配(item.id 可能是数字或字符串)
            const matchedOption = testStandardOptions.value.find(item =>
              item.id == savedTestStandardId || String(item.id) === String(savedTestStandardId)
            );
            if (matchedOption) {
              // 确保使用匹配项的 id(保持类型一致)
              form.value.testStandardId = matchedOption.id;
            } else {
              // 如果找不到匹配项,尝试直接使用原值
              console.warn('未找到匹配的指标选项,testStandardId:', savedTestStandardId, '可用选项:', testStandardOptions.value);
              form.value.testStandardId = savedTestStandardId;
            }
          }
          // 编辑场景保留已有检验值,直接拉取原参数数据
          getQualityInspectParamList(row.id);
        });
      });
    } else {
      getQualityInspectParamList(row.id);
    }
  }
}
const getProductOptions = () => {
  productTreeList().then((res) => {
  return productTreeList().then((res) => {
    productOptions.value = convertIdToValue(res);
  });
};
const getModels = (value) => {
  form.value.productModelId = undefined;
  form.value.unit = undefined;
  form.value.uidNo = undefined;
  form.value.batchNo = "";
  modelOptions.value = [];
  currentProductId.value = value
  form.value.productName = findNodeById(productOptions.value, value);
@@ -279,6 +487,11 @@
const handleChangeModel = (value) => {
  form.value.model = modelOptions.value.find(item => item.id == value)?.model || '';
  form.value.unit = modelOptions.value.find(item => item.id == value)?.unit || '';
  form.value.uidNo = modelOptions.value.find(item => item.id == value)?.uidNo || '';
  // 选择规格型号后,如果已有生产日期则重新计算有效期
  if (form.value.productionDate) {
    calculateValidityDate();
  }
}
const findNodeById = (nodes, productId) => {
@@ -372,9 +585,66 @@
}
const getQualityInspectParamList = (id) => {
   qualityInspectParamInfo(id).then(res => {
      tableData.value = res.data;
      tableData.value = (res.data || []).map(item => ({...item}));
   })
}
// 计算有效期(生产日期 + 规格型号中的有效期)
const calculateValidityDate = async () => {
  if (!form.value.productionDate) {
    form.value.validityDate = '';
    return;
  }
  // 获取规格型号的有效期
  const selectedModel = modelOptions.value.find(item => item.id == form.value.productModelId);
  if (selectedModel && selectedModel.validityPeriod) {
    const productionDate = new Date(form.value.productionDate);
    const validityPeriod = parseFloat(selectedModel.validityPeriod);
    const validityDate = new Date(productionDate);
    validityDate.setFullYear(validityDate.getFullYear() + Math.floor(validityPeriod));
    validityDate.setMonth(validityDate.getMonth() + Math.round((validityPeriod % 1) * 12));
    form.value.validityDate = validityDate.toISOString().split('T')[0];
  }
};
// 获取设备台账列表
const loadDeviceList = () => {
   qualityInspectParamDeviceList().then(res => {
      deviceList.value = res.data || [];
   });
};
// 设备状态颜色映射
const getDeviceStatusType = (status) => {
   const map = {
      '正常': 'success',
      '运行': 'primary',
      '停机': 'warning',
      '维修': 'danger'
   };
   return map[status] || 'info';
};
// 检测器具变化时,自动填充设备状态
const handleInstrumentChange = (row) => {
   if (row.instrument === '目测') {
      row.deviceId = null;
      row.deviceName = '目测';
      row.deviceStatus = '';
      return;
   }
   const device = deviceList.value.find(d => d.deviceName === row.instrument);
   if (device) {
      row.deviceId = device.id;
      row.deviceName = device.deviceName;
      row.deviceStatus = device.status || '';
   } else {
      row.deviceId = null;
      row.deviceName = row.instrument || '';
      row.deviceStatus = '';
   }
};
// 关闭弹框
const closeDia = () => {
  proxy.resetForm("formRef");