/**
 * 表单对话框管理 Composable
 */

import { ref, reactive, nextTick } from 'vue'
import type { FormInstance } from 'element-plus'

export type DialogMode = 'add' | 'edit' | 'view'

export interface FormDialogOptions<T> {
  initialData?: () => T
}

export function useFormDialog<T extends Record<string, any>>(options: FormDialogOptions<T> = {}) {
  // 对话框可见性
  const visible = ref(false)

  // 对话框模式
  const mode = ref<DialogMode>('add')

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

  // 表单数据
  const formData = reactive<T>((options.initialData?.() || {}) as T)

  // 加载状态
  const loading = ref(false)

  // 对话框标题
  const dialogTitle = ref('')

  /**
   * 打开对话框
   * @param dialogMode 对话框模式
   * @param data 初始数据（编辑/查看模式）
   * @param title 自定义标题
   */
  const open = (dialogMode: DialogMode = 'add', data?: Partial<T>, title?: string) => {
    mode.value = dialogMode
    visible.value = true

    // 设置标题
    if (title) {
      dialogTitle.value = title
    } else {
      const titles: Record<DialogMode, string> = {
        add: '新增',
        edit: '编辑',
        view: '查看'
      }
      dialogTitle.value = titles[dialogMode]
    }

    // 重置表单
    nextTick(() => {
      formRef.value?.resetFields()

      // 如果有初始数据，填充表单
      if (data) {
        Object.assign(formData, data)
      } else if (options.initialData) {
        Object.assign(formData, options.initialData())
      }
    })
  }

  /**
   * 关闭对话框
   */
  const close = () => {
    visible.value = false
    nextTick(() => {
      formRef.value?.resetFields()
    })
  }

  /**
   * 验证表单
   */
  const validate = async (): Promise<boolean> => {
    if (!formRef.value) return false

    try {
      await formRef.value.validate()
      return true
    } catch {
      return false
    }
  }

  /**
   * 重置表单
   */
  const resetFields = () => {
    formRef.value?.resetFields()
  }

  /**
   * 清空验证
   */
  const clearValidate = () => {
    formRef.value?.clearValidate()
  }

  // 是否为新增模式
  const isAddMode = () => mode.value === 'add'

  // 是否为编辑模式
  const isEditMode = () => mode.value === 'edit'

  // 是否为查看模式
  const isViewMode = () => mode.value === 'view'

  return {
    visible,
    mode,
    formRef,
    formData,
    loading,
    dialogTitle,
    open,
    close,
    validate,
    resetFields,
    clearValidate,
    isAddMode,
    isEditMode,
    isViewMode
  }
}
