<template>
  <div>
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
      <el-button @click="$router.back()"><el-icon><ArrowLeft /></el-icon> 返回</el-button>
      <span style="font-size:16px;font-weight:bold">{{ isEdit ? '编辑品牌' : '新增品牌' }}</span>
    </div>
    <el-card shadow="hover" style="margin-bottom:20px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="品牌名称" required><el-input v-model="form.brandName" maxlength="50" /></el-form-item>
        <el-form-item label="device字段" required><el-input v-model="form.deviceField" /></el-form-item>
        <el-form-item label="tags路径" required><el-input v-model="form.tagsPath" /></el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="hover">
      <template #header><div style="display:flex;justify-content:space-between"><span>字段映射列表</span><el-button size="small" @click="addMapping">+ 新增映射</el-button></div></template>
      <el-table :data="form.mappings" border stripe size="small" style="width:100%" row-class-name="mapping-row" :row-style="({row}) => row.isEnabled === 0 ? { opacity: 0.5 } : {}">
        <el-table-column label="标准字段" min-width="180"><template #default="{row}"><el-select v-model="row.standardField" style="width:100%"><el-option v-for="f in standardFields" :key="f" :label="f" :value="f" /></el-select></template></el-table-column>
        <el-table-column label="字段名" min-width="140"><template #default="{row}"><el-input v-model="row.fieldName" /></template></el-table-column>
        <el-table-column label="匹配方式" min-width="110"><template #default="{row}"><el-select v-model="row.matchBy" style="width:100%"><el-option label="id" value="id" /><el-option label="desc" value="desc" /></el-select></template></el-table-column>
        <el-table-column label="数据类型" min-width="110"><template #default="{row}"><el-select v-model="row.dataType" style="width:100%"><el-option label="string" value="string" /><el-option label="number" value="number" /></el-select></template></el-table-column>
        <el-table-column label="必填" width="60" align="center"><template #default="{row}"><el-checkbox v-model="row.isRequired" :true-value="1" :false-value="0" /></template></el-table-column>
        <el-table-column label="启用" width="70" align="center"><template #default="{row}"><el-switch v-model="row.isEnabled" :active-value="1" :inactive-value="0" inline-prompt active-text="是" inactive-text="否" /></template></el-table-column>
        <el-table-column label="操作" width="80" align="center"><template #default="{ $index }"><el-button link type="danger" @click="form.mappings.splice($index, 1)">删除</el-button></template></el-table-column>
      </el-table>
    </el-card>
    <div style="margin-top:20px;text-align:right">
      <el-button @click="$router.back()">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSave">保存</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
const route = useRoute()
const router = useRouter()
import type { Brand, ApiResponse } from '@/types'
type BrandMappingForm = { standardField: string; fieldName: string; matchBy: string; dataType: string; isRequired: number; isEnabled: number }
const isEdit = !!route.params.id
const submitting = ref(false)
const standardFields = ['program_name','part_count','device_status','run_status','operate_mode','spindle_speed_set','feed_speed_set','spindle_speed_actual','feed_speed_actual','spindle_load','spindle_override','power_on_time','run_time','cutting_time','cycle_time','machining_status']
const form = reactive({ brandName: '', deviceField: 'device', tagsPath: 'tags', mappings: [] as BrandMappingForm[] })
function addMapping() { form.mappings.push({ standardField: '', fieldName: '', matchBy: 'id', dataType: 'string', isRequired: 0, isEnabled: 1 }) }
async function loadData() {
  if (!isEdit) return
  const r = await request.get<Brand>(`/admin/brand/${route.params.id}`)
  if (r.data) { form.brandName = r.data.brandName; form.deviceField = r.data.deviceField; form.tagsPath = r.data.tagsPath; form.mappings = (r.data as any).mappings || [] }
}
async function handleSave() {
  await ElMessageBox.confirm('品牌模板修改不影响历史数据，确定保存？', '提示', { type: 'warning' })
  submitting.value = true
  try { await request[isEdit ? 'put' : 'post'](isEdit ? `/admin/brand/${route.params.id}` : '/admin/brand', { ...form }); ElMessage.success('保存成功'); router.back() } finally { submitting.value = false }
}
onMounted(loadData)
</script>
