<template>
  <div class="page-permission">
    <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">
            <div v-loading="loading">
              <el-scrollbar height="620px">
                <el-tree
                  ref="treeRef"
                  :data="permissionViewTree"
                  nodeKey="value"
                  highlight-current
                  check-strictly
                  @current-change="onSelectTreeNode"
                  @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>编辑权限: </span>
                <span>{{ treeItemTitle }}</span>
              </el-space>
              <el-popconfirm v-if="isEditing" :title="`确定要删除${treeItemTitle}吗？`" width="200" @confirm="handleDeletePermission">
                <template #reference>
                  <el-button type="danger" size="small">删除权限</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
          <!-- 表单 -->
          <div class="pt-6">
            <PermissionForm
              v-show="selectedPermissionId != null"
              ref="formInstance"
              :permissionList="permissionViewTree"
              @change="handleChangePermssion"
              isShowSubmit
              class="w-2/3 ml-10"
            />
            <el-empty v-show="selectedPermissionId == null" description="从左侧列表选择一项后，进行编辑" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加新权限 -->
    <CreateDrawer
      ref="drawerInstance"
      :permissionList="permissionViewTree"
      @change="handleChangePermssion"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, shallowRef, onMounted } from 'vue';
  import PermissionForm from './PermissionForm.vue';
  import CreateDrawer from './CreateDrawer.vue';
  import { AlignLeftOutlined, FileAddOutlined } from '@vicons/antd';
  import { PermissionTree, PermissionView, PermissionViewItem, PermissionViewTree, Permission } from '@/types/permission/type';
  import { getPermissionTree, deletePermission } from '@/api/system/permission';
  import { getTreeItem } from '@/utils';
  import { cloneDeep } from 'lodash-es';
import { ElMessage } from 'element-plus';
  

  // 左侧权限树相关
  const expandedKeys = ref<PermissionViewItem['value'][]>([]);
  const loading = ref(true);
  const treeRef = ref();
  const permissionTree = shallowRef<PermissionTree>([]);
  const permissionViewTree = shallowRef<PermissionViewTree>([]);

  // 右侧编辑菜单相关
  const treeItemTitle = ref('');
  const isEditing = ref(false);
  const selectedPermissionId = ref<number | null>(null);
  const formInstance = ref<InstanceType<typeof PermissionForm>>();

  // 抽屉相关
  const drawerInstance = ref<InstanceType<typeof CreateDrawer>>();

  const queryPermissionTree = async () => {
    loading.value = true;
    try {
      permissionTree.value = await getPermissionTree();
      permissionViewTree.value = transformToViewTree(permissionTree.value);
    } catch (e) {
      console.error(e);
    } finally {
      loading.value = false;
    }
  };

  const transformToViewTree = (tree: PermissionTree | null): PermissionViewTree => {
    if (tree == null) return [];

    const viewTree: PermissionViewTree = [];
    for (const item of tree) {
      const viewItem: PermissionView = {
        value: item.id!,
        label: item.permissionName,
      };

      if (Array.isArray(item.children) && item.children.length > 0) {
        viewItem.children = transformToViewTree(item.children);
        viewTree.push(viewItem);
      } else {
        viewTree.push(viewItem);
      }
    }

    return viewTree;
  };

  const onSelectTreeNode = (data: PermissionView, node: any) => {
    console.log(node);

    const permissionId = data.value as number;
    selectedPermissionId.value = permissionId;
    isEditing.value = true;
    treeItemTitle.value = data.label;
      
    const treeItem: Permission = getTreeItem(permissionTree.value, permissionId, 'id');
    const permission = cloneDeep(treeItem);
    delete permission.children;
    formInstance.value?.setData(permission);
  };

  /**
   * 左侧权限树 展开 / 收起
   */
  const packHandle = () => {
    if (!expandedKeys.value.length) {
      treeNodeExpand(true);
      expandedKeys.value = permissionViewTree.value?.map((item) => item.value);
    } else {
      expandedKeys.value = [];
      treeNodeExpand(false);
    }
  };

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

  const onExpandedKeys = (keys) => {
    expandedKeys.value = keys;
  };


  function clearEditing() {
    isEditing.value = false;
    treeItemTitle.value = '';
    selectedPermissionId.value = null;
  }

  /**
   * 编辑权限，或者 新建权限 后的 change 事件处理
   */
  const handleChangePermssion = () => {
    clearEditing();
    queryPermissionTree();
  };


  /**
   * 不允许删除父节点
   */
  const handleDeletePermission = async () => {
    const treeItem: Permission = getTreeItem(permissionTree.value, selectedPermissionId.value!, 'id');
    if (treeItem.children && treeItem.children.length > 0) {
      ElMessage.error('当前权限含有子权限，无法删除');
      return;
    }

    try {
      await deletePermission(selectedPermissionId.value!);
      clearEditing();
      queryPermissionTree();
    } catch(e) {
      console.error(e);
    }
  }

  function openCreateDrawer() {
    drawerInstance.value?.openDrawer();
  }

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

<style scoped>
  .page-permission {
    height: calc(100vh - 100px);
  }
</style>
