<!-- MetricForm.vue - 指标配置表单组件 -->
<template>
  <el-form 
    ref="formRef" 
    :model="metric" 
    :rules="rules" 
    label-width="100px"
    @submit.prevent
  >
    <el-form-item label="指标名称" prop="name">
      <el-input v-model="metric.name" placeholder="请输入指标名称" />
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { addIndicator, updateIndicator } from '@/api/evaluate/indicator'
import { ElMessage } from 'element-plus'

const props = defineProps({
  metric: {
    type: Object,
    required: true
  },
  isNew: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['refresh'])

const formRef = ref(null)

const rules = reactive({
  name: [
    { required: true, message: '请输入指标名称', trigger: 'blur' }
  ]
})

const submitForm = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (props.isNew) {
        const res = await addIndicator({ name: props.metric.name, parentId: 0, level: 1, type: 1 })
        if (res.code === 200) {
          ElMessage.success('指标添加成功')
          emit('refresh')
        } else {
          ElMessage.error(res.message || '指标添加失败')
        }
      } else {
        const res = await updateIndicator({ id: props.metric.id, name: props.metric.name })
        if (res.code === 200) {
          ElMessage.success('指标修改成功')
          emit('refresh')
        } else {
          ElMessage.error(res.message || '指标修改失败')
        }
      }
    }
  })
}

defineExpose({
  submitForm
})
</script>