<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="treeData"
                  nodeKey="key"
                  highlight-current
                  check-strictly
                  @current-change="selectedTree"
                  @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>编辑{{ getTypeMsg }}{{ treeItemTitle ? `：${treeItemTitle}` : '' }}</span>
                <el-divider direction="vertical" />
                <p depth="3" class="text-sm"> 从左侧列表选择一项后，进行编辑 </p>
              </el-space>
              <el-popconfirm
                @confirm="handleDeleteMenu"
                v-if="isEditMenu"
                :title="`确定要删除 ${treeItemTitle} ${getTypeMsg}吗？`"
              >
                <template #reference>
                  <el-button type="danger" size="small">删除{{ getTypeMsg }}</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
          <!-- 表单 -->
          <div v-loading="loadingR" class="pt-6">
            <MenuForm
              ref="menuFormRef"
              :permissionList="treeData"
              @change="menuChange"
              class="w-2/4 ml-10"
              isShowSubmit
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :permissionList="treeData"
      @change="menuChange"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { AlignLeftOutlined, FileAddOutlined } from '@vicons/antd';
  import { menuInfo, deleteMenu } from '@/api/system/menu';
  import { permissionList } from '@/api/system/role';
  import { getTreeItem } from '@/utils';
  import CreateDrawer from './CreateDrawer.vue';
  import MenuForm from './MenuForm.vue';

  const createDrawerRef = ref();
  const treeRef = ref();
  const message = ElMessage;

  let expandedKeys = ref([]);

  const treeData = ref([]);

  const loading = ref(true);
  const loadingR = ref(false);

  const isEditMenu = ref(false);
  const treeItemTitle = ref('');
  const pattern = ref('');
  const drawerTitle = ref('');
  const menuFormRef = ref();

  const menuTypeMsg = ref(['目录', '菜单', '按钮']);

  const formParams = ref({
    id: null,
    parentId: 0,
    activeMenu: '',
    affix: false,
    alwaysShow: true,
    icon: '',
    isCache: 1,
    isFrame: 1,
    isVisible: 0,
    menuName: '',
    menuType: 0,
    openType: 1,
    status: 0,
    orderNum: null,
    permissionCode: '',
    permissionName: '',
    query: '',
    routeUrl: '',
    routeName: '',
    component: '',
    redirect: '',
  });

  const getTypeMsg = computed(() => {
    return menuTypeMsg.value[formParams.value.menuType];
  });

  function handleDeleteMenu() {
    deleteMenu({ permissionId: formParams.value.id }).then(() => {
      message.success('删除成功');
      isEditMenu.value = false;
      treeItemTitle.value = '';
      menuFormRef.value.handleReset();
      getPermissionList();
    });
  }

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

  async function selectedTree(checkedInfo) {
    const currentKey = checkedInfo.key;
    if (currentKey) {
      const treeItem = getTreeItem(unref(treeData), currentKey);
      treeItemTitle.value = treeItem.label;
      loadingR.value = true;
      const info = await menuInfo({ permissionId: currentKey });
      const newMenuInfo = {
        id: info.id,
        parentId: info.parentId,
        activeMenu: info.activeMenu,
        affix: info.affix,
        alwaysShow: info.alwaysShow,
        component: info.component,
        icon: info.icon,
        isCache: info.isCache,
        isFrame: info.isFrame,
        isVisible: parseInt(info.visible),
        menuName: info.menuName,
        menuType: info.menuType,
        openType: info.openType,
        status: parseInt(info.status),
        orderNum: info.orderNum,
        permissionCode: info.permissionCode,
        permissionName: info.permissionName,
        query: info.query,
        routeUrl: info.routeUrl,
        routeName: info.routeName,
        redirect: info.redirect,
        frameSrc: info.frameSrc,
        isRoot: info.isRoot,
      };
      formParams.value = newMenuInfo;
      menuFormRef.value.setData(newMenuInfo);
      isEditMenu.value = true;
      loadingR.value = false;
      treeRef.value.setCheckedKeys([currentKey]);
    }
  }

  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 = treeData.value?.map((item: any) => item.key as string) as [];
    } else {
      expandedKeys.value = [];
      treeNodeExpand(false);
    }
  }

  async function getPermissionList() {
    loading.value = true;
    const list = await permissionList();
    treeData.value = list;
    loading.value = false;
  }

  async function menuChange() {
    getPermissionList();
    treeItemTitle.value = '';
    isEditMenu.value = false;
  }

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

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

<style lang="scss" sctep></style>
