<template>
    <el-breadcrumb separator="/">
        <template v-for="(item,index) in list">
            <el-breadcrumb-item :key="index" v-if="index < list.length - 1" :to="{ path: item.path }">{{ item.title }}</el-breadcrumb-item>
            <el-breadcrumb-item :key="index" v-else>{{ item.title }}</el-breadcrumb-item>
        </template>
    </el-breadcrumb>
</template>

<script>
import { config } from '@/config'

export default {
    name: 'Breadcrumb',
    data() {
        return {
            list: []
        }
    },
    computed: {
        menus() {
            return this.$router.options.routes
        },
        useAnimate() {
            return this.$store.state.app.useAnimate
        },
    },
	watch: {
		$route() {
			this.getBreadcrumbList()
		}
	},
    mounted() {
        setTimeout(() => {
            this.getBreadcrumbList()
        }, 500);
    },
    methods: {
        updateTitle() {
            let title = config.title
            if (this.list.length > 0) {
                title = this.list[this.list.length - 1].title + '' + title
            }
            document.title = title
        },
        findMenu(path, data) {
            if (!data) {
                data = this.menus
            }
            for (let i = 0; i < data.length; i++) {
                const item = data[i]
                if (path === item.path) {
                    return item
                }
                if (item.children) {
                    for (let j = 0; j < item.children.length; j++) {
                        const child = item.children[j]
                        if (path === child.path) {
                            return child
                        }
                    }
                }
            }
            return null
        },
        getBreadcrumbList() {
            const matched = this.$route.matched.filter(item => item.meta && item.meta.name)
            const res = []
            const vm = this
            matched.map(item => {
                if (item.meta.parent) {
                    const parent = vm.findMenu(item.meta.parent)
                    if (parent) {
                        res.push({
                            title: parent.meta.name,
                            path: parent.path
                        })
                    }
                }
                res.push({
                    title: item.meta.name,
                    path: item.path
                })
            })
            this.list = res
        },
        handleLoadPath(path) {
            this.$router.push(path)
        }
    }
}
</script>

<style lang="scss" scoped>
.el-breadcrumb {
    display: flex;
    align-items: center;
}
</style>