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

const activeConfigTab = ref('metrics')
const assets = ref([])
const metricList = ref([])
const productList = ref([])
const metricDialogVisible = ref(false)
const productDialogVisible = ref(false)
const productMetricDialogVisible = ref(false)
const isEditMetric = ref(false)
const isEditProduct = ref(false)
const currentMetricId = ref(null)
const currentProductId = ref(null)
const newMetric = ref({ category_level_1: '几何精度', category_level_2: '', metric_name: '', value_type: '单值', description: '' })
const newProduct = ref({ product_code: '', product_name: '', product_detail: '' })
const productMetricIds = ref([])
const productUpperLimits = ref({})
const productLowerLimits = ref({})
const productIdealValues = ref({})
const productExtremeValues = ref({})
const productUnits = ref({})
const productPositionNotes = ref({})
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 fetchAssets = async () => {
  const data = await fetchJson('/api/assets')
  assets.value = data.data || []
}

const fetchMetrics = async () => {
  const data = await fetchJson('/api/metrics')
  metricList.value = data.data || []
}

const fetchProducts = async () => {
  const data = await fetchJson('/api/products')
  productList.value = data.data || []
}

const accuracyMetrics = computed(() => metricList.value)

const ensureAdmin = () => {
  if (isAdmin) return true
  ElMessage.warning('仅管理员可维护精度指标和参数配置')
  return false
}

const handleAddMetric = (category = '几何精度') => {
  if (!ensureAdmin()) return
  isEditMetric.value = false
  newMetric.value = { category_level_1: category, category_level_2: '', metric_name: '', value_type: category === '加工精度' ? '抽样数组' : '单值', description: '' }
  metricDialogVisible.value = true
}

const handleEditMetric = (row) => {
  if (!ensureAdmin()) return
  isEditMetric.value = true
  currentMetricId.value = row.metric_id
  newMetric.value = { ...row }
  metricDialogVisible.value = true
}

const submitMetric = async () => {
  if (!ensureAdmin()) return
  if (!newMetric.value.category_level_2) return ElMessage.warning('二级精度类型不能为空')
  if (!newMetric.value.metric_name) return ElMessage.warning('具体指标名称不能为空')

  const url = isEditMetric.value ? `/api/metrics/${currentMetricId.value}` : '/api/metrics'
  const method = isEditMetric.value ? 'PUT' : 'POST'
  await fetchJson(url, {
    method,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(newMetric.value),
  })
  ElMessage.success('保存成功')
  metricDialogVisible.value = false
  fetchMetrics()
}

const handleDeleteMetric = (row) => {
  if (!ensureAdmin()) return
  ElMessageBox.confirm(`确定删除 "${row.metric_name}" 吗？`, '警告', { type: 'warning' })
    .then(async () => {
      await fetchJson(`/api/metrics/${row.metric_id}`, { method: 'DELETE' })
      ElMessage.success('删除成功')
      fetchMetrics()
    })
    .catch(() => {})
}

const processMetrics = computed(() => metricList.value.filter((item) => item.category_level_1 === '加工精度'))

const handleAddProduct = () => {
  if (!ensureAdmin()) return
  isEditProduct.value = false
  newProduct.value = { product_code: '', product_name: '', product_detail: '' }
  productDialogVisible.value = true
}

const handleEditProduct = (row) => {
  if (!ensureAdmin()) return
  isEditProduct.value = true
  currentProductId.value = row.product_id
  newProduct.value = {
    product_code: row.product_code,
    product_name: row.product_name,
    product_detail: row.product_detail || '',
  }
  productDialogVisible.value = true
}

const submitProduct = async () => {
  if (!ensureAdmin()) return
  if (!newProduct.value.product_code || !newProduct.value.product_name) return ElMessage.warning('产品编号和名称不能为空')

  const url = isEditProduct.value ? `/api/products/${currentProductId.value}` : '/api/products'
  const method = isEditProduct.value ? 'PUT' : 'POST'
  await fetchJson(url, {
    method,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(newProduct.value),
  })
  ElMessage.success('保存成功')
  productDialogVisible.value = false
  fetchProducts()
}

const handleDeleteProduct = (row) => {
  if (!ensureAdmin()) return
  ElMessageBox.confirm(`确定删除产品 "${row.product_name}" 吗？`, '警告', { type: 'warning' })
    .then(async () => {
      await fetchJson(`/api/products/${row.product_id}`, { method: 'DELETE' })
      ElMessage.success('删除成功')
      fetchProducts()
    })
    .catch(() => {})
}

const openProductMetricDialog = async (row) => {
  if (!ensureAdmin()) return
  currentProductId.value = row.product_id
  productMetricIds.value = []
  productUpperLimits.value = {}
  productLowerLimits.value = {}
  productIdealValues.value = {}
  productExtremeValues.value = {}
  productUnits.value = {}
  productPositionNotes.value = {}
  const data = await fetchJson(`/api/products/${row.product_id}/metric-configs`)
  ;(data.data || []).forEach((item) => {
    productMetricIds.value.push(item.metric_id)
    productUpperLimits.value[item.metric_id] = item.upper_limit
    productLowerLimits.value[item.metric_id] = item.lower_limit
    productIdealValues.value[item.metric_id] = item.ideal_value
    productExtremeValues.value[item.metric_id] = item.extreme_value
    productUnits.value[item.metric_id] = item.unit || ''
    productPositionNotes.value[item.metric_id] = item.position_note || ''
  })
  productMetricDialogVisible.value = true
}

const saveProductMetricConfigs = async () => {
  if (!ensureAdmin()) return
  await fetchJson(`/api/products/${currentProductId.value}/metric-configs`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      metrics: productMetricIds.value.map((id) => ({
        metric_id: id,
        upper_limit: productUpperLimits.value[id] !== '' && productUpperLimits.value[id] !== undefined ? Number(productUpperLimits.value[id]) : null,
        lower_limit: productLowerLimits.value[id] !== '' && productLowerLimits.value[id] !== undefined ? Number(productLowerLimits.value[id]) : null,
        ideal_value: null,
        extreme_value: null,
        unit: productUnits.value[id] || '',
        position_note: productPositionNotes.value[id] || '',
      })),
    }),
  })
  ElMessage.success('加工指标配置已保存')
  productMetricDialogVisible.value = false
}

onMounted(() => {
  fetchAssets()
  fetchMetrics()
  fetchProducts()
})
</script>

<template>
  <div>
    <el-tabs v-model="activeConfigTab">
      <el-tab-pane label="精度指标设置" name="metrics">
        <div class="toolbar">
          <el-button type="success" :disabled="!isAdmin" @click="handleAddMetric">+ 新建精度指标</el-button>
          <ExcelImportDialog title="精度指标" scope-key="精度指标" @success="fetchMetrics" />
        </div>
        <el-table :data="accuracyMetrics" border style="width: 100%">
          <el-table-column prop="category_level_1" label="一级分类" width="150" />
          <el-table-column prop="category_level_2" label="二级类型" width="180">
            <template #default="scope">
              <el-tag type="info">{{ scope.row.category_level_2 || '未分类' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="metric_name" label="具体指标名称" />
          <el-table-column prop="value_type" label="录入方式" width="120" />
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" type="primary" plain :disabled="!isAdmin" @click="handleEditMetric(scope.row)">修改</el-button>
              <el-button size="small" type="danger" plain :disabled="!isAdmin" @click="handleDeleteMetric(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="!accuracyMetrics.length" description="暂无精度指标，请先新建精度指标，再回到设备台账绑定到对象" />
      </el-tab-pane>

      <el-tab-pane label="加工制品设置" name="products">
        <div class="toolbar">
          <el-button type="success" :disabled="!isAdmin" @click="handleAddProduct">+ 新建产品</el-button>
          <ExcelImportDialog title="制品与加工指标" scope-key="制品配置" @success="fetchProducts" />
        </div>
        <el-table :data="productList" border style="width: 100%">
          <el-table-column prop="product_code" label="产品编号" width="140" />
          <el-table-column prop="product_name" label="产品名称" min-width="180" />
          <el-table-column prop="product_detail" label="产品说明" min-width="220" show-overflow-tooltip />
          <el-table-column prop="asset_count" label="已绑定设备数" width="120" />
          <el-table-column prop="record_count" label="批次记录数" width="120" />
          <el-table-column label="操作" width="240">
            <template #default="scope">
              <el-button size="small" type="success" plain :disabled="!isAdmin" @click="openProductMetricDialog(scope.row)">加工指标</el-button>
              <el-button size="small" type="primary" plain :disabled="!isAdmin" @click="handleEditProduct(scope.row)">修改</el-button>
              <el-button size="small" type="danger" plain :disabled="!isAdmin" @click="handleDeleteProduct(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="!productList.length" description="暂无产品配置，请先新建产品并为其配置加工精度指标" />
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="metricDialogVisible" :title="isEditMetric ? '修改精度指标' : '新建精度指标'" width="520px">
      <el-form :model="newMetric" label-width="100px">
        <el-form-item label="一级分类">
          <el-select v-model="newMetric.category_level_1" style="width: 100%">
            <el-option label="几何精度" value="几何精度" />
            <el-option label="位置精度" value="位置精度" />
            <el-option label="加工精度" value="加工精度" />
          </el-select>
        </el-form-item>
        <el-form-item label="二级类型"><el-input v-model="newMetric.category_level_2" /></el-form-item>
        <el-form-item label="指标名称"><el-input v-model="newMetric.metric_name" /></el-form-item>
        <el-form-item label="录入方式">
          <el-select v-model="newMetric.value_type" style="width: 100%">
            <el-option label="单值" value="单值" />
            <el-option label="抽样数组" value="抽样数组" />
          </el-select>
        </el-form-item>
        <el-form-item label="说明"><el-input v-model="newMetric.description" type="textarea" :rows="3" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="metricDialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="!isAdmin" @click="submitMetric">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="productDialogVisible" :title="isEditProduct ? '修改产品' : '新建产品'" width="520px">
      <el-form :model="newProduct" label-width="100px">
        <el-form-item label="产品编号"><el-input v-model="newProduct.product_code" /></el-form-item>
        <el-form-item label="产品名称"><el-input v-model="newProduct.product_name" /></el-form-item>
        <el-form-item label="说明"><el-input v-model="newProduct.product_detail" type="textarea" :rows="3" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="!isAdmin" @click="submitProduct">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="productMetricDialogVisible" title="配置产品加工精度指标" width="780px" top="6vh">
      <div class="toolbar" style="margin-top: -8px">
        <el-alert
          type="info"
          :closable="false"
          title="这里配置产品加工精度指标的出厂精度、失效精度和单位。同一指标作用在产品不同位置时，可在作用部位/备注中写明。"
        />
      </div>
      <div class="metric-list">
        <el-checkbox-group v-model="productMetricIds">
          <div v-for="metric in processMetrics" :key="metric.metric_id" class="metric-row">
            <el-checkbox :value="metric.metric_id" :label="metric.metric_id">
              <span>{{ metric.metric_name }}</span>
              <span style="margin-left: 8px; color: #8a98ac; font-size: 12px">{{ metric.category_level_2 }}</span>
            </el-checkbox>
	            <div v-if="productMetricIds.includes(metric.metric_id)" class="product-metric-inputs">
	              <el-input v-model="productLowerLimits[metric.metric_id]" placeholder="出厂精度" size="small" />
	              <el-input v-model="productUpperLimits[metric.metric_id]" placeholder="失效精度" size="small" />
	              <el-input v-model="productUnits[metric.metric_id]" placeholder="单位" size="small" />
	              <el-input v-model="productPositionNotes[metric.metric_id]" placeholder="作用部位/备注，例如外圆、端面、安装孔" size="small" />
	            </div>
          </div>
        </el-checkbox-group>
      </div>
      <template #footer>
        <el-button @click="productMetricDialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="!isAdmin" @click="saveProductMetricConfigs">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.config-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 18px;
}

.config-card {
  border-radius: 24px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.toolbar {
  margin-bottom: 16px;
}

.metric-list {
  display: grid;
  gap: 12px;
}

.metric-row {
  display: grid;
  gap: 10px;
  padding: 12px 14px;
  border-radius: 16px;
  background: rgba(245, 248, 253, 0.8);
}

.product-metric-inputs {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 10px;
}

@media (max-width: 1200px) {
  .config-grid {
    grid-template-columns: 1fr;
  }

  .product-metric-inputs {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
</style>
