<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="80px"
    inline
  >
    <el-form-item label="类型名称" prop="name">
      <el-input
        v-model="formData.name"
        placeholder="请输入类型名称"
        maxlength="20"
        show-word-limit
        style="width: 200px"
      />
    </el-form-item>

    <el-form-item label="排序值" prop="sort">
      <el-input-number
        v-model="formData.sort"
        :min="0"
        :max="9999"
        controls-position="right"
        style="width: 120px"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" size="small" @click="handleSubmit">
        确定
      </el-button>
      <el-button size="small" @click="handleCancel">
        取消
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { AdvertTypeCreateRequest } from '@/api/business/advert'

const props = defineProps<{
  modelValue: AdvertTypeCreateRequest
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: AdvertTypeCreateRequest): void
  (e: 'submit'): void
  (e: 'cancel'): void
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const formData = ref<AdvertTypeCreateRequest>({
  name: props.modelValue.name,
  sort: props.modelValue.sort
})

// 监听外部数据变化
watch(() => props.modelValue, (val) => {
  formData.value = { ...val }
}, { deep: true })

// 同步数据到外部
watch(formData, (val) => {
  emit('update:modelValue', val)
}, { deep: true })

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' },
    { min: 1, max: 20, message: '名称长度在1-20个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    emit('submit')
  } catch {
    // 验证失败
  }
}

// 取消
const handleCancel = () => {
  emit('cancel')
}

// 暴露方法
defineExpose({
  validate: () => formRef.value?.validate(),
  resetFields: () => formRef.value?.resetFields()
})
</script>

<style scoped>
</style>
