<template>
  <Dialog title="查看领料单" v-model="dialogVisible" width="80%">
    <Descriptions :schema="schema" :data="detailData" />

    <el-divider content-position="left">领料明细</el-divider>
    <el-table :data="detailData.items" border style="width: 100%" max-height="480">
      <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>

    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </Dialog>

  <!-- 过磅单详情弹窗 -->
  <Dialog title="过磅单详情" v-model="weighDialogVisible" width="50%">
    <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 * 100).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>

    <!-- 检验信息部分 - 仅当有检验数据时显示 -->
    <template v-if="hasInspectionData">
      <el-divider content-position="left">检验信息</el-divider>
      <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>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { getMaterialRequisition } from '@/api/mes/production/material-requisition'
import { formatDate } from '@/utils/formatTime'
import { Icon } from '@/components/Icon'
import { WeighApi } from '@/api/erp/purchase/weigh'

const dialogVisible = ref(false)
const detailData = ref<any>({
  items: []
})

const weighDialogVisible = ref(false)
const weighDetail = ref<any>(null)

// 判断是否有检验数据
const hasInspectionData = computed(() => {
  if (!weighDetail.value) return false
  return !!(
    weighDetail.value.sampleDate ||
    weighDetail.value.sampleLocation ||
    weighDetail.value.representativeWeight ||
    weighDetail.value.sampleWeight ||
    weighDetail.value.impurityWeight ||
    weighDetail.value.sandWeight ||
    weighDetail.value.sensoryEvaluation ||
    weighDetail.value.qualificationRate ||
    weighDetail.value.moistureContent ||
    weighDetail.value.sugarContent ||
    weighDetail.value.raValue ||
    weighDetail.value.stvValue ||
    weighDetail.value.labTechnician ||
    weighDetail.value.inspectionRemark
  )
})

const schema = [
  {
    label: '领料单号',
    field: 'code'
  },
  {
    label: '工单编号',
    field: 'orderCode'
  },
  {
    label: '领料时间',
    field: 'requisitionTime',
    formatter: (val: string) => (val ? formatDate(val) : '')
  },
  {
    label: '状态',
    field: 'status',
    formatter: (val: number) => {
      const statusMap: Record<number, string> = {
        0: '草稿',
        1: '待审核',
        2: '已审核',
        3: '已领料',
        4: '已取消'
      }
      return statusMap[val] || '未知'
    }
  },
  {
    label: '申请人',
    field: 'applicantName'
  },
  {
    label: '审批人',
    field: 'approverName'
  },
  {
    label: '备注',
    field: 'remark'
  },
  {
    label: '创建时间',
    field: 'createTime',
    formatter: (val: string) => (val ? formatDate(val) : '')
  }
]

const open = async (id: number) => {
  dialogVisible.value = true
  const res = await getMaterialRequisition(id)
  detailData.value = res
}

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)
  }
}

defineExpose({
  open
})
</script>
