<!-- 动态组件 -->
<template>
    <div :class="['app-auth-component', direction]">
        <div class="auth-navbar">
            <ul class="tabs" v-if="dataList.length">
                <li :class="['tabs-item', item.code === componentId && 'is-active']" v-for="(item, index) in dataList"
                    :key="index" @click="onTabChange(item.code)">
                    {{ item.title }}
                </li>
            </ul>
            <slot></slot>
        </div>
        <div class="auth-container">
            <component :is="componentMap.get(componentId)" :code="componentId" v-bind="options" v-if="componentId" />
        </div>
    </div>
</template>

<script lang="ts" setup>
import { shallowRef, PropType, onMounted, useAttrs } from 'vue'
import { useAuth } from '@/hooks/auth'

const props = defineProps({
    code: String,
    options: Object,
    // 组件方向
    direction: {
        type: String as PropType<'top' | 'bottom' | 'left' | 'right'>,
        default: 'top',
    },
    // 过滤标签
    tabs: {
        type: Array as PropType<string[]>,
        default: () => ([]),
    },
    // 选中的标签
    selectedTab: {
        type: String,
        default: '',
    },
})

const { componentMap, getAuthComponent } = useAuth(props.code)
const { onChange } = useAttrs()
const componentId = shallowRef<string>()
const dataList = shallowRef<Ermcp.UserMenu[]>([]) // 数据列表

const onTabChange = (code: string) => {
    if (componentId.value !== code) {
        if (onChange instanceof Function) {
            onChange(code)
        } else {
            componentId.value = code
        }
    }
}

onMounted(() => {
    const auth = getAuthComponent();

    if (props.tabs.length) {
        dataList.value = auth.filter((e) => props.tabs.includes(e.code))
    } else {
        dataList.value = auth
    }

    const tabItem = dataList.value.find((e) => e.code === props.selectedTab)

    if (tabItem) {
        componentId.value = tabItem.code
    } else {
        componentId.value = dataList.value[0]?.code
    }
})
</script>

<style lang="less">
@import './index.less';
</style>