<template>
  <VerticalFlexLayout>
    <template #static>
      <Breadcrumb />
    </template>
    <div>
      <div>
        <div class="search"
          ><span class="searchLabel"> 搜索：</span><el-input v-model="searchKey" placeholder="请输入关键字进行搜索" />
        </div>
        <el-table :data="filterData" row-key="id" :tree-props="treeProps" default-expand-all style="padding: 0 20px">
          <el-table-column label="组织名称">
            <template #default="{ row }">
              {{ `${row.deptName} (${row.userCount})` }}
            </template>
          </el-table-column>
        </el-table>
      </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' });
  });

  function reloadTable() {
    loadDataTable();
  }

  onMounted(() => {
    loadDataTable();
  });
</script>
<style 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;
    }
  }
</style>
