<template>
  <cacp-form-layout>
    <el-form
      ref="formRef"
      :model="state.formData"
      :rules="state.rules"
      label-width="150px"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="tplCategory"  label="生成模板">
            <el-select v-model="state.formData.tplCategory" disabled @change="handleTplChange">
              <el-option label="单表（增删改查）" value="crud" />
              <el-option label="树表（增删改查）" value="tree" />
              <el-option label="主子表（增删改查）" value="sub" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="tplWebType" label="前端类型">
            <el-select v-model="state.formData.tplWebType" disabled>
              <el-option label="Vue2 Element UI 模版" value="element-ui" />
              <el-option label="Vue3 Element Plus 模版" value="element-plus" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="packageName">
            <template #label>
              生成包路径
              <el-tooltip content="生成在哪个java包下，例如 com.rongji.system" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-input v-model="state.formData.packageName" placeholder="请输入生成包路径" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="moduleName">
            <template #label>
              生成模块名
              <el-tooltip content="可理解为子系统名，例如 system" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-input v-model="state.formData.moduleName" placeholder="请输入生成模块名" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="businessName">
            <template #label>
              生成业务名
              <el-tooltip content="可理解为功能英文名，例如 user" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-input v-model="state.formData.businessName" placeholder="请输入生成业务名" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="functionName">
            <template #label>
              生成功能名
              <el-tooltip content="用作类描述，例如 用户" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <el-input v-model="state.formData.functionName" placeholder="请输入生成功能名" clearable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </cacp-form-layout>
</template>

<script lang="ts" setup>
import { reactive, ref, watch} from 'vue'
import type { GenTableColumn } from '@/types/gen/GenTableColumn'
import type { FormInstance, FormRules } from 'element-plus'

// 定义类型
interface TableInfo {
  tableName: string
  tableComment: string
  columns?: GenTableColumn[]
}

interface Menu {
  menuId: number
  menuName?: string
  children?: Menu[]
}

interface FormData {
  tplCategory?: string
  tplWebType?: string
  packageName?: string
  moduleName?: string
  businessName?: string
  functionName?: string
  genType?: string
  genPath?: string
  treeCode?: string
  treeParentCode?: string
  treeName?: string
  subTableName?: string
  subTableFkName?: string
  columns?: GenTableColumn[]
  parentMenuId?: number
  [key: string]: any
}

// Props
interface Props {
  info: FormData
  tables: TableInfo[]
  menus: Menu[]
}

const props = withDefaults(defineProps<Props>(), {
  info: () => ({
    tplCategory: 'crud',
    tplWebType: 'element-ui',
    packageName: '',
    moduleName: '',
    businessName: '',
    functionName: '',
    genType: '0',
    genPath: '',
    treeCode: '',
    treeParentCode: '',
    treeName: '',
    subTableName: '',
    subTableFkName: '',
    columns: []
  }),
  tables: () => [],
  menus: () => []
})

// Refs
const formRef = ref<FormInstance>()

// 响应式状态
interface State {
  formData: FormData
  subColumns: GenTableColumn[]
  rules: FormRules
  treeProps: {
    value: string
    label: string
    children: string
  }
}

const state = reactive<State>({
  formData: {
    tplCategory: 'crud',
    tplWebType: 'element-ui',
    packageName: '',
    moduleName: '',
    businessName: '',
    functionName: '',
    genType: '0',
    genPath: '',
    treeCode: '',
    treeParentCode: '',
    treeName: '',
    subTableName: '',
    subTableFkName: '',
    columns: []
  },
  subColumns: [],
  rules: {
    tplCategory: [
      { required: true, message: '请选择生成模板', trigger: 'blur' }
    ],
    packageName: [
      { required: true, message: '请输入生成包路径', trigger: 'blur' }
    ],
    moduleName: [
      { required: true, message: '请输入生成模块名', trigger: 'blur' }
    ],
    businessName: [
      { required: true, message: '请输入生成业务名', trigger: 'blur' }
    ],
    functionName: [
      { required: true, message: '请输入生成功能名', trigger: 'blur' }
    ]
  },
  treeProps: {
    value: 'menuId',
    label: 'menuName',
    children: 'children'
  }
})

// 监听 props 变化，更新表单数据
watch(
  () => props.info,
  (newInfo) => {
    if (newInfo) {
      state.formData = {
        tplCategory: newInfo.tplCategory || 'crud',
        tplWebType: newInfo.tplWebType || 'element-ui',
        packageName: newInfo.packageName || '',
        moduleName: newInfo.moduleName || '',
        businessName: newInfo.businessName || '',
        functionName: newInfo.functionName || '',
        genType: newInfo.genType || '0',
        genPath: newInfo.genPath || '',
        treeCode: newInfo.treeCode || '',
        treeParentCode: newInfo.treeParentCode || '',
        treeName: newInfo.treeName || '',
        subTableName: newInfo.subTableName || '',
        subTableFkName: newInfo.subTableFkName || '',
        columns: newInfo.columns || [],
        parentMenuId: newInfo.parentMenuId
      }
    }
  },
  { immediate: true, deep: true }
)

// 监听 tables 和 menus
// watch(
//   () => props.tables,
//   (newTables) => {
//     // 可以在这里处理 tables 数据的更新
//   },
//   { immediate: true }
// )
//
// watch(
//   () => props.menus,
//   (newMenus) => {
//     // 可以在这里处理 menus 数据的更新
//   },
//   { immediate: true }
// )

// 监听子表名变化
watch(
  () => state.formData.subTableName,
  (newVal) => {
    setSubTableColumns(newVal)
  }
)

// 监听前端类型变化
watch(
  () => state.formData.tplWebType,
  (newVal) => {
    if (!newVal) {
      state.formData.tplWebType = 'element-ui'
    }
  }
)

const handleTplChange = (value: string) => {
  if (value !== 'sub') {
    state.formData.subTableName = ''
    state.formData.subTableFkName = ''
  }
}

const setSubTableColumns = (value: string) => {
  const table = props.tables.find(item => item.tableName === value)
  if (table) {
    state.subColumns = table.columns || []
  } else {
    state.subColumns = []
  }
}


// 表单验证方法
const validate = () => {
  return new Promise((resolve, reject) => {
    if (!formRef.value) {
      reject(new Error('表单未初始化'))
      return
    }

    formRef.value.validate((valid) => {
      if (valid) {
        resolve(state.formData)
      } else {
        reject(new Error('表单验证失败'))
      }
    })
  })
}

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

// 清除验证
const clearValidate = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 暴露方法给父组件
defineExpose({
  getFormRef: () => formRef.value,
  validate,
  resetFields,
  clearValidate
})
</script>

<style scoped>
.form-header {
  margin: 10px 0;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
  color: #409eff;
  font-size: 14px;
  font-weight: 600;
}

.el-col {
  margin-bottom: 10px;
}
</style>
