<template>
  <VerticalFlexLayout>
    <template #static>
      <Breadcrumb />
    </template>
    <div>
      <div>
        <div class="search"
          ><span class="searchLabel"> 搜索：</span><el-input v-model="searchKey" placeholder="请输入关键字进行搜索" />
        </div>
        <el-tree :data="filterData" :render-content="renderTree" style="padding: 0 20px" default-expand-all />
      </div>

      <CreateDrawer
        ref="createDrawerRef"
        :title="drawerTitle"
        :deptList="tableData"
        :data-source="currentDept"
        :width="450"
        @change="reloadTable"
      />
    </div>
  </VerticalFlexLayout>
</template>

<script lang="ts" setup>
  import { computed, onMounted, reactive, ref } from 'vue';
  import { PageWrapper } from '@/components/Page';
  import { getAllDepartments } from '@/api/auth/dept';
  import CreateDrawer from './CreateDrawer.vue';
  import type { DeptTree, DeptTreeItem } from '@/types/dept/type';
  import { filterTree } from '@/utils/tree';
  import Breadcrumb from '@/components/Breadcrumb.vue';
  import VerticalFlexLayout from '@/components/VerticalFlexLayout.vue';

  const tableData = ref<DeptTree[]>([]);
  const treeProps = reactive({
    checkStrictly: false,
  });
  const createDrawerRef = ref();
  const searchKey = ref('');
  const drawerTitle = ref('添加部门');
  const currentDept = ref<DeptTreeItem>({
    id: null,
    deptName: '',
    parentId: null,
    orderNum: undefined,
    createdBy: 0,
    updatedBy: 0,
    createdAt: '',
    updatedAt: '',
    isDeleted: 0,
    tenantId: 0,
    userCount: 0,
  });

  const loadDataTable = async () => {
    const result = await getAllDepartments();
    tableData.value = result;
  };

  const filterData = computed(() => {
    if (!searchKey.value) {
      return tableData.value;
    }
    return filterTree({ nodes: tableData.value, value: searchKey.value, key: 'deptName' });
  });

  const renderTree = (h, { node, data }) => {
    console.log({ node, data });
    return h('span', { class: 'deptContent' }, `${data.deptName} (${data.userCount})`);
  };

  function reloadTable() {
    loadDataTable();
  }

  onMounted(() => {
    loadDataTable();
  });
</script>
<style lang="scss" scoped>
  .el-space--horizontal {
    align-items: center;
    gap: 0px 20px;
  }

  .el-tooltip__trigger {
    width: 16px;
  }

  .tooltip__password {
    color: var(--el-color-primary);
  }

  .box-item {
    position: absolute;
    top: 0;
    right: 0;
  }

  .el-space__item:hover {
    cursor: pointer;
  }
  .search {
    margin: 20px;
    margin-top: 0;
    padding-top: 20px;
    width: 300px;
    display: flex;
    align-items: center;
    .searchLabel {
      width: 65px;
    }
  }

  .deptContent {
    font-size: 14px;
  }
</style>
