<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" @submit.prevent>
      <el-form-item label="分组名称" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入分组名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <!-- 单选框 -->
        <el-radio-group v-model="queryParams.status">
          <el-radio
            v-for="dict in group_status"
            :key="dict.value"
            :label="dict.value"
          >{{dict.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery" native-type="button"> 搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['group_management:group_management:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="group_managementList"
      row-key="groupId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <!-- <el-table-column label="上级分组" prop="parentId" /> -->
      <el-table-column label="分组名称" align="center" prop="groupName" />
      <!-- <el-table-column label="祖级列表" align="center" prop="ancestors" /> -->
      <el-table-column label="所属分组" align="center" prop="ancestorNames" />
      <!-- <el-table-column label="是否为叶子结点" align="center" prop="isLeaf" /> -->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="group_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建者" align="center" prop="createBy" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="更新者" align="center" prop="updateBy" /> -->
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['group_management:group_management:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['group_management:group_management:add']">新增</el-button>
          <el-button v-if="scope.row.isLeaf === true" link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['group_management:group_management:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改分组管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="group_managementRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级分组" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="group_managementOptions"
            :props="{ value: 'groupId', label: 'groupName', children: 'children' }"
            value-key="groupId"
            placeholder="请选择上级分组"
            check-strictly
            :disabled="title === '修改分组管理'"
          />
        </el-form-item>
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in group_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Group_management">
import { listGroup_management, getGroup_management, delGroup_management, addGroup_management, updateGroup_management } from "@/api/fileManagement/group_management"

const { proxy } = getCurrentInstance()
const { group_status } = proxy.useDict('group_status')

const group_managementList = ref([])
const group_managementOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const isExpandAll = ref(true)
const refreshTable = ref(true)

const data = reactive({
  form: {},
  queryParams: {
    groupName: null,
    status: '0', // 默认启用状态
  },
  rules: {
    parentId: [
      { required: true, message: "上级分组不能为空", trigger: "blur" }
    ],
    groupName: [
      { required: true, message: "分组名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询分组管理列表 */
function getList() {
  loading.value = true
  listGroup_management(queryParams.value).then(response => {
    group_managementList.value = proxy.handleTree(response.data, "groupId", "parentId")
    loading.value = false
  })
}

/** 查询分组管理下拉树结构 */
function getTreeselect() {
  listGroup_management().then(response => {
    group_managementOptions.value = []
    const data = { groupId: 0, groupName: '顶级节点', ancestors:"0",children: [] }
    data.children = proxy.handleTree(response.data, "groupId", "parentId")
    group_managementOptions.value.push(data)
  })
}

// 新增：递归查找节点函数
function findNode(tree, id) {
  let result = null
  for (const node of tree) {
    if (node.groupId === id) return node
    if (node.children && node.children.length) {
      result = findNode(node.children, id)
      if (result) return result
    }
  }
  return result
}
	
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    groupId: null,
    parentId: null,
    groupName: null,
    ancestors: null,
    status: '0', // 默认启用状态
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("group_managementRef")
}

/** 搜索功能 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  getTreeselect()
  if (row != null && row.groupId) {
    form.value.parentId = row.groupId
  } else {
    form.value.parentId = 0
  }
  open.value = true
  title.value = "添加分组管理"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTreeselect()
  if (row != null) {
    form.value.parentId = row.parentId
  }
  getGroup_management(row.groupId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改分组管理"
  })
}

/** 提交按钮 */
// function submitForm() {
//   proxy.$refs["group_managementRef"].validate(valid => {
//     if (valid) {
//       // 新增：计算祖先路径
//       if (form.value.parentId === 0) {
//         form.value.ancestors = "0"
//       } else {
//         const parentNode = findNode(group_managementOptions.value, form.value.parentId)
//         if (parentNode) {
//           form.value.ancestors = `${parentNode.ancestors},${parentNode.groupId}`
//         } else {
//           // 找不到父节点时使用默认值
//           form.value.ancestors = "0"
//         }
//       }

//       if (form.value.groupId != null) {
//         updateGroup_management(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功")
//           open.value = false
//           getList()
//         })
//       } else {
//         addGroup_management(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功")
//           open.value = false
//           getList()
//         })
//       }
//     }
//   })
// }

/** 提交按钮 */
function submitForm() {
  proxy.$refs["group_managementRef"].validate(valid => {
    if (!valid) return;

    // 计算祖先路径
    if (form.value.parentId === 0) {
      form.value.ancestors = "0";
    } else {
      const parentNode = findNode(group_managementOptions.value, form.value.parentId);
      form.value.ancestors = parentNode
        ? `${parentNode.ancestors},${parentNode.groupId}`
        : "0";
    }

    const request = form.value.groupId != null
      ? updateGroup_management(form.value)
      : addGroup_management(form.value);

    request
      .then(() => {
        proxy.$modal.msgSuccess(form.value.groupId ? "修改成功" : "新增成功");
        open.value = false;
        getList();
      })
      .catch(error => {
        // ✅ 后端返回的错误信息
        const msg = error?.response?.data?.msg || "操作失败";
        proxy.$modal.msgError(msg);
      });
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除分组管理编号为"' + row.groupId + '"的数据项？').then(function() {
    return delGroup_management(row.groupId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>