<template>
  <VerticalFlexLayout>
    <template #static>
      <Breadcrumb />
    </template>
    <PageWrapper style="background: #fff; height: 100%; width: 100%">
      <div class="main_page">
        <div class="left_panel">
          <div class="left_top">
            <el-space>
              <el-button type="primary" icon-placement="left" @click="openCreateDrawer" style="margin-left: 20px">
                添加权限
                <template #icon>
                  <div class="flex items-center">
                    <el-icon size="14">
                      <FileAddOutlined />
                    </el-icon>
                  </div>
                </template>
              </el-button>

              <el-button type="primary" 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>
          </div>
          <div class="w-full" style="margin-top: 20px; margin-left: 20px">
            <div v-loading="loading">
              <el-scrollbar height="620px">
                <el-tree
                  ref="treeRef"
                  :data="permissionViewTree"
                  nodeKey="value"
                  highlight-current
                  check-strictly
                  :expand-on-click-node="false"
                  @current-change="onSelectTreeNode"
                  @update:expanded-keys="onExpandedKeys"
                />
              </el-scrollbar>
            </div>
          </div>
        </div>
        <div class="right_panel">
          <div class="right_top">
            <div class="editPermission" style="align-items: center">
              <el-space>
                <span style="color: #303133; margin-left: 20px">编辑权限 </span>
                <span v-if="treeItemTitle" style="color: #303133">：{{ treeItemTitle }}</span>
              </el-space>
              <el-popconfirm
                v-if="isEditing"
                :title="`确定要删除${treeItemTitle}吗？`"
                width="200"
                @confirm="handleDeletePermission"
              >
                <template #reference>
                  <el-button type="danger" size="small" style="margin-left: 50px; align-items: center"
                    >删除权限</el-button
                  >
                </template>
              </el-popconfirm>
            </div>
          </div>
          <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>
        </div>
      </div>
      <CreateDrawer ref="drawerInstance" :permissionList="permissionViewTree" @change="handleChangePermssion" />
    </PageWrapper>
  </VerticalFlexLayout>
</template>

<script setup lang="ts">
  import { ref, shallowRef, onMounted } from 'vue';
  import PermissionForm from './PermissionForm.vue';
  import CreateDrawer from './CreateDrawer.vue';
  import { PageWrapper } from '@/components/Page';
  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';
  import Breadcrumb from '@/components/Breadcrumb.vue';
  import VerticalFlexLayout from '@/components/VerticalFlexLayout.vue';

  // 左侧权限树相关
  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;
    expandedKeys.value = [];
  }

  /**
   * 编辑权限，或者 新建权限 后的 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 - 173px);
    background-color: #fff;
  }
  .editPermission {
    display: flex;
    justify-content: space-between;
  }
</style>
<style lang="scss" scoped>
  .main_page {
    width: 100%;
    height: calc(100vh - 160px);
    position: relative;
    display: flex;
    flex-direction: row;
    .left_panel {
      width: 25%;
      height: 100%;
      position: relative;
      display: flex;
      flex-direction: column;
      border-right: 1px solid #eaeaea;
      .left_top {
        width: 100%;
        // height: 69px;
        padding-top: 18px;
        padding-bottom: 18px;
        position: relative;
        display: flex;
        flex-direction: row;
        border-bottom: 1px solid #eaeaea;
      }
    }
    .right_panel {
      width: 75%;
      height: 100%;
      position: relative;
      display: flex;
      flex-direction: column;
      .right_top {
        width: 100%;
        height: 69px;
        position: relative;
        display: flex;
        flex-direction: row;
        border-bottom: 1px solid #eaeaea;
      }
    }
  }
</style>
