<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="150px">
    <el-row>
      <el-col :span="12">
        <el-form-item prop="tplCategory">
          <span slot="label">生成模板</span>
          <el-select v-model="formData.tplCategory" @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">
          <span slot="label">前端类型</span>
          <el-select v-model="formData.tplWebType">
            <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">
          <span slot="label">
            生成包路径
            <el-tooltip content="生成在哪个java包下，例如 com.rongji.system" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-input v-model="formData.packageName" />
        </el-form-item>
      </el-col>

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

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

      <el-col :span="12">
        <el-form-item prop="functionName">
          <span slot="label">
            生成功能名
            <el-tooltip content="用作类描述，例如 用户" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-input v-model="formData.functionName" />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="genType">
          <span slot="label">
            生成代码方式
            <el-tooltip content="默认为zip压缩包下载，也可以自定义生成路径" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-radio v-model="formData.genType" label="0">zip压缩包</el-radio>
          <el-radio v-model="formData.genType" label="1">自定义路径</el-radio>
        </el-form-item>
      </el-col>

      <!--      <el-col :span="12">
              <el-form-item>
                <span slot="label">
                  上级菜单
                  <el-tooltip content="分配到指定菜单下，例如 系统管理" placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-tree-select
                  v-model="formData.parentMenuId"
                  :data="menus"
                  :props="treeProps"
                  check-strictly
                  :render-after-expand="false"
                  placeholder="请选择系统菜单"
                />
              </el-form-item>
            </el-col>-->

      <el-col :span="24" v-if="formData.genType == '1'">
        <el-form-item prop="genPath">
          <span slot="label">
            自定义路径
            <el-tooltip content="填写磁盘绝对路径，若不填写，则生成到当前Web项目下" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-input v-model="formData.genPath">
            <template #append>
              <el-dropdown @command="handlePathCommand">
                <el-button type="primary">
                  最近路径快速选择
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="reset">恢复默认的生成基础路径</el-dropdown-item>
                    <el-dropdown-item command="project">项目根路径</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 树表配置 -->
    <el-row v-show="formData.tplCategory == 'tree'">
      <h4 class="form-header">其他信息</h4>
      <el-col :span="12">
        <el-form-item>
          <span slot="label">
            树编码字段
            <el-tooltip content="树显示的编码字段名， 如：dept_id" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-select v-model="formData.treeCode" placeholder="请选择">
            <el-option
              v-for="(column, index) in formData.columns"
              :key="index"
              :label="`${column.columnName}：${column.columnComment}`"
              :value="column.columnName"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item>
          <span slot="label">
            树父编码字段
            <el-tooltip content="树显示的父编码字段名， 如：parent_Id" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-select v-model="formData.treeParentCode" placeholder="请选择">
            <el-option
              v-for="(column, index) in formData.columns"
              :key="index"
              :label="`${column.columnName}：${column.columnComment}`"
              :value="column.columnName"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item>
          <span slot="label">
            树名称字段
            <el-tooltip content="树节点的显示名称字段名， 如：dept_name" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-select v-model="formData.treeName" placeholder="请选择">
            <el-option
              v-for="(column, index) in formData.columns"
              :key="index"
              :label="`${column.columnName}：${column.columnComment}`"
              :value="column.columnName"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 主子表配置 -->
    <el-row v-show="formData.tplCategory == 'sub'">
      <h4 class="form-header">关联信息</h4>
      <el-col :span="12">
        <el-form-item>
          <span slot="label">
            关联子表的表名
            <el-tooltip content="关联子表的表名， 如：sys_user" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-select v-model="formData.subTableName" placeholder="请选择" @change="handleSubTableChange">
            <el-option
              v-for="(table, index) in tables"
              :key="index"
              :label="`${table.tableName}：${table.tableComment}`"
              :value="table.tableName"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item>
          <span slot="label">
            子表关联的外键名
            <el-tooltip content="子表关联的外键名， 如：user_id" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-select v-model="formData.subTableFkName" placeholder="请选择">
            <el-option
              v-for="(column, index) in subColumns"
              :key="index"
              :label="`${column.columnName}：${column.columnComment}`"
              :value="column.columnName"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'

// Props
const props = defineProps({
  info: {
    type: Object,
    default: () => ({})
  },
  tables: {
    type: Array,
    default: () => []
  },
  menus: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['update:info', 'change'])

// Refs
const formRef = ref(null)
const subColumns = ref([])

// 表单数据 - 使用 computed 或者直接使用 props.info
const formData = ref({ ...props.info })

// 监听 props.info 的变化
watch(() => props.info, (newVal) => {
  formData.value = { ...newVal }
}, { deep: true })

// 树形选择器配置
const treeProps = {
  value: 'menuId',
  label: 'menuName',
  children: 'children'
}

// 表单验证规则
const 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" }
  ],
}

// 监听器
watch(() => formData.value.subTableName, (val) => {
  setSubTableColumns(val)
})

watch(() => formData.value.tplWebType, (val) => {
  if (val === '') {
    formData.value.tplWebType = "element-ui"
  }
})

// 确保数据正确同步到父组件
watch(formData, (newVal) => {
  // 同步所有字段到父组件的 info
  Object.keys(newVal).forEach(key => {
    props.info[key] = newVal[key]
  })
}, { deep: true, immediate: true })

// 添加一个方法来强制同步数据
const syncDataToParent = () => {
  Object.keys(formData.value).forEach(key => {
    props.info[key] = formData.value[key]
  })
}

// 方法
const handleSubTableChange = (value) => {
  formData.value.subTableFkName = ''
}

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

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

const handlePathCommand = (command) => {
  switch (command) {
    case 'reset':
      formData.value.genPath = '/'
      break
    case 'project':
      formData.value.genPath = process.cwd()
      break
  }
}

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

    formRef.value.validate((valid) => {
      if (valid) {
        resolve(formData.value)
      } 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,
  syncDataToParent
})
</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>
