<template>
  <el-dialog
    v-model="dialogVisible"
    title="成品详情"
    width="800px"
    append-to-body
    destroy-on-close
  >
    <el-card shadow="never" header="领料信息" v-loading="materialLoading" v-if="qualityData?.workOrderCode">
      <el-empty v-if="!materialLoading && !materialData.items?.length" description="未找到领料数据" />
      <el-table v-else :data="materialData.items" border style="width: 100%" max-height="300">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="物料信息" min-width="240">
          <template #default="{ row }">
            <div class="text-13px text-gray-600">编码：{{ row.materialCode }}</div>
            <div class="text-13px">名称：{{ row.materialName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit" width="80" />
        <el-table-column label="计划数量" prop="planQuantity" width="120" />
        <el-table-column label="实际数量" prop="actualQuantity" width="120" />
        <el-table-column label="仓库" prop="warehouseName" width="140" />
        <el-table-column label="过磅单号" prop="no" width="160" />
        <el-table-column label="备注" prop="remark" min-width="160" />
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="过磅详情" placement="top" v-if="row.purchaseId">
              <el-button link type="primary" @click="openWeighDetail(row.purchaseId)">
                <Icon icon="ep:document" />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card shadow="never" header="质检信息" v-loading="loading">
      <el-empty v-if="!loading && !qualityData" description="未找到质检数据" />
      <el-descriptions v-else :column="2" border>
        <el-descriptions-item label="质检编号">{{ qualityData?.code || '-' }}</el-descriptions-item>
        <el-descriptions-item label="批次编号">{{ qualityData?.workOrderCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ qualityData?.productName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="产品编号">{{ qualityData?.productCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="质检状态">{{
            qualityData?.status === 0
              ? '待检'
              : qualityData?.status === 1
                ? '检验中'
                : qualityData?.status === 2
                  ? '已完成'
                  : '已入库'
          }}</el-descriptions-item>
        <el-descriptions-item label="是否合格">{{ qualityData?.qualified ? '合格' : '不合格' }}</el-descriptions-item>
        <el-descriptions-item label="质检员">{{ qualityData?.inspectorName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="质检时间">{{ qualityData?.inspectionTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ qualityData?.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template v-if="qualityData && isTomato(qualityData?.workOrderCode)">
        <el-divider>番茄酱（番茄）附加检验</el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工艺">{{
              tomatoExtra.process === 'HOT' || tomatoExtra.process === '热破'
                ? '热破'
                : tomatoExtra.process === 'COLD' || tomatoExtra.process === '冷破'
                  ? '冷破'
                  : tomatoExtra.process || '-'
            }}</el-descriptions-item>
          <el-descriptions-item label="浓度(%)">{{ tomatoExtra.concentration ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="数量">{{ tomatoExtra.quantity ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="重量(kg)">{{ tomatoExtra.weight ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="感官" :span="2">{{ tomatoExtra.sensory || '-' }}</el-descriptions-item>
          <el-descriptions-item label="可溶性固形物(%)">{{ tomatoExtra.solubleSolidsPercent ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="粘稠度(cm/30s)">{{ tomatoExtra.viscosityCmPer30s ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="番茄红素(mg/100g)">{{ tomatoExtra.lycopeneMgPer100g ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="总酸(%)">{{ tomatoExtra.totalAcidPercent ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="PH 值">{{ tomatoExtra.pHValue ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="色差 a/b">{{ tomatoExtra.colorDifferenceAB ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="霉菌(%)">{{ tomatoExtra.mouldPositivePercent ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="评定">{{
              tomatoExtra.assessConformance === 1
                ? '品质符合'
                : tomatoExtra.assessConformance === 0
                  ? '品质不符合'
                  : '-'
            }}</el-descriptions-item>
          <el-descriptions-item label="评定说明" :span="2">{{ tomatoExtra.assessRemark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </template>
      <template v-else-if="qualityData && isStevia(qualityData?.workOrderCode)">
        <el-divider>甜菊糖（甜叶菊）附加检验</el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="标签" :span="2">{{ steviaExtra.label || '-' }}</el-descriptions-item>
          <el-descriptions-item label="色泽">{{ steviaExtra.color || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ steviaExtra.state || '-' }}</el-descriptions-item>
          <el-descriptions-item label="甜菊糖苷含量(%)">{{ steviaExtra.glycosidesPercent ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="灰分(%)">{{ steviaExtra.ashPercent ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="干燥减重(%)">{{ steviaExtra.lossOnDryingPercent ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="甲醇(mg/kg)">{{ steviaExtra.methanolMgPerKg ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="乙醇(mg/kg)">{{ steviaExtra.ethanolMgPerKg ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="铅(mg/kg)">{{ steviaExtra.leadMgPerKg ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="总砷(mg/kg)">{{ steviaExtra.totalArsenicMgPerKg ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="PH 值">{{ steviaExtra.pHValue ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="RD">{{ steviaExtra.rd ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="RA">{{ steviaExtra.ra ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="STV">{{ steviaExtra.stv ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="RF">{{ steviaExtra.rf ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="RC">{{ steviaExtra.rc ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="DA">{{ steviaExtra.da ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="RV">{{ steviaExtra.rv ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="RB">{{ steviaExtra.rb ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="SB">{{ steviaExtra.sb ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="水分(%)">{{ steviaExtra.moisture ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="比吸光">{{ steviaExtra.specificAbsorbance ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="透光率(%)">{{ steviaExtra.transmittance ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="产量(kg)">{{ steviaExtra.yield ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ steviaExtra.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-card>

    <!-- 添加销售出库单信息 -->
    <el-card shadow="never" header="销售出库单信息" v-loading="saleOutwarehouseLoading">
      <el-empty v-if="!saleOutwarehouseLoading && !saleOutwarehouseData" description="未找到销售出库单数据" />
      <template v-else>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="出库单号">{{ saleOutwarehouseData?.no || '-' }}</el-descriptions-item>
          <el-descriptions-item label="出库时间">{{ saleOutwarehouseData?.outTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="客户">{{ saleOutwarehouseData?.customerName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="仓库">{{ saleOutwarehouseData?.warehouseNames || '-' }}</el-descriptions-item>
          <el-descriptions-item label="应收金额">{{ formatPrice(saleOutwarehouseData?.totalPrice) }}</el-descriptions-item>
          <el-descriptions-item label="收款状态">
            <dict-tag :type="DICT_TYPE.ERP_RECEIPT_STATUS" :value="saleOutwarehouseData?.receiptStatus || 0" />
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ saleOutwarehouseData?.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>出库产品明细</el-divider>
        <el-table :data="saleOutwarehouseData?.items || []" border style="width: 100%" max-height="300">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="产品信息" min-width="240">
            <template #default="{ row }">
              <div class="text-13px text-gray-600">名称：{{ row.productName }}</div>
              <div class="text-13px">条码：{{ row.productBarCode || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="productUnitName" width="80" />
          <el-table-column label="数量" prop="count" width="100" />
          <el-table-column label="单价" width="120">
            <template #default="{ row }">
              {{ formatPrice(row.productPrice) }}
            </template>
          </el-table-column>
          <el-table-column label="金额" width="120">
            <template #default="{ row }">
              {{ formatPrice(row.totalPrice) }}
            </template>
          </el-table-column>
          <el-table-column label="仓库" prop="warehouseName" width="140" />
          <el-table-column label="备注" prop="remark" min-width="160" />
        </el-table>
      </template>
    </el-card>

    <!-- 过磅单详情弹窗 -->
    <el-dialog
      v-model="weighDialogVisible"
      title="过磅单详情"
      width="50%"
      append-to-body
      destroy-on-close
    >
      <h3 class="form-section-title">基本信息</h3>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="过磅单号">{{ weighDetail?.no || '-' }}</el-descriptions-item>
        <el-descriptions-item label="入库状态">{{
            weighDetail?.inStatus === 1 ? '已入库' : '未入库'
          }}</el-descriptions-item>
        <el-descriptions-item label="产品">{{
            weighDetail?.productName || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="车牌">{{
            weighDetail?.vehicleNumber || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="毛重">{{
            weighDetail?.grossWeight != null ? weighDetail.grossWeight + ' kg' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="皮重">{{
            weighDetail?.tareWeight != null ? weighDetail.tareWeight + ' kg' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="净重">{{
            weighDetail?.netWeight != null ? weighDetail.netWeight + ' kg' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="计划重量">{{
            weighDetail?.plannedWeight != null ? weighDetail.plannedWeight + ' kg' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="杂质率">{{
            weighDetail?.impurityRate != null ? (weighDetail.impurityRate).toFixed(2) + '%' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="供应商">{{
            weighDetail?.supplierName || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="供应商类型">{{
            weighDetail?.supplierName2 || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{
            weighDetail?.idCardNumber || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="司机">{{ weighDetail?.driver || '-' }}</el-descriptions-item>
        <el-descriptions-item label="管理员">{{
            weighDetail?.administrator || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="过磅员">{{ weighDetail?.weigher || '-' }}</el-descriptions-item>
        <el-descriptions-item label="产地证编号">{{
            weighDetail?.originCertificateNumber || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="附件">
          <template v-if="weighDetail?.fileUrl">
            <a :href="weighDetail.fileUrl" target="_blank">查看附件</a>
          </template>
          <template v-else>-</template>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{
            weighDetail?.remark || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{
            weighDetail?.createTime ? formatDate(weighDetail.createTime) : '-'
          }}</el-descriptions-item>
      </el-descriptions>

      <!-- 新增检验信息部分 -->
      <h3 class="form-section-title">检验信息</h3>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="取样日期">{{
            weighDetail?.sampleDate ? formatDate(weighDetail.sampleDate) : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="取样地点">{{
            weighDetail?.sampleLocation || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="代表重量">{{
            weighDetail?.representativeWeight != null ? weighDetail.representativeWeight + ' kg' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="样品重量">{{
            weighDetail?.sampleWeight != null ? weighDetail.sampleWeight + ' kg' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="杂质重量">{{
            weighDetail?.impurityWeight != null ? weighDetail.impurityWeight + ' kg' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="沙土重量">{{
            weighDetail?.sandWeight != null ? weighDetail.sandWeight + ' kg' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="感官">{{
            weighDetail?.sensoryEvaluation || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="合格率">{{
            weighDetail?.qualificationRate ? weighDetail.qualificationRate + '%' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="水分">{{
            weighDetail?.moistureContent ? weighDetail.moistureContent + '%' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="含糖">{{
            weighDetail?.sugarContent ? weighDetail.sugarContent + '%' : '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="RA值">{{
            weighDetail?.raValue || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="STV值">{{
            weighDetail?.stvValue || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="化验员">{{
            weighDetail?.labTechnician || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="检验备注" :span="2">{{
            weighDetail?.inspectionRemark || '-'
          }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getFinishedProductQuality } from '@/api/mes/quality/productquality/index'
import { StockRecordApi } from '@/api/erp/stock/record'
import { getMaterialRequisition, getMaterialRequisitionPage } from '@/api/mes/production/material-requisition'
import { formatDate } from '@/utils/formatTime'
import { Icon } from '@/components/Icon'
import { WeighApi } from '@/api/erp/purchase/weigh'
import { SaleOutwarehouseApi, SaleOutwarehouseVO } from '@/api/erp/sale/outwarehouse'
import { erpPriceInputFormatter } from '@/utils'
import { DICT_TYPE } from '@/utils/dict'

const props = defineProps({
  qualityId: {
    type: [Number, String],
    default: undefined
  },
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible'])

// 对话框可见性
const dialogVisible = ref(false)

// 监听外部visible变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
})

// 监听内部dialogVisible变化
watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val)
})

// 质检数据
const qualityData = ref<any>(null)
const loading = ref(false)

// 附加信息
const steviaExtra = ref<any>({})
const tomatoExtra = ref<any>({})

// 领料数据
const materialData = ref<any>({
  items: []
})
const materialLoading = ref(false)

// 过磅详情
const weighDialogVisible = ref(false)
const weighDetail = ref<any>(null)

// 销售出库单数据
const saleOutwarehouseData = ref<SaleOutwarehouseVO | null>(null)
const saleOutwarehouseLoading = ref(false)

// 格式化金额
const formatPrice = (price: number | undefined) => {
  if (price == null) return '-'
  return erpPriceInputFormatter(price.toString())
}

// 判断产品类型
const isTomato = (code?: string) => {
  const c = (code || '').toUpperCase()
  return c.startsWith('X8')
}
const isStevia = (code?: string) => {
  const c = (code || '').toUpperCase()
  return c.startsWith('X') && !c.startsWith('X8')
}

// 获取领料数据
const fetchMaterialData = async (workOrderCode: string) => {
  if (!workOrderCode) return

  materialLoading.value = true
  try {
    // 先通过工单编号查询对应的领料单ID
    const pageResult = await getMaterialRequisitionPage({
      pageNo: 1,
      pageSize: 10,
      orderCode: workOrderCode
    })

    if (pageResult && pageResult.list && pageResult.list.length > 0) {
      // 获取第一个领料单的ID
      const requisitionId = pageResult.list[0].id
      // 通过ID查询领料单详情
      const detailRes = await getMaterialRequisition(requisitionId)
      materialData.value = detailRes || { items: [] }
    } else {
      materialData.value = { items: [] }
    }
  } catch (error) {
    console.error('获取领料数据失败:', error)
    ElMessage.error('获取领料数据失败')
    materialData.value = { items: [] }
  } finally {
    materialLoading.value = false
  }
}

// 获取销售出库单数据
const fetchSaleOutwarehouseData = async (stockRecordId: number) => {
  if (!stockRecordId) return

  saleOutwarehouseLoading.value = true
  try {
    console.log('获取库存记录:', stockRecordId)

    // 先根据库存明细ID获取销售出库主表ID
    const outIdRes: any = await SaleOutwarehouseApi.getIdByStockRecordId(stockRecordId)
    const outId: number | null = outIdRes?.data ?? outIdRes ?? null

    if (!outId) {
      saleOutwarehouseData.value = null
      return
    }

    // 再根据主表ID获取销售出库单详情
    const detailRes: any = await SaleOutwarehouseApi.getSaleOutwarehouse(outId)
    const detail = detailRes?.data ?? detailRes ?? null

    if (detail) {
      // 兼容后端返回 itemList 的情况
      if (!detail.items && detail.itemList) {
        detail.items = detail.itemList
      }
      // 兜底计算仓库名称汇总
      if (!detail.warehouseNames && Array.isArray(detail.items)) {
        const names = Array.from(new Set((detail.items || []).map((i: any) => i?.warehouseName).filter((n: any) => !!n)))
        if (names.length) {
          detail.warehouseNames = names.join(',')
        }
      }
      saleOutwarehouseData.value = detail as SaleOutwarehouseVO
    } else {
      saleOutwarehouseData.value = null
    }
  } catch (error) {
    console.error('获取销售出库单数据失败:', error)
    ElMessage.error('获取销售出库单数据失败')
    saleOutwarehouseData.value = null
  } finally {
    saleOutwarehouseLoading.value = false
  }
}

// 打开过磅详情
const openWeighDetail = async (purchaseId: number) => {
  try {
    const res: any = await WeighApi.getWeigh(purchaseId)
    weighDetail.value = res?.data || res
    weighDialogVisible.value = true
  } catch (e) {
    console.error('获取过磅单详情失败', e)
    ElMessage.error('获取过磅单详情失败')
  }
}

// 获取质检数据
const fetchQualityData = async (id: number | string) => {
  if (!id) return

  loading.value = true
  try {
    // 转换id为数字类型，如果是字符串的话
    const numId = typeof id === 'string' ? parseInt(id) : id

    // 先获取库存记录详情，确定bizId是否为质检单ID
    try {
      const stockRecord = await StockRecordApi.getStockRecord(numId)
      // 如果是质检相关的业务类型，使用bizId查询质检单
      if (stockRecord && stockRecord.bizId) {
        const qualityId = stockRecord.bizId
        const res = await getFinishedProductQuality(qualityId)
        if (res) {
          qualityData.value = res

          // 提取番茄附加信息（直接从顶层字段提取）
          tomatoExtra.value = {
            process: res.tomatoProcess,
            concentration: res.tomatoConcentration,
            quantity: res.tomatoQuantity,
            weight: res.weight,
            sensory: res.tomatoSensory,
            solubleSolidsPercent: res.tomatoSolubleSolidsPercent,
            viscosityCmPer30s: res.tomatoViscosityCmPer,
            lycopeneMgPer100g: res.tomatoLycopeneMgPer,
            totalAcidPercent: res.tomatoTotalAcidPercent,
            pHValue: res.tomatoPhValue,
            colorDifferenceAB: res.tomatoColorDifference,
            mouldPositivePercent: res.tomatoMouldPositivePercent,
            assessConformance: res.tomatoAssessConformance,
            assessRemark: res.tomatoAssessRemark
          }

          // 提取甜菊糖附加信息（直接从顶层字段提取）
          steviaExtra.value = {
            label: res.steviaLabel,
            color: res.steviaColor,
            state: res.steviaState,
            glycosidesPercent: res.steviaGlycosidesPercent,
            ashPercent: res.steviaAshPercent,
            lossOnDryingPercent: res.steviaLossOnDryingPercent,
            methanolMgPerKg: res.steviaMethanolMgPerKg,
            ethanolMgPerKg: res.steviaEthanolMgPerKg,
            leadMgPerKg: res.steviaLeadMgPerKg,
            totalArsenicMgPerKg: res.steviaTotalArsenicMgPerKg,
            pHValue: res.steviaPhValue,
            rd: res.steviaRd,
            ra: res.steviaRa,
            stv: res.steviaStv,
            rf: res.steviaRf,
            rc: res.steviaRc,
            da: res.steviaDa,
            rv: res.steviaRv,
            rb: res.steviaRb,
            sb: res.steviaSb,
            moisture: res.steviaMoisture,
            specificAbsorbance: res.steviaSpecificAbsorbance,
            transmittance: res.steviaTransmittance,
            yield: res.steviaYield,
            remark: res.steviaRemark
          }

          // 获取领料数据
          if (res.workOrderCode) {
            fetchMaterialData(res.workOrderCode)
          }

          // 获取销售出库单数据
          fetchSaleOutwarehouseData(numId)
          return
        }
      }
    } catch (e) {
      console.error('获取库存记录失败，尝试直接查询质检单:', e)
    }

    // 如果上面的逻辑失败，尝试直接使用ID查询质检单
    const res = await getFinishedProductQuality(numId)
    if (res) {
      qualityData.value = res

      // 提取番茄附加信息（直接从顶层字段提取）
      tomatoExtra.value = {
        process: res.tomatoProcess,
        concentration: res.tomatoConcentration,
        quantity: res.tomatoQuantity,
        weight: res.weight,
        sensory: res.tomatoSensory,
        solubleSolidsPercent: res.tomatoSolubleSolidsPercent,
        viscosityCmPer30s: res.tomatoViscosityCmPer,
        lycopeneMgPer100g: res.tomatoLycopeneMgPer,
        totalAcidPercent: res.tomatoTotalAcidPercent,
        pHValue: res.tomatoPhValue,
        colorDifferenceAB: res.tomatoColorDifference,
        mouldPositivePercent: res.tomatoMouldPositivePercent,
        assessConformance: res.tomatoAssessConformance,
        assessRemark: res.tomatoAssessRemark
      }

      // 提取甜菊糖附加信息（直接从顶层字段提取）
      steviaExtra.value = {
        label: res.steviaLabel,
        color: res.steviaColor,
        state: res.steviaState,
        glycosidesPercent: res.steviaGlycosidesPercent,
        ashPercent: res.steviaAshPercent,
        lossOnDryingPercent: res.steviaLossOnDryingPercent,
        methanolMgPerKg: res.steviaMethanolMgPerKg,
        ethanolMgPerKg: res.steviaEthanolMgPerKg,
        leadMgPerKg: res.steviaLeadMgPerKg,
        totalArsenicMgPerKg: res.steviaTotalArsenicMgPerKg,
        pHValue: res.steviaPhValue,
        rd: res.steviaRd,
        ra: res.steviaRa,
        stv: res.steviaStv,
        rf: res.steviaRf,
        rc: res.steviaRc,
        da: res.steviaDa,
        rv: res.steviaRv,
        rb: res.steviaRb,
        sb: res.steviaSb,
        moisture: res.steviaMoisture,
        specificAbsorbance: res.steviaSpecificAbsorbance,
        transmittance: res.steviaTransmittance,
        yield: res.steviaYield,
        remark: res.steviaRemark
      }

      // 获取领料数据
      if (res.workOrderCode) {
        fetchMaterialData(res.workOrderCode)
      }

      // 获取销售出库单数据
      fetchSaleOutwarehouseData(numId)
    }
  } catch (error) {
    console.error('获取质检数据失败:', error)
    ElMessage.error('获取质检数据失败')
    qualityData.value = null
  } finally {
    loading.value = false
  }
}

// 监听ID变化
watch(() => props.qualityId, (newVal) => {
  if (newVal) {
    fetchQualityData(newVal)
  } else {
    qualityData.value = null
    saleOutwarehouseData.value = null
  }
}, { immediate: true })

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal && props.qualityId) {
    fetchQualityData(props.qualityId)
  }
})

onMounted(() => {
  if (props.qualityId) {
    fetchQualityData(props.qualityId)
  }
})
</script>

<style scoped>
.form-section-title {
  margin: 15px 0;
  padding-left: 10px;
  border-left: 3px solid #409eff;
  font-size: 16px;
  color: #606266;
}
</style>
