<template>
  <a-modal
    :title="formTitle"
    :open="formOpen"
    :get-container="false"
    :mask-closable="false"
    :confirm-loading="loading"
    @cancel="handleCancel"
    @ok="submitForm"
    width="700px"
    destroy-on-close
  >
    <a-card :bordered="false">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
        layout="horizontal"
      >
        <a-form-item label="表单名称" name="formName">
          <a-input
            v-model:value="formState.formName"
            placeholder="请输入表单名称"
            show-count
            :maxlength="32"
            allow-clear
          />
        </a-form-item>

        <a-form-item label="地址(URL)" name="formUrl">
          <a-input
            v-model:value="formState.formUrl"
            placeholder="请输入地址"
            show-count
            :maxlength="128"
            allow-clear
          />
        </a-form-item>

        <a-form-item label="业务表名称" name="formTableName">
          <a-select
            v-model:value="formState.formTableName"
            placeholder="请选择业务表"
            allow-clear
            style="width: 100%"
          >
            <a-select-option
              v-for="item in tableOptions"
              :key="item.name"
              :value="item.name"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="备注" name="remark">
          <a-textarea
            v-model:value="formState.remark"
            placeholder="请输入备注"
            :auto-size="{ minRows: 4, maxRows: 6 }"
            show-count
            :maxlength="256"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-card>
    
    <template #footer>
      <a-button @click="handleCancel" :disabled="loading">取消</a-button>
      <a-button 
        type="primary" 
        @click="submitForm" 
        :loading="loading"
        :disabled="loading"
      >
        确定
      </a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { addForm, updateForm } from "@/components/Process/api/form"
import { selectTableNameList } from '/@/components/Process/api/definition'

interface FormState {
  id?: number | null
  formId?: number | null
  formName?: string
  formContent?: string
  remark?: string
  formRules?: string
  formOptions?: string
  formTp?: number
  formUrl?: string
  formTableName?: string
  createTime?: string
  updateTime?: string
  createBy?: string
  updateBy?: string
}

interface TableOption {
  name: string
  // 可以根据实际接口返回的字段添加更多属性
}

// 响应式数据
const formState = reactive<FormState>({
  id: undefined,
  formId: undefined,
  formTp: 2,
  formName: undefined,
  formContent: undefined,
  remark: undefined,
  formRules: undefined,
  formOptions: undefined,
  formUrl: undefined,
  formTableName: undefined,
  createTime: undefined,
  updateTime: undefined,
  createBy: undefined,
  updateBy: undefined,
})

// refs
const formOpen = ref(false)
const formRef = ref<FormInstance>()
const tableOptions = ref<TableOption[]>([])
const loading = ref(false)

// 计算属性
const formTitle = computed(() => 
  formState.formId ? '修改表单' : '新增表单'
)

// 表单验证规则
const rules = reactive({
  formName: [
    { required: true, message: '表单名称不能为空', trigger: 'blur' },
    { min: 1, max: 32, message: '表单名称长度应在1-32个字符之间', trigger: 'blur' }
  ],
  formUrl: [
    { required: true, message: '表单地址不能为空', trigger: 'blur' },
    { min: 1, max: 128, message: '表单地址长度应在1-128个字符之间', trigger: 'blur' }
  ],
  formTableName: [
    { required: true, message: '请选择业务表名称', trigger: 'change' }
  ]
})

// emits
const emit = defineEmits<{
  callBack: []
}>()

// 方法
/**
 * 初始化表单数据
 */
const iniData = async (data: Partial<FormState> = {}) => {
  try {
    formOpen.value = true
    resetFormState()
    
    // 加载业务表列表
    await loadTableOptions()
    
    // 如果有传入数据，则填充表单
    if (data && Object.keys(data).length > 0) {
      Object.assign(formState, data)
    }
  } catch (error) {
    console.error('初始化表单失败:', error)
    message.error('初始化表单失败')
  }
}

/**
 * 加载业务表选项
 */
const loadTableOptions = async () => {
  try {
    const res = await selectTableNameList()
    tableOptions.value = res || []
  } catch (error) {
    console.error('加载业务表列表失败:', error)
    tableOptions.value = []
    message.error('加载业务表列表失败')
  }
}

/**
 * 取消操作
 */
const handleCancel = () => {
  if (loading.value) return
  
  formOpen.value = false
  resetForm()
}

/**
 * 重置表单状态
 */
const resetFormState = () => {
  Object.keys(formState).forEach(key => {
    formState[key] = undefined
  })
  formState.formTp = 2 // 设置默认值
}

/**
 * 重置表单（包括验证状态）
 */
const resetForm = () => {
  formRef.value?.resetFields()
  resetFormState()
}

/**
 * 提交表单
 */
const submitForm = async () => {
  try {
    // 表单验证
    await formRef.value?.validate()
    
    loading.value = true
    
    // 根据是否有formId决定是新增还是修改
    const submitFn = formState.formId ? updateForm : addForm
    await submitFn(formState)
    
    message.success(formState.formId ? '修改成功' : '新增成功')
    formOpen.value = false
    resetForm()
    
    // 通知父组件
    emit('callBack')
    
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error instanceof Error) {
      message.error(error.message || '操作失败')
    }
  } finally {
    loading.value = false
  }
}

// 暴露方法给父组件
defineExpose({
  iniData
})
</script>

<style scoped>
:deep(.ant-card) {
  border: none;
  box-shadow: none;
}
</style>