<template>
    <view>
        <up-navbar :fixed="fixed" :border="border">
            <template #left>
                <slot name="left">
                    <view class="d-flex a-c">
                        <up-icon v-if="showBack" name="arrow-left" size="40rpx" color="#333" @click="handleBackClick"></up-icon>
                        <up-icon v-else name="home" size="40rpx" color="#333" @click="handleHomeClick"></up-icon>
                        <slot name="leftText">
                            <text class="f-s-38 c-#333 f-w-500 ml-20">{{ leftText }}</text>
                        </slot>
                    </view>
                </slot>
            </template>
            <template #center>
                <slot name="center">
                    <text class="f-s-38 c-#333 f-w-500">{{ title }}</text>
                </slot>
            </template>
        </up-navbar>
        <view v-if="breadcrumb" class="bg-#EBF6EE pd2-10-24 f-s-24 c-#3FAD5B">
            <slot name="breadcrumb">
                <template v-for="(item, index) in breads" :key="index">{{ index ? ' > ' : '' }}{{ item.title }}</template>
            </slot>
        </view>
    </view>
</template>
<script lang="ts" setup>
import { usePagesStore } from '@/store/modules/pages';
import { ref, onMounted } from 'vue';
const pagesStore = usePagesStore();
const props = withDefaults(
    defineProps<{
        title?: string;
        border?: boolean;
        fixed?: boolean;
        homeUrl?: string;
        leftText?: string;
        // 是否有面包屑
        breadcrumb?: boolean;
    }>(),
    {
        title: '',
        border: true,
        fixed: true,
        homeUrl: '/pages/index/index',
        leftText: '',
        breadcrumb: true,
    }
);

const emit = defineEmits<{
    (e: 'back'): void;
    (e: 'home'): void;
}>();

const showBack = ref(false);
onMounted(() => {
    const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [];
    showBack.value = pages.length > 1;
});

function handleBackClick() {
    emit('back');
    const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [];
    if (pages.length > 1) {
        uni.navigateBack();
    } else {
        uni.switchTab({ url: props.homeUrl });
    }
}
function handleHomeClick() {
    emit('home');
    uni.switchTab({ url: props.homeUrl });
}
const breads = ref<any[]>([])
const initPages = () => {
    const pages = getCurrentPages()
    // 获取当前页面
    const currentPage: any = pages[pages.length - 1]
    if (props.title || props.leftText) {
        pagesStore.setPageTitle(currentPage.route, props.title || props.leftText);
    }
    breads.value = pages.map((item: any) => {
        const route = item.route;        
        return {
            title: pagesStore.mapPages.get(route)?.title || '未命名页面',
            route,
        }
    })
};
onMounted(() => {
  initPages();
});
</script>
