<script setup>
import { computed, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getCurrentRole } from '../utils/auth'
import ExcelImportDialog from '../components/ExcelImportDialog.vue'

const selectedCategory = ref('整机')
const selectedEntryAssetId = ref(null)
const selectedProductId = ref(null)
const entryMode = ref('both')
const assets = ref([])
const entryFormMetrics = ref([])
const assetProducts = ref([])
const productMetricConfigs = ref([])
const formData = ref({})
const processFormData = ref({})
const processBatchNo = ref('')
const processQuantity = ref(undefined)
const processRemark = ref('')

const formatNow = () => {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:00`
}
const selectedDate = ref(formatNow())
const currentRole = getCurrentRole()
const canSubmitRecord = true

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 isProcessMetric = (metric) => metric.category_level_1 === '加工精度' || metric.category_level_1 === '互换性指标'

const filteredAssets = computed(() => assets.value.filter((asset) => asset.asset_category === selectedCategory.value))
const trackMetrics = computed(() => entryFormMetrics.value.filter((metric) => !isProcessMetric(metric)))
const hasTrackMetrics = computed(() => trackMetrics.value.length > 0)
const hasProcessMetrics = computed(() => selectedCategory.value === '整机' && assetProducts.value.length > 0)
const showTrackEntry = computed(() => selectedEntryAssetId.value && hasTrackMetrics.value && ['track', 'both'].includes(entryMode.value))
const showProcessEntry = computed(() => selectedEntryAssetId.value && hasProcessMetrics.value && ['process', 'both'].includes(entryMode.value))
const selectedModeHasNoData = computed(() => {
  if (!selectedEntryAssetId.value) return false
  if (entryMode.value === 'track') return !hasTrackMetrics.value
  if (entryMode.value === 'process') return !hasProcessMetrics.value
  return !hasTrackMetrics.value && !hasProcessMetrics.value
})

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

const resetProcessState = () => {
  selectedProductId.value = null
  assetProducts.value = []
  productMetricConfigs.value = []
  processFormData.value = {}
  processBatchNo.value = ''
  processQuantity.value = undefined
  processRemark.value = ''
}

const handleCategoryChange = () => {
  selectedEntryAssetId.value = null
  entryMode.value = selectedCategory.value === '整机' ? 'both' : 'track'
  entryFormMetrics.value = []
  formData.value = {}
  resetProcessState()
}

const initTrackForm = () => {
  const initData = {}
  trackMetrics.value.forEach((metric) => {
    initData[metric.metric_id] = { val: undefined, samples: '' }
  })
  formData.value = initData
}

const loadProductConfigs = async (productId) => {
  if (!productId) {
    productMetricConfigs.value = []
    processFormData.value = {}
    return
  }
  const data = await fetchJson(`/api/products/${productId}/metric-configs`)
  productMetricConfigs.value = data.data || []
  const nextForm = {}
  productMetricConfigs.value.forEach((metric) => {
    nextForm[metric.metric_id] = ''
  })
  processFormData.value = nextForm
}

const handleEntryAssetChange = async (aid) => {
  const [metricData, productData] = await Promise.all([
    fetchJson(`/api/assets/${aid}/metrics/detail`),
    selectedCategory.value === '整机' ? fetchJson(`/api/assets/${aid}/products`) : Promise.resolve({ data: [] }),
  ])
  entryFormMetrics.value = metricData.data || []
  initTrackForm()
  assetProducts.value = productData.data || []
  if (assetProducts.value.length) {
    selectedProductId.value = assetProducts.value[0].product_id
    await loadProductConfigs(selectedProductId.value)
  } else {
    resetProcessState()
  }
}

const submitTrackRecord = async () => {
  if (!selectedDate.value) return ElMessage.warning('请选择测定发生的时间')
  if (!trackMetrics.value.length) return ElMessage.warning('当前对象没有几何/位置精度指标')

  const records = []
  for (const metric of trackMetrics.value) {
    const input = formData.value[metric.metric_id]
    if (!input) continue
    if (metric.value_type === '单值') {
      if (input.val === undefined || input.val === null) return ElMessage.warning(`请填写“${metric.metric_name}”`)
      records.push({ metric_id: metric.metric_id, raw_data: { val: input.val } })
    } else {
      if (!input.samples) return ElMessage.warning(`请填写“${metric.metric_name}”`)
      const arr = input.samples
        .split(/[,，\s\n]+/)
        .filter((s) => s.trim() !== '')
        .map(Number)
      if (arr.some(Number.isNaN)) return ElMessage.warning(`“${metric.metric_name}”包含非数字格式`)
      records.push({ metric_id: metric.metric_id, raw_data: { samples: arr } })
    }
  }

  await fetchJson('/api/records', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      asset_id: selectedEntryAssetId.value,
      record_date: selectedDate.value,
      records,
    }),
  })

  ElMessage.success('几何/位置精度记录已归档')
  await handleEntryAssetChange(selectedEntryAssetId.value)
}

const submitProcessRecord = async () => {
  if (!selectedDate.value) return ElMessage.warning('请选择测定发生的时间')
  if (!selectedProductId.value) return ElMessage.warning('请先选择加工产品')
  if (!processBatchNo.value) return ElMessage.warning('请填写生产批次号')
  if (!productMetricConfigs.value.length) return ElMessage.warning('该产品尚未配置加工精度指标')

  const metricSamples = []
  for (const metric of productMetricConfigs.value) {
    const raw = processFormData.value[metric.metric_id]
    if (!raw) return ElMessage.warning(`请填写“${metric.metric_name}”的样本值`)
    const values = raw
      .split(/[,，\s\n]+/)
      .filter((s) => s.trim() !== '')
      .map(Number)
    if (values.length < 2) return ElMessage.warning(`“${metric.metric_name}”至少需要 2 个样本值`)
    if (values.some(Number.isNaN)) return ElMessage.warning(`“${metric.metric_name}”包含非数字格式`)
    metricSamples.push({ metric_id: metric.metric_id, values })
  }

  await fetchJson('/api/product-records', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      asset_id: selectedEntryAssetId.value,
      product_id: selectedProductId.value,
      batch_no: processBatchNo.value,
      record_date: selectedDate.value,
      production_quantity: processQuantity.value || null,
      remark: processRemark.value || '',
      metric_samples: metricSamples,
    }),
  })

  ElMessage.success('加工制品批次记录已归档')
  await loadProductConfigs(selectedProductId.value)
  processBatchNo.value = ''
  processQuantity.value = undefined
  processRemark.value = ''
}

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

<template>
  <div>
    <div style="margin-bottom: 20px">
      <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="selectedEntryAssetId"
	          placeholder="步骤2：选择被测对象"
	          style="width: 300px"
	          @change="handleEntryAssetChange"
        >
          <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="entryMode"
	          placeholder="步骤3：选择录入内容"
	          style="width: 260px"
	          :disabled="!selectedEntryAssetId"
	        >
	          <el-option label="几何/位置精度" value="track" />
	          <el-option label="制品批次" value="process" :disabled="selectedCategory !== '整机'" />
	          <el-option label="几何/位置 + 制品批次" value="both" :disabled="selectedCategory !== '整机'" />
	        </el-select>
	        <ExcelImportDialog title="几何/位置精度记录" scope-key="精度测量记录" @success="loadAssets" />
	        <ExcelImportDialog v-if="selectedCategory === '整机'" title="制品测量记录" scope-key="制品测量记录" @success="loadAssets" />
	      </div>
	    </div>
	
	    <el-card v-if="showTrackEntry" shadow="never" style="margin-bottom: 20px">
      <template #header>
        <div style="font-weight: 600">几何/位置精度测定录入</div>
      </template>
      <el-form label-width="180px" label-position="left">
        <el-form-item label="测定时间 (支持历史补录)" style="margin-bottom: 30px; border-bottom: 1px dashed #eee; padding-bottom: 20px">
          <el-date-picker
            v-model="selectedDate"
            type="datetime"
            placeholder="请选择测定记录发生的真实时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%; max-width: 450px"
          />
        </el-form-item>

        <el-form-item v-for="metric in trackMetrics" :key="metric.metric_id" :label="metric.metric_name">
          <template #label>
            <div style="line-height: 1.2">
              <div>{{ metric.metric_name }}</div>
              <div style="font-size: 12px; color: #999">{{ metric.category_level_1 }}</div>
            </div>
          </template>
          <div style="width: 100%; max-width: 450px">
            <el-input-number
              v-if="metric.value_type === '单值'"
              v-model="formData[metric.metric_id].val"
              :precision="4"
              :step="0.001"
              style="width: 100%"
            />
            <el-input
              v-else
              v-model="formData[metric.metric_id].samples"
              type="textarea"
              :rows="2"
              placeholder="输入抽样数组，空格或逗号分隔"
            />
          </div>
        </el-form-item>

        <el-form-item style="margin-top: 30px">
          <el-button type="primary" size="large" :disabled="!canSubmitRecord" @click="submitTrackRecord">提交几何/位置记录</el-button>
        </el-form-item>
      </el-form>
    </el-card>

	    <el-card v-if="showProcessEntry" shadow="never">
      <template #header>
        <div style="font-weight: 600">加工精度制品批次录入</div>
      </template>
      <el-form label-width="180px" label-position="left">
        <el-form-item label="生产批次测定时间">
          <el-date-picker
            v-model="selectedDate"
            type="datetime"
            placeholder="请选择批次测定时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%; max-width: 450px"
          />
        </el-form-item>
        <el-form-item label="加工产品">
          <el-select v-model="selectedProductId" style="width: 100%; max-width: 450px" @change="loadProductConfigs">
            <el-option
              v-for="product in assetProducts"
              :key="product.product_id"
              :label="`${product.product_code} (${product.product_name})`"
              :value="product.product_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次号">
          <el-input v-model="processBatchNo" style="width: 100%; max-width: 450px" placeholder="例如 VC-20260612-01" />
        </el-form-item>
        <el-form-item label="批次数量">
          <el-input-number v-model="processQuantity" :min="1" style="width: 100%; max-width: 250px" />
        </el-form-item>
        <el-form-item label="批次说明">
          <el-input v-model="processRemark" type="textarea" :rows="2" style="width: 100%; max-width: 450px" placeholder="工艺备注、班次说明等" />
        </el-form-item>

        <el-alert
          type="info"
          :closable="false"
          style="margin-bottom: 16px"
	          title="制品批次数据单独归档到制品样本记录，不会与几何/位置精度测定记录混存。"
        />

        <el-form-item v-for="metric in productMetricConfigs" :key="metric.metric_id" :label="metric.metric_name">
          <template #label>
            <div style="line-height: 1.2">
              <div>{{ metric.metric_name }}</div>
	              <div style="font-size: 12px; color: #999">
	                {{ metric.category_level_1 }} · 公差 {{ metric.lower_limit ?? '-' }} ~ {{ metric.upper_limit ?? '-' }} {{ metric.unit || '' }}
	              </div>
	              <div v-if="metric.position_note" style="font-size: 12px; color: #8a98ac">部位：{{ metric.position_note }}</div>
	            </div>
	          </template>
          <el-input
            v-model="processFormData[metric.metric_id]"
            type="textarea"
            :rows="2"
            style="width: 100%; max-width: 450px"
            placeholder="输入该批次样本值，空格或逗号分隔"
          />
        </el-form-item>

        <el-form-item style="margin-top: 30px">
          <el-button type="success" size="large" :disabled="!canSubmitRecord" @click="submitProcessRecord">提交加工批次记录</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-alert
      v-if="currentRole === 'user'"
      type="info"
      :closable="false"
      style="margin-top: 16px"
      title="当前为普通用户：可录入测试记录、查看详情与分析结果，但不能新增资产、修改资产配置或编辑历史数据。"
    />

    <el-empty v-if="!filteredAssets.length" description="当前类型下暂无测试对象，请先到设备台账新增整机或部件" />
    <el-empty v-else-if="!selectedEntryAssetId" description="请先选择类型和测试对象，再录入本次测定数据" />
	    <el-empty
	      v-else-if="selectedModeHasNoData"
	      description="当前选择的录入内容没有可录入数据。几何/位置精度需先绑定指标；制品批次需先在设备台账绑定制品并配置互换性指标。"
	    />
  </div>
</template>
