<template>
  <div class="app-container">
    <!-- 顶部搜索区域 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search-wrapper">
        <el-card class="search-card">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="queryParams.menuName" placeholder="请输入菜单名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="菜单状态" clearable style="width: 140px">
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card class="modern-card">
      <template #header>
        <el-row :gutter="10" class="mb8 op-row">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" @click="handleCascadeDelete" :loading="deleteLoading">删除</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-tabs v-model="platformId" @tab-change="handlePlatformChange" class="modern-tabs">
        <el-tab-pane label="平台管理端" :name="0" />
        <el-tab-pane label="商户后台" :name="1" />
      </el-tabs>

      <el-table
        ref="menuTableRef"
        v-loading="loading"
        :data="menuList"
        row-key="menuId"
        style="width: 100%"
        :header-cell-style="{ background: '#f8f9fb', color: '#666', fontWeight: 'bold' }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        lazy
        :load="getChildrenList"
        @expand-change="expandMenuHandle"
      >
        <el-table-column prop="menuName" label="菜单名称" min-width="180" :show-overflow-tooltip="true">
          <template #default="scope">
            <span class="menu-name-text">{{ scope.row.menuName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标" align="center" width="80">
          <template #default="scope">
            <div class="icon-wrapper">
              <svg-icon :icon-class="scope.row.icon" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="排序" align="center" width="80" />
        <el-table-column prop="perms" label="权限标识" min-width="150" :show-overflow-tooltip="true">
          <template #default="scope">
            <code class="perms-code" v-if="scope.row.perms">{{ scope.row.perms }}</code>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="component" label="组件路径" min-width="180" :show-overflow-tooltip="true">
          <template #default="scope">
            <span class="path-text">{{ scope.row.component || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'" size="small" effect="light" class="status-tag">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="180" prop="createTime" />
        <el-table-column label="操作" align="right" width="180" fixed="right">
          <template #default="scope">
            <div class="op-btns">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
              </el-tooltip>
              <el-tooltip content="新增" placement="top">
                <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="750px">
      <el-form ref="menuFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <el-tree-select v-model="form.parentId" :data="menuOptions"
                              :props="{ value: 'menuId', label: 'menuName', children: 'children' } as any" value-key="menuId"
                              placeholder="选择上级菜单" check-strictly style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio-button value="M">目录</el-radio-button>
                <el-radio-button value="C">菜单</el-radio-button>
                <el-radio-button value="F">按钮</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'F'" :span="24">
            <el-form-item label="菜单图标" prop="icon">
              <icon-select v-model="form.icon" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'F'" :span="12">
            <el-form-item label="是否外链">
              <el-radio-group v-model="form.isFrame">
                <el-radio value="0">是</el-radio>
                <el-radio value="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'F'" :span="12">
            <el-form-item prop="path">
              <template #label>
                <span>
                  <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip> 路由地址
                </span>
              </template>
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType === 'C'" :span="12">
            <el-form-item prop="component">
              <template #label>
                <span>
                  <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip> 组件路径
                </span>
              </template>
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'M'" :span="12">
            <el-form-item label="权限字符">
              <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType === 'C'" :span="12">
            <el-form-item label="是否缓存">
              <el-radio-group v-model="form.isCache">
                <el-radio value="0">缓存</el-radio>
                <el-radio value="1">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'F'" :span="12">
            <el-form-item label="显示状态">
              <el-radio-group v-model="form.visible">
                <el-radio v-for="dict in sys_show_hide" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 级联删除对话框 -->
    <el-dialog v-model="deleteDialog.visible" :title="deleteDialog.title" destroy-on-close append-to-body width="600px">
      <div class="delete-tree-container">
        <el-tree ref="menuTreeRef" class="tree-border" :data="menuOptions" show-checkbox node-key="menuId"
                 :check-strictly="false" empty-text="加载中，请稍候" :default-expanded-keys="[0]"
                 :props="{ value: 'menuId', label: 'menuName', children: 'children' } as any" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelCascade">取 消</el-button>
          <el-button type="primary" @click="submitDeleteForm" :loading="deleteLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup name="Menu" lang="ts">
import { addMenu, cascadeDelMenu, delMenu, getMenu, listMenu, updateMenu } from '@/api/system/menu';
import { MenuForm, MenuQuery, MenuVO } from '@/api/system/menu/types';
import { MenuTypeEnum } from '@/enums/MenuTypeEnum';

interface MenuOptionsType {
  menuId: number;
  menuName: string;
  children: MenuOptionsType[] | undefined;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_show_hide, sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_show_hide', 'sys_normal_disable'));

const platformId = ref(0);
const menuList = ref<MenuVO[]>([]);
const menuChildrenListMap = ref({});
const menuExpandMap = ref({});
const loading = ref(true);
const menuOptions = ref<MenuOptionsType[]>([]);
const showSearch = ref(true); // 搜索显隐变量
const isExpandAll = ref(false); // 展开状态控制

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const menuFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>(); // 搜索表单引用
const initFormData = {
  path: '',
  menuId: undefined,
  parentId: 0,
  menuName: '',
  icon: '',
  menuType: MenuTypeEnum.M,
  orderNum: 1,
  isFrame: '1',
  isCache: '0',
  visible: '0',
  status: '0'
};
const data = reactive<PageData<MenuForm, MenuQuery>>({
  form: { ...initFormData },
  queryParams: {
    menuName: undefined,
    status: undefined
  },
  rules: {
    menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }],
    path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }]
  }
});

const menuTableRef = ref<ElTableInstance>();
const { queryParams, form, rules } = toRefs<PageData<MenuForm, MenuQuery>>(data);

/** 重置查询 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

/** 展开/折叠操作 */
const toggleExpandAll = () => {
    isExpandAll.value = !isExpandAll.value;
    menuList.value.forEach(row => {
        menuTableRef.value?.toggleRowExpansion(row, isExpandAll.value);
    });
};

/** 获取子菜单列表 */
const getChildrenList = async (row: any, treeNode: unknown, resolve: (data: any[]) => void) => {
  menuExpandMap.value[row.menuId] = { row, treeNode, resolve };
  const children = menuChildrenListMap.value[row.menuId] || [];
  if (children.length == 0) {
    menuTableRef.value?.updateKeyChildren(row.menuId, children);
  }
  resolve(children);
};

const expandMenuHandle = async (row: any, expanded: boolean) => {
  if (!expanded) {
    menuExpandMap.value[row.menuId] = undefined;
  }
};

const refreshLoadTree = (parentId: string | number) => {
  if (menuExpandMap.value[parentId]) {
    const { row, treeNode, resolve } = menuExpandMap.value[parentId];
    if (row) {
      getChildrenList(row, treeNode, resolve);
      if (row.parentId) {
        const grandpaMenu = menuExpandMap.value[row.parentId];
        if (grandpaMenu) getChildrenList(grandpaMenu.row, grandpaMenu.treeNode, grandpaMenu.resolve);
      }
    }
  }
};

const refreshAllExpandMenuData = () => {
  for (const menuId in menuExpandMap.value) {
    refreshLoadTree(menuId);
  }
};

const getList = async () => {
  loading.value = true;
  const params = { ...queryParams.value, platformId: platformId.value };
  const res = await listMenu(params);

  const tempMap = {};
  for (const menu of res.data) {
    const parentId = menu.parentId;
    if (!tempMap[parentId]) tempMap[parentId] = [];
    tempMap[parentId].push(menu);
  }
  
  const menuIdSet = new Set();
  for (const menu of res.data) {
    menu['hasChildren'] = tempMap[menu.menuId]?.length > 0;
    menuIdSet.add(menu.menuId);
  }
  menuChildrenListMap.value = tempMap;
  menuList.value = res.data.filter((menu) => !menuIdSet.has(menu.parentId));
  refreshAllExpandMenuData();
  loading.value = false;
};

const getTreeselect = async () => {
  menuOptions.value = [];
  const response = await listMenu({ platformId: platformId.value });
  const menu: MenuOptionsType = { menuId: 0, menuName: '主类目', children: [] };
  menu.children = proxy?.handleTree<MenuOptionsType>(response.data, 'menuId');
  menuOptions.value.push(menu);
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = { ...initFormData };
  menuFormRef.value?.resetFields();
};

const handlePlatformChange = () => {
  getList();
};

const handleQuery = () => {
  getList();
};

/** 新增按钮操作 */
const handleAdd = (row?: MenuVO) => {
  reset();
  getTreeselect();
  if (row && row.menuId) {
    form.value.parentId = row.menuId;

    // 1. 自动填充权限标识前缀（提取父级权限的前两段）
    if (row.perms) {
      const parts = row.perms.split(':');
      if (parts.length >= 2) {
        form.value.perms = parts[0] + ':' + parts[1] + ':';
      }
    }

    // 2. 自动计算排序（父级下子项最大排序值 + 1）
    const children = menuChildrenListMap.value[row.menuId] || [];
    if (children.length > 0) {
      const maxOrder = Math.max(...children.map((c: any) => c.orderNum || 0));
      form.value.orderNum = maxOrder + 1;
    } else {
      form.value.orderNum = 1;
    }
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加菜单';
};

const handleUpdate = async (row: MenuVO) => {
  reset();
  await getTreeselect();
  if (row.menuId) {
    const { data } = await getMenu(row.menuId);
    form.value = data;
  }
  dialog.visible = true;
  dialog.title = '修改菜单';
};

const submitForm = () => {
  menuFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const menuData = { ...form.value, platformId: platformId.value };
      form.value.menuId ? await updateMenu(menuData) : await addMenu(menuData);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

const handleDelete = async (row: MenuVO) => {
  await proxy?.$modal.confirm(`是否确认删除名称为"${row.menuName}"的数据项?`);
  await delMenu(row.menuId, platformId.value);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

const deleteLoading = ref<boolean>(false);
const menuTreeRef = ref<ElTreeInstance>();
const deleteDialog = reactive<DialogOption>({
  visible: false,
  title: '级联删除菜单'
});

const handleCascadeDelete = () => {
  getTreeselect();
  deleteDialog.visible = true;
};

const cancelCascade = () => {
  deleteDialog.visible = false;
};

const submitDeleteForm = async () => {
  const menuIds = menuTreeRef.value?.getCheckedKeys();
  if (!menuIds || menuIds.length === 0) {
    proxy?.$modal.msgWarning('请选择要删除的菜单');
    return;
  }
  
  await proxy?.$modal.confirm('确定要级联删除选中的菜单及其子菜单吗？此操作不可逆！');
  deleteLoading.value = true;
  await cascadeDelMenu(menuIds, platformId.value).finally(() => (deleteLoading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
  deleteDialog.visible = false;
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.modern-tabs {
  margin-bottom: 20px;
  :deep(.el-tabs__header) {
    margin: 0 0 15px;
    border-bottom: none;
  }
  :deep(.el-tabs__item) {
    font-size: 15px;
    font-weight: 500;
    transition: all 0.3s;
    &.is-active { font-weight: 700; }
  }
}

.menu-name-text {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.icon-wrapper {
  display: inline-flex;
  width: 32px;
  height: 32px;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  background-color: #f1f5f9;
  border-radius: 6px;
  color: var(--el-color-primary);
}

.perms-code {
  background-color: #fff7ed;
  padding: 2px 8px;
  border-radius: 4px;
  font-family: 'JetBrains Mono', monospace;
  font-size: 12px;
  color: #ea580c;
  border: 1px solid #ffedd5;
}

.op-btns {
  display: flex;
  justify-content: flex-end;
  gap: 4px;
}

.delete-tree-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  padding: 12px;
  background: #fcfcfc;
}

:deep(.el-table) {
  --el-table-header-bg-color: #f8fafc;
  .el-table__expand-icon {
    font-size: 14px;
    color: var(--el-color-primary);
  }
}
</style>
