<template>
  <div class="page-container">
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">菜单管理</span>
          </div>
          <div class="header-right">
            <el-input
              v-model="queryParams.menuName"
              placeholder="搜索菜单名称"
              class="search-input"
              prefix-icon="Search"
              clearable
              @keyup.enter="handleQuery"
            />
            <el-select v-model="queryParams.status" placeholder="状态" class="status-select" clearable @change="handleQuery">
              <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
            <el-button type="primary" icon="Plus" @click="handleAdd()">新增菜单</el-button>
            <el-button type="danger" plain icon="Delete" @click="handleCascadeDelete" :loading="deleteLoading">级联删除</el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="platformId" @tab-change="handlePlatformChange" class="custom-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: '#606266' }"
        :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-button link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button link type="primary" @click="handleAdd(scope.row)">新增</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </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 dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const menuFormRef = 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 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;
  }
  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">
.page-container {
  padding: 20px;
  background-color: #f5f7f9;
  min-height: 100%;
}

.table-card {
  border: none;
  border-radius: 8px;
  
  :deep(.el-card__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  .title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.header-right {
  display: flex;
  gap: 12px;
  
  .search-input { width: 220px; }
  .status-select { width: 120px; }
  
  :deep(.el-input__wrapper) {
    background-color: #f4f5f7;
    box-shadow: none;
    border: 1px solid transparent;
    
    &:hover, &.is-focus {
      border-color: #409eff;
      background-color: #fff;
    }
  }
}

.custom-tabs {
  margin-bottom: 16px;
  :deep(.el-tabs__nav-wrap::after) { height: 1px; }
  :deep(.el-tabs__header) { margin-bottom: 0; }
}

.menu-name-text {
  font-weight: 600;
  color: #333;
}

.icon-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  color: #606266;
}

.perms-code {
  background-color: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
  color: #e6a23c;
}

.path-text {
  color: #909399;
  font-size: 13px;
}

.status-tag { border: none; font-weight: 500; }

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

.delete-tree-container {
  max-height: 450px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

:deep(.el-table) {
  --el-table-border-color: #f0f0f0;
  th.el-table__cell { font-weight: 600; }
  td.el-table__cell { padding: 12px 0; }
}
</style>
