<template>
  <PageWrapper>
    <el-row :gutter="12">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <el-space>
              <el-button type="primary" icon-placement="left" @click="openCreateDrawer">
                添加菜单
                <template #icon>
                  <div class="flex items-center">
                    <el-icon size="14">
                      <FileAddOutlined />
                    </el-icon>
                  </div>
                </template>
              </el-button>

              <el-button type="primary" plain icon-placement="left" @click="packHandle">
                全部{{ expandedKeys.length ? '收起' : '展开' }}
                <template #icon>
                  <div class="flex items-center">
                    <el-icon size="14">
                      <AlignLeftOutlined />
                    </el-icon>
                  </div>
                </template>
              </el-button>
            </el-space>
          </template>
          <div class="w-full menu">
            <div class="menu-list" v-loading="loading">
              <el-scrollbar height="620px">
                <el-tree
                  ref="treeRef"
                  :pattern="pattern"
                  :data="menuTree"
                  nodeKey="id"
                  highlight-current
                  check-strictly
                  :expand-on-click-node="false"
                  @current-change="onSelectTreeItem"
                  @update:expanded-keys="onExpandedKeys"
                />
              </el-scrollbar>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="hover">
          <template #header>
            <div class="flex justify-between">
              <el-space>
                <span>编辑菜单 {{ treeItemTitle ? `：${treeItemTitle}` : '' }}</span>
              </el-space>
              <el-popconfirm
                @confirm="handleDeleteMenu"
                v-if="isEditMenu"
                :title="`确定要删除菜单${treeItemTitle}吗？`"
              >
                <template #reference>
                  <el-button type="danger" size="small">删除菜单</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
          <!-- 表单 -->
          <div class="pt-6">
            <MenuForm
              v-show="selectedMenuId != null"
              ref="menuFormRef"
              :parent-menu-tree="menuTree"
              @change="handleMenuChange"
              class="w-2/3 ml-10"
              isShowSubmit
            />
            <el-empty v-show="selectedMenuId == null" description="从左侧列表选择一项后，进行编辑" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :parent-menu-tree="menuTree"
      @change="handleMenuChange"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, onMounted, shallowRef } from 'vue';
  import { ElMessage } from 'element-plus';
  import { AlignLeftOutlined, FileAddOutlined } from '@vicons/antd';
  import { deleteMenu } from '@/api/system/menu';
  import { queryFullMenuTree } from '@/api/system/menu';
  import { MenuDetailTree, MenuTree, MenuDetail, Menu } from '@/types/menu/type';
  import { getTreeItem } from '@/utils';
  import CreateDrawer from './CreateDrawer.vue';
  import MenuForm from './MenuForm.vue';
  import { cloneDeep } from 'lodash-es';

  const menuDetailTree = shallowRef<MenuDetailTree>([]); // 菜单详情树
  const menuTree = shallowRef<MenuTree>([]); // 菜单树，用于展示
  const selectedMenuId = ref<MenuDetail['id']>(null); // 选中的菜单
  const loading = ref(true); // 左侧菜单树加载
  const expandedKeys = ref([]); 
 
  const isEditMenu = ref(false); 
  const treeItemTitle = ref('');
  const pattern = ref('');
  const drawerTitle = ref('');

  // 组件实例引用
  const createDrawerRef = ref();
  const treeRef = ref();
  const menuFormRef = ref();

  function clearEditing() {
    selectedMenuId.value = null;
    isEditMenu.value = false;
    treeItemTitle.value = '';
    expandedKeys.value = [];
  }

  function handleDeleteMenu() {
    const treeItem = getTreeItem(menuTree.value, selectedMenuId.value!, 'id') as Menu;
    if (treeItem?.children && treeItem?.children.length) {
      ElMessage.error('当前结节含有子节点，无法删除');
      return;
    }

    deleteMenu(selectedMenuId.value!).then(() => {
      ElMessage.success('删除成功');
      clearEditing();
      menuFormRef.value.handleReset();
      getMenuTree();
    });
  }

  function openCreateDrawer() {
    drawerTitle.value = '添加菜单';
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  async function onSelectTreeItem(checkedInfo: Menu) {
    const currentMenuId = checkedInfo.id as number;
    selectedMenuId.value = currentMenuId;

    if (currentMenuId) {
      const menu: Menu = getTreeItem(menuTree.value, currentMenuId, 'id');
      treeItemTitle.value = menu.label;

      const menuDetail: MenuDetail = getTreeItem(menuDetailTree.value, currentMenuId, 'id');
      const menuFormData = cloneDeep(menuDetail);
      delete menuFormData.children;
      // console.log('menu form data', menuFormData)
      menuFormRef.value.setData(menuFormData);

      isEditMenu.value = true;
      treeRef.value.setCheckedKeys([currentMenuId]);
    }
  }

  function treeNodeExpand(status) {
    for (var i = 0; i < treeRef.value.store._getAllNodes().length; i++) {
      treeRef.value.store._getAllNodes()[i].expanded = status;
    }
  }

  function packHandle() {
    if (!expandedKeys.value.length) {
      treeNodeExpand(true);
      expandedKeys.value = menuTree.value?.map((item: any) => item.key as string) as [];
    } else {
      expandedKeys.value = [];
      treeNodeExpand(false);
    }
  }

  /**
   * 获取 菜单树。一个菜单详细树，用于创建和编辑菜单。 一个是展示树，用于 el-tree 组件
   * 注意：原来的 getPermissionList 重新命名为 getMenuTree
   */
  async function getMenuTree() {
    loading.value = true;
    menuDetailTree.value = await queryFullMenuTree();
    menuTree.value = transformToSimpleMenus(menuDetailTree.value);
    loading.value = false;
  }

  function transformToSimpleMenus(menus: MenuDetailTree | null): MenuTree {
    if (menus == null) {
      return [];
    }
  
    const tree: MenuTree = [];
    for (const item of menus) {
      const treeItem: Menu = { 
        id: item.id!, 
        label: item.menuName, 
        routeName: item.routeName,
        children: null
      };

      if (Array.isArray(item.children) && item.children?.length > 0) {
        treeItem.children = transformToSimpleMenus(item.children);
        tree.push(treeItem);
      } else {
        tree.push(treeItem);
      }
    }

    return tree;
  }

  async function handleMenuChange() {
    getMenuTree();
    clearEditing();
  }

  onMounted(async () => {
    getMenuTree();
  });

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }
</script>

