<template>
    <div class="hc-top-menu-box">
        <el-scrollbar>
            <div class="hc-flex">
                <template v-for="(item, index) in topMenuData" :key="index">
                    <div class="hc-top-menu-item hc-flex text-4.5" :class="curKey === item?.code ? 'cur' : '' " @click="topMenuClick(item)">
                        <HcIcon v-if="item?.source" :name="item?.source" :fill="curKey === item?.code" class="mr-1" />
                        <span class="name">{{ item?.name }}</span>
                    </div>
                </template>
            </div>
        </el-scrollbar>
    </div>
</template>

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

const emit = defineEmits(['change'])
//初始组合式
const useRoutes = useRoute()
const useAppState = useAppStore()

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

//监听路由数据
const curKey = ref('')
watch(() => useRoutes, (obj) => {
    const topMenuName = obj.matched[0]?.name
    const menus = topMenuData.value
    for (let i = 0; i < menus.length; i++) {
        if (menus[i].code === topMenuName) {
            emit('change', menus[i].children)
        }
    }
    curKey.value = topMenuName
}, { immediate: true, deep: true })

//菜单被点击
const topMenuClick = (item) => {
    emit('change', item.children)
}
</script>

<style lang="scss">
.hc-top-menu-box {
    position: relative;
    height: 100%;
    .hc-top-menu-item {
        color: #303133;
        cursor: pointer;
        transition: color .2s;
        &:hover {
            color: var(--el-color-primary-light-5);
        }
        &.cur {
            color: var(--el-color-primary);
        }
    }
    .hc-top-menu-item + .hc-top-menu-item {
        margin-left: 24px;
    }
}
</style>
