<!-- 动态组件 -->
<template>
    <app-tabs :data-list="dataList" v-model:data-index="dataIndex" prop-label="title" @change="onTabChange">
        <template #navbar>
            <slot></slot>
        </template>
        <component :is="componentMap.get(componentId)" :code="componentId" v-bind="options" v-if="componentId" />
    </app-tabs>
</template>

<script lang="ts" setup>
import { shallowRef, PropType, onMounted, useAttrs, computed } from 'vue'
import { useMenu } from '@/hooks/menu'
import AppTabs from '@/components/base/tabs/index.vue'

const props = defineProps({
    code: String,
    options: Object,
    // 过滤标签
    tabs: {
        type: Array as PropType<string[]>,
        default: () => ([]),
    },
    // 选中的标签
    selectedTab: {
        type: String,
        default: '',
    },
})

const { componentMap, getAuthComponents } = useMenu(props.code)
const { onChange } = useAttrs()
const dataList = shallowRef<Model.MenusRsp[]>([]) // 数据列表
const dataIndex = shallowRef(0) // 选中的标签

const componentId = computed(() => dataList.value[dataIndex.value]?.resourceCode)

const onTabChange = (index: number, { resourceCode }: Model.MenusRsp) => {
    if (onChange instanceof Function) {
        onChange(resourceCode)
    } else {
        dataIndex.value = index
    }
}

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

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

    const tabIndex = dataList.value.findIndex((e) => e.resourceCode === props.selectedTab)
    if (tabIndex > -1) {
        dataIndex.value = tabIndex
    }
})
</script>