<template>
  <div
    class="overflow-hidden bg-white h-full rounded-2xl"
    :style="{ 'border-right': '1px solid #e5e7eb' }"
  >
    <BasicTree
      :title="t('组织列表')"
      toolbar
      search
      switcher
      :clickRowToExpand="true"
      :treeData="treeData"
      :selectedKeys="selectedKeys"
      expandOnSearch
      :fieldNames="{ key: 'id', title: 'name' }"
      @select="handleSelect"
    >
      <template #title="{ name, departmentType }">
        <a-tag color="processing" v-if="departmentType === 1">公司</a-tag>
        <a-tag color="orange" v-else-if="departmentType === 0">部门</a-tag>
        {{ name }}
      </template>
    </BasicTree>
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import { getDepartmentTree } from '/@/api/system/department';

  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree },

    emits: ['select'],
    setup(_, { emit }) {
      const treeData = ref<TreeItem[]>([]);
      const selectedKeys = ref<string[]>([]);

      async function fetch() {
        treeData.value = (await getDepartmentTree()) as unknown as TreeItem[];
        let id = treeData.value[0].id;
        selectedKeys.value.push(id);
        emit('select', id);
      }

      function handleSelect(keys: string) {
        emit('select', keys[0]);
      }

      onMounted(() => {
        fetch();
      });
      return { treeData, handleSelect, selectedKeys, t };
    },
  });
</script>
