<template>
    <el-scrollbar>
        <div class="hc-header-top-menu-bar">
            <template v-for="(item, index) in topMenuData" :key="index">
                <div class="item" :class="curKey === item?.code ? 'cur' : '' " @click="topMenuClick(item)">{{ item?.name }}</div>
            </template>
        </div>
    </el-scrollbar>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useAppStore } from '~src/store'
import HcTopMenu from '~src/plugins/HcTopMenu'
import { getArrValue } from 'js-fast-way'

const emit = defineEmits(['change', 'load'])

//初始组合式
const useRoutes = useRoute()
const store = useAppStore()

//处理菜单数据
const setMenuItem = async (item) => {
    emit('change', await HcTopMenu.setMenuItem(item))
}

//监听菜单数据
const topMenuData = ref([])
watch(() => store.getMenus, (val) => {
    topMenuData.value = getArrValue(val)
}, { immediate: true, deep: true })

//监听路由数据
const curKey = ref('')
watch(() => useRoutes, (val) => {
    HcTopMenu.initMenu({
        routes: val,
        menu: topMenuData.value,
        load: (key) => {
            curKey.value = key
            emit('load', key)
        },
        change: (key, item) => {
            curKey.value = key
            setMenuItem(item)
        },
    })
}, { immediate: true, deep: true })

//菜单被点击
const topMenuClick = (item) => {
    setMenuItem(item)
}
</script>

<style lang="scss">
.hc-header-top-menu-bar {
    position: relative;
    height: 100%;
    display: flex;
    align-items: center;
    .item {
        position: relative;
        cursor: pointer;
        padding: 6px 8px;
        border-radius: 3px;
        color: #efefef;
        transition: background .2s, color .2s;
        &:hover {
            color: white;
            background: var(--el-color-primary-dark-2);
        }
        &.cur {
            color: white;
            background: var(--el-color-primary-dark-2);
        }
    }
    .item + .item {
        margin-left: 2px;
    }
}
</style>
