<script setup>
import { computed, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isAdmin as getIsAdmin } from '../utils/auth'

const selectedCategory = ref('整机')
const selectedAssetId = ref(null)
const assetList = ref([])
const recordList = ref([])
const productRecordList = ref([])
const selectedMetricFilter = ref('')
const detailsDialogVisible = ref(false)
const currentDetailsData = ref([])
const currentDetailsTitle = ref('')
const productDetailsDialogVisible = ref(false)
const currentProductDetails = ref([])
const currentProductDetailsTitle = ref('')
const productDetailsLoading = ref(false)
const isAdmin = getIsAdmin()

const fetchJson = async (url, options) => {
  const res = await fetch(url, options)
  const data = await res.json()
  if (!res.ok || data.status === 'error') throw new Error(data.message || '请求失败')
  return data
}

const filteredAssets = computed(() => assetList.value.filter((item) => item.asset_category === selectedCategory.value))

const availableMetrics = computed(() => {
  const metricsSet = new Set()
  recordList.value.forEach((r) => metricsSet.add(r.metric_name))
  return Array.from(metricsSet)
})

const filteredRecordList = computed(() => {
  if (!selectedMetricFilter.value) return recordList.value
  return recordList.value.filter((r) => r.metric_name === selectedMetricFilter.value)
})

const loadAssets = async () => {
  const data = await fetchJson('/api/assets')
  assetList.value = data.data || []
}

const handleCategoryChange = () => {
  selectedAssetId.value = null
  recordList.value = []
  productRecordList.value = []
  selectedMetricFilter.value = ''
}

const fetchRecords = async () => {
  if (!selectedAssetId.value) return
  selectedMetricFilter.value = ''
  const [recordsData, productData] = await Promise.all([
    fetchJson(`/api/records?asset_id=${selectedAssetId.value}`),
    selectedCategory.value === '整机'
      ? fetchJson(`/api/product-records?asset_id=${selectedAssetId.value}`)
      : Promise.resolve({ data: [] }),
  ])
  recordList.value = recordsData.data || []
  productRecordList.value = productData.data || []
}

const handleDelete = (row) => {
  if (!isAdmin) {
    ElMessage.warning('仅管理员可删除历史测试记录')
    return
  }
  ElMessageBox.confirm(`确定要删除这条【${row.metric_name}】的测试记录吗？`, '警告', { type: 'warning' })
    .then(async () => {
      await fetchJson(`/api/records/${row.record_id}`, { method: 'DELETE' })
      ElMessage.success('删除成功')
      fetchRecords()
    })
    .catch(() => {})
}

const openDetails = (row) => {
  currentDetailsTitle.value = `【${row.metric_name}】的完整抽样数据`
  currentDetailsData.value = row.raw_data.samples
  detailsDialogVisible.value = true
}

const openProductDetails = async (row) => {
  currentProductDetailsTitle.value = `【${row.product_name} / ${row.batch_no || '未填写批次'}】制品录入明细`
  currentProductDetails.value = []
  productDetailsDialogVisible.value = true
  productDetailsLoading.value = true
  try {
    const data = await fetchJson(`/api/product-records?asset_id=${row.asset_id}&product_id=${row.product_id}`)
    const freshRow = (data.data || []).find((item) => item.product_record_id === row.product_record_id)
    currentProductDetails.value = freshRow?.metric_samples || row.metric_samples || []
  } catch (error) {
    ElMessage.error(error.message || '制品明细读取失败')
    currentProductDetails.value = row.metric_samples || []
  } finally {
    productDetailsLoading.value = false
  }
}

const productMetricSummary = (row) => {
  const metrics = row.metric_samples || []
  if (!metrics.length) return '-'
  return metrics.map((item) => `${item.metric_name}（${item.samples?.length || 0}个）`).join('、')
}

const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间'
  const date = new Date(timeStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

onMounted(() => {
  loadAssets()
})
</script>

<template>
  <div>
    <div style="margin-bottom: 20px">
      <span style="font-weight: bold; font-size: 18px">测试记录数据管理</span>
      <div style="margin-top: 15px; display: flex; gap: 15px; flex-wrap: wrap">
        <el-select v-model="selectedCategory" placeholder="步骤1：选择类型" style="width: 220px" @change="handleCategoryChange">
          <el-option label="整机" value="整机" />
          <el-option label="部件" value="部件" />
        </el-select>

        <el-select v-model="selectedAssetId" placeholder="步骤2：选择测试对象" style="width: 300px" @change="fetchRecords">
          <el-option
            v-for="a in filteredAssets"
            :key="a.asset_id"
            :label="`${a.asset_code} (${a.asset_name})`"
            :value="a.asset_id"
          />
        </el-select>

        <el-select
          v-model="selectedMetricFilter"
          placeholder="步骤3：筛选具体指标 (可选)"
          style="width: 250px"
          clearable
          :disabled="!selectedAssetId"
        >
          <el-option v-for="m in availableMetrics" :key="m" :label="m" :value="m" />
        </el-select>
      </div>
    </div>

    <el-card v-if="selectedAssetId" shadow="never">
      <template #header>
        <div style="font-weight: 600">几何/位置精度测试记录</div>
      </template>
      <el-table :data="filteredRecordList" border stripe style="width: 100%">
        <el-table-column prop="record_id" label="记录ID" width="80" />

        <el-table-column prop="metric_name" label="测定指标" width="400">
          <template #default="scope">
            <span style="font-weight: bold">{{ scope.row.metric_name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="value_type" label="数据属性" width="120">
          <template #default="scope">
            <el-tag size="small" :type="scope.row.value_type === '单值' ? 'primary' : 'success'">
              {{ scope.row.value_type }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="测定数值">
          <template #default="scope">
            <span v-if="scope.row.raw_data.val !== undefined" style="color: #409eff; font-weight: bold; font-size: 16px">
              {{ scope.row.raw_data.val }}
            </span>
            <span v-else-if="scope.row.raw_data.samples">
              <el-button link type="primary" size="small" @click="openDetails(scope.row)">
                查看详情 (共 {{ scope.row.raw_data.samples.length }} 个数据)
              </el-button>
            </span>
            <span v-else>{{ scope.row.raw_data }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="unit" label="单位" width="90">
          <template #default="scope">{{ scope.row.unit || '-' }}</template>
        </el-table-column>

        <el-table-column prop="created_at" label="录入时间" width="200" sortable>
          <template #default="scope">{{ formatTime(scope.row.created_at) }}</template>
        </el-table-column>

        <el-table-column label="数据操作" width="100">
          <template #default="scope">
            <el-button type="danger" size="small" plain :disabled="!isAdmin" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="filteredRecordList.length === 0" description="未找到符合条件的测试记录" />
    </el-card>

    <el-card v-if="selectedAssetId && selectedCategory === '整机'" shadow="never" style="margin-top: 16px">
      <template #header>
        <div style="font-weight: 600">加工制品批次录入记录</div>
      </template>
      <el-table :data="productRecordList" border stripe style="width: 100%">
        <el-table-column prop="product_record_id" label="记录ID" width="90" />

        <el-table-column label="制品" min-width="220">
          <template #default="scope">
            <div style="font-weight: 600">{{ scope.row.product_name || '-' }}</div>
            <div style="font-size: 12px; color: #8a98ac">{{ scope.row.product_code || '-' }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="batch_no" label="生产批次号" min-width="170">
          <template #default="scope">{{ scope.row.batch_no || '-' }}</template>
        </el-table-column>

        <el-table-column prop="production_quantity" label="批次数量" width="110">
          <template #default="scope">{{ scope.row.production_quantity ?? '-' }}</template>
        </el-table-column>

        <el-table-column prop="sample_count" label="每项样本数" width="110">
          <template #default="scope">{{ scope.row.sample_count ?? '-' }}</template>
        </el-table-column>

        <el-table-column label="录入指标与样本" min-width="320">
          <template #default="scope">
            <span>{{ productMetricSummary(scope.row) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="录入时间" width="200" sortable>
          <template #default="scope">{{ formatTime(scope.row.created_at) }}</template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" min-width="160">
          <template #default="scope">{{ scope.row.remark || '-' }}</template>
        </el-table-column>

        <el-table-column label="数据详情" width="110" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="openProductDetails(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="productRecordList.length === 0" description="当前整机暂无加工制品批次录入记录" />
    </el-card>
    <el-empty v-if="!selectedAssetId" description="请在上方依次选择类型与测试对象以查看数据" />

    <el-dialog v-model="detailsDialogVisible" :title="currentDetailsTitle" width="500px">
      <div style="background-color: #f5f7fa; padding: 15px; border-radius: 4px">
        <div style="display: flex; flex-wrap: wrap; gap: 10px; max-height: 400px; overflow-y: auto">
          <el-tag
            v-for="(item, index) in currentDetailsData"
            :key="index"
            type="success"
            effect="plain"
            size="large"
            style="font-family: monospace; font-size: 14px"
          >
            <span style="color: #999; margin-right: 5px">#{{ index + 1 }}</span>
            <span style="font-weight: bold">{{ item }}</span>
          </el-tag>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="detailsDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="productDetailsDialogVisible"
      :title="currentProductDetailsTitle"
      width="860px"
      align-center
      append-to-body
      destroy-on-close
    >
      <div v-loading="productDetailsLoading" class="product-detail-dialog-body">
        <div v-if="currentProductDetails.length" style="display: grid; gap: 14px">
        <div
          v-for="metric in currentProductDetails"
          :key="metric.metric_id"
          class="product-detail-metric-card"
        >
          <div style="display: flex; justify-content: space-between; gap: 12px; margin-bottom: 12px">
            <span style="font-weight: 700">{{ metric.metric_name }}</span>
            <span style="color: #8a98ac">单位：{{ metric.unit || '-' }}</span>
          </div>
          <el-table :data="metric.samples || []" border size="small" style="width: 100%">
            <el-table-column prop="sample_no" label="样本序号" width="120" />
            <el-table-column label="测定值">
              <template #default="scope">
                <span style="font-weight: 700; color: #3269a8">{{ scope.row.value }}</span>
                <span style="margin-left: 6px; color: #8a98ac">{{ metric.unit || '' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
        <el-empty v-else-if="!productDetailsLoading" description="该批次暂无样本明细，请确认后端服务已重启并已写入制品样本值" />
      </div>
      <template #footer>
        <el-button type="primary" @click="productDetailsDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.product-detail-dialog-body {
  max-height: 58vh;
  min-height: 220px;
  overflow-y: auto;
  padding: 4px;
}

.product-detail-metric-card {
  padding: 16px;
  border: 1px solid rgba(119, 149, 188, 0.18);
  border-radius: 14px;
  background: linear-gradient(135deg, rgba(245, 249, 255, 0.96), rgba(255, 255, 255, 0.96));
}
</style>
