import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, NavigationEnd, Params, Router, PRIMARY_OUTLET} from '@angular/router';
import {route} from '../../app.route';

interface IBreadcrumb {
    label: string; // 用于显示的path
    params?: Params; // 跳转的时候所带的参数
    url: string; // 跳转的url
}

@Component({
    selector: 'smart-breadcrumb',
    templateUrl: './breadcrumb.component.html',
    styles: [
            `
            .breadcrumbs {
                padding: 0 16px 16px;
            }
        `
    ]
})
export class BreadcrumbComponent implements OnInit {

    routes = route;
    public breadcrumbs: IBreadcrumb[];
    public showActionBtn: boolean;
    public showControlBth: boolean;

    constructor(private activedRoute: ActivatedRoute, private router: Router) {
        this.breadcrumbs = [];
    }

    ngOnInit() {
        const ROUTE_DATA_BREADCRUMB = 'breadcrumb';
        this.router.events.filter(event => event instanceof NavigationEnd)
            .subscribe(event => {
                let root: ActivatedRoute = this.activedRoute.root;
                console.log(root);
                this.breadcrumbs = this.getBreadcrumbs(root);
                console.log(this.breadcrumbs);
            });
    }

    getBreadcrumbs(route: ActivatedRoute, url = '', breadcrumbs: IBreadcrumb[] = []): IBreadcrumb[] {
        const ROUTE_DATA_BREADCRUMB = 'breadcrumb';
        let children: ActivatedRoute[] = route.children;
        console.log(children);
        if (children.length === 0) {
            return breadcrumbs;
        }

        // @ts-ignore
        for (let child of children) {
            if (child.outlet !== PRIMARY_OUTLET) {
                continue;
            }
            //verify the custom data property "breadcrumb" is specified on the route
            if (!child.snapshot.data.hasOwnProperty(ROUTE_DATA_BREADCRUMB)) {
                return this.getBreadcrumbs(child, url, breadcrumbs);
            }

            //get the route's URL segment
            let routeURL: string = child.snapshot.url.map(segment => segment.path).join('/');

            //append route URL to URL
            url += `/${routeURL}`;
            console.log('%c url：', 'background: #222; color: red');
            console.log(url);

            //add breadcrumb
            let breadcrumb: IBreadcrumb = {
                label: child.snapshot.data[ROUTE_DATA_BREADCRUMB],
                params: child.snapshot.params,
                url: '/app' + url   // 这个app是根据自己的跳转路由加的，不然点面包屑死活不跳呀
            };
            console.log('%c single breadcrumb：', 'background: #222; color: red');
            console.log(breadcrumb);

            breadcrumbs.push(breadcrumb);
            //recursive
            return this.getBreadcrumbs(child, url, breadcrumbs);
        }
        return breadcrumbs;
    }
}
