<template>
  <el-dialog class="group-edit" v-model="showDialog" :title="`${formData.id ? '编辑分组' : '新增分组'}`" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form ref="formRef" :model="formData" :rules="ruleForm" label-width="100px" @keyup.enter="onSubmit">
      <el-form-item label="分组名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入分组名称" />
      </el-form-item>
      <el-form-item label="分组标识" prop="groupKey">
        <el-input v-model="formData.groupKey" placeholder="请输入分组唯一标识，留空则自动生成" />
      </el-form-item>
      <el-form-item label="父级分组" prop="parentId">
        <el-cascader v-model="formData.parentId" :options="groupOptions" :props="cascaderProps" placeholder="请选择父级分组，不选择则为顶级分组" clearable style="width: 100%" />
      </el-form-item>
      <el-form-item label="排序号" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" :max="999" />
      </el-form-item>
      <el-form-item label="分组描述" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入分组描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { ruleRequired } from "/@/utils/validator";
import api from "/@/api/modules/apiHub";

const emit = defineEmits(["refresh"]);

const showDialog = ref(false);
const formRef = ref();
const groupOptions = ref<any[]>([]);
const cascaderProps = {
  checkStrictly: true,
  emitPath: false,
  value: 'Id',
  label: 'Name',
  children: 'Children'
};
let treeData: any[] = [];

// 定义基础表单数据
const baseForm = {
  id: undefined,
  groupKey: "",
  name: "",
  parentId: "",
  sort: 0,
  description: "",
};

const formData = reactive({ ...baseForm });

// 表单验证规则
const ruleForm = {
  name: [ruleRequired("分组名称不能为空", "change")],
};

// 获取分组树形结构
api.group.tree().then((res: any) => {
  treeData = res.list || [];
  groupOptions.value = res.list || [];
});

// 提交表单
const onSubmit = async () => {
  await formRef.value.validate();

  // 准备提交数据
  const submitData = JSON.parse(JSON.stringify(formData));

  // 如果没有设置groupKey，生成一个基于名称的唯一标识
  if (!submitData.groupKey) {
    submitData.groupKey = "group_" + Date.now() + "_" + Math.floor(Math.random() * 1000);
  }

  // 处理空的parent_key，将空字符串设置为null
  if (submitData.parentId === "") {
    submitData.parentId = null;
  }

  // 调用API
  if (submitData.id) {
    // 编辑模式
    await api.group.edit(submitData);
  } else {
    // 新增模式
    await api.group.add(submitData);
  }

  ElMessage.success("操作成功");
  resetForm();
  showDialog.value = false;
  emit("refresh");
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, { ...baseForm });
  formRef.value && formRef.value.resetFields();
};

// 取消操作
const cancel = () => {
  resetForm();
  showDialog.value = false;
};

// 加载分组选项
const loadGroupOptions = async (excludeId?: string) => {
  // 如果是编辑模式，需要排除当前分组及其子分组
  if (excludeId) {
    const filterTree = (nodes: any[]) => {
      return nodes.filter((node) => {
        if (node.Id === excludeId) {
          return false;
        }
        if (node.Children && node.Children.length) {
          node.Children = filterTree(node.Children);
        }
        return true;
      });
    };

    groupOptions.value = filterTree(treeData);
  } else {
    groupOptions.value = treeData;
  }
};

// 根据GroupKey查找Id
const findIdByGroupKey = (groupKey: string, tree: any[]): string | null => {
  for (const node of tree) {
    if (node.GroupKey === groupKey) {
      return node.Id;
    }
    if (node.Children && node.Children.length > 0) {
      const foundId = findIdByGroupKey(groupKey, node.Children);
      if (foundId) return foundId;
    }
  }
  return null;
};

// 打开对话框
const open = async (row?: any, parentGroupKey?: string) => {
  // 先重置表单
  resetForm();
  showDialog.value = true;

  // 加载分组选项
  await loadGroupOptions(row?.Id);

  // 等待DOM更新
  await nextTick();
  
  if (row) {
    // 编辑模式，填充表单数据
    formData.id = row.Id;
    formData.groupKey = row.GroupKey;
    formData.name = row.Name;
    formData.parentId = row.ParentId;
    formData.sort = row.Sort;
    formData.description = row.Description;
  } else if (parentGroupKey) {
    // 新增子分组模式
    // 先根据GroupKey查找Id
    const parentId = findIdByGroupKey(parentGroupKey, treeData);
    
    if (parentId) {
      // 使用setTimeout确保在下一个事件循环中设置值
      setTimeout(() => {
        // 设置父级分组ID
        formData.parentId = parentId;
        
        // 手动触发表单验证，强制更新显示
        if (formRef.value) {
          formRef.value.validateField('parentId');
        }
      }, 200);
    }
  }
};

defineExpose({ open });
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
