<template>
  <a-modal
    v-model:visible="visible"
    :title="isEdit ? '编辑{{ModuleTitle}}' : '新增{{ModuleTitle}}'"
    :width="600"
    :mask-closable="false"
    unmount-on-close
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-form-item field="name" label="名称" required>
        <a-input v-model="formData.name" placeholder="请输入名称" :max-length="100" />
      </a-form-item>
      <a-form-item field="description" label="描述">
        <a-textarea v-model="formData.description" placeholder="请输入描述" :max-length="500" :auto-size="{ minRows: 3, maxRows: 5 }" />
      </a-form-item>
      <a-form-item field="enabled" label="启用状态">
        <a-switch v-model="formData.enabled" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { {{Module}}Item, {{Module}}CreateData, {{Module}}UpdateData } from '@/api/ops/{{module}}'
import { create{{Module}}, update{{Module}} } from '@/api/ops/{{module}}'

const props = defineProps<{
  visible: boolean
  record: {{Module}}Item | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}>()

const formRef = ref()
const isEdit = computed(() => !!props.record)

const formData = ref<{{Module}}CreateData>({
  name: '',
  description: '',
  enabled: true,
})

const rules = {
  name: [
    { required: true, message: '请输入名称' },
    { max_length: 100, message: '名称不能超过100个字符' },
  ],
}

watch(
  () => props.visible,
  (val) => {
    if (val && props.record) {
      formData.value = {
        name: props.record.name,
        description: props.record.description || '',
        enabled: props.record.enabled,
      }
    } else if (val) {
      formData.value = {
        name: '',
        description: '',
        enabled: true,
      }
    }
  }
)

const handleOk = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (valid) return

    if (isEdit.value && props.record) {
      const res = await update{{Module}}(props.record.id, formData.value as {{Module}}UpdateData)
      if (res && res.code === 0) {
        Message.success('更新成功')
        emit('success')
        emit('update:visible', false)
      }
    } else {
      const res = await create{{Module}}(formData.value)
      if (res && res.code === 0) {
        Message.success('创建成功')
        emit('success')
        emit('update:visible', false)
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    Message.error('操作失败')
  }
}

const handleCancel = () => {
  emit('update:visible', false)
}
</script>

<style scoped lang="less"></style>
