<template>
    <div class="flex flex-col w-[240px] border-r-solid-light2">
        <structure />
        <organization-tree
            ref="organizationTreeRef"
            :data="data"
            :loading="loading"
            :currentNodeKey="curSelectedNode?.id"
            @set-group-leader="setGroupLeader"
        />
    </div>
    <group-leader-dialog ref="groupLeaderDialogRef" @refresh-list="$emit('fetchTableList')" />
</template>

<script setup lang="ts">
import structure from '../components/organization/structure.vue'
import organizationTree, { type Tree } from '../components/organization/organization-tree.vue'
import groupLeaderDialog from '../components/organization/groupLeader-dialog.vue'
import { ORGANIZATION_INJECTION_KEY } from '@/config/symbol'
import type { PropType } from 'vue'
import { organzationLists } from '@/api/account_center/organization'

defineProps({
    curSelectedNode: {
        type: Object as PropType<Tree>,
        default: () => ({})
    }
})
const emit = defineEmits(['setSelectedNode', 'fetchTableList'])
const data = ref<Tree[]>([])
const loading = ref(false)
const organizationTreeRef = ref<InstanceType<typeof organizationTree>>()
const setSelectedNode = (data: Tree) => {
    emit('setSelectedNode', data)
    organizationTreeRef.value?.setCurrentKey(data)
}
const fetchOrganizationList = async () => {
    loading.value = true
    try {
        const result = await organzationLists()
        data.value = result
        loading.value = false
        data.value.length > 0 && setSelectedNode(data.value[0])
    } catch (error) {}
}
provide(ORGANIZATION_INJECTION_KEY, {
    fetchOrganizationList,
    setSelectedNode
})
fetchOrganizationList()

const groupLeaderDialogRef = ref<InstanceType<typeof groupLeaderDialog>>()
const setGroupLeader = (data: Tree) => {
    groupLeaderDialogRef.value?.openDialog({
        title: '设置组长',
        data
    })
}
</script>

<style scoped lang="scss"></style>
