<template>
    <Menu :indexPath="indexPath()" router @select="onSelect" :class="bem()">
        <template v-for="item in navs">
            <menu-item
                v-if="!item.children || item.children.length === 0"
                :key="item.id"
                :index="transformUrl(item.link)"
                :route="transformUrl(item.link)"
            >
                <span>{{item.title}}</span>
            </menu-item>
            <sub-menu
                v-else
                :key="item.id"
                :index="transformUrl(item.link)"
                :route="transformUrl(item.link)"
                @show="$emit('sub-menu:show', item.id, item)"
                @hide="$emit('sub-menu:hide', item.id, item)"
                placement="bottom-start"
                offset="-36px, 0, 0, 0"
                :hide-menu="_isHideMenu(item)"
                :title="item.title"
                :popover-class="bem('popover')"
            >
                <menu-item
                    v-for="menu in item.children"
                    :key="menu.id"
                    :index="transformUrl(item.link)"
                    :route="transformUrl(menu.link)"
                >
                    <badge v-if="menu.is_new" value="New">{{menu.title}}</badge>
                    <span v-else>{{menu.title}}</span>
                </menu-item>
            </sub-menu>
        </template>
    </Menu>
</template>

<script>
import { createComponentName, componentMixin } from '../_utils/component';
import request from '../request';
import Menu from '../Menu';
import SubMenu from '../Menu/SubMenu';
import MenuItem from '../Menu/Item';
import Badge from '../Badge';
import defaultData from './default-data';
import { toRelativePath, includeUrl } from '../_utils/url';
const cacheKey = 'gaoding-navigation';

// FIXME: 目前写的有点混乱
export default {
    name: createComponentName('navigation'),
    components: { Menu, SubMenu, MenuItem, Badge },
    mixins: [componentMixin],
    props: {
    // 当前页面的域名, 会将相同域名的地址转换为相对路径
        host: {
            type: String
        },
        // 是否隐藏二级菜单
        isHideMenu: {
            type: Function
        },
        // 修改激活状态的路由
        transformValue: {
            type: Function
        }
    },
    data() {
        return {
            navs: [...defaultData]
        };
    },
    watch: {
        $route() {
            this.$forceUpdate();
        }
    },
    beforeMount() {
        try {
            if (localStorage.getItem(cacheKey)) {
                // 简单处理, 暂时不考虑缓存时间
                const data = JSON.parse(localStorage.getItem(cacheKey));
                this.navs = data;
            }
        }
        catch (error) {
            console.error(error);
        }
    },
    mounted() {
        request.get('/api/navigations').then(res => {
            this.navs = res.data.filter(d => d.title);

            try {
                localStorage.setItem(cacheKey, JSON.stringify(res.data));
            }
            catch (error) {
                console.error(error);
            }
        });
    },
    methods: {
        indexPath() {
            if (!this.$isServer) {
                const value = this.getIndexPath(this.navs, []);
                if (this.transformValue) return this.transformValue(value, this);
                return value;
            }
            return [];
        },
        _isHideMenu(nav) {
            if (!this.isHideMenu) return false;
            return this.isHideMenu(
                this.transformUrl(nav.link),
                this.indexPath(),
                nav
            );
        },
        getIndexPath(navs, value) {
            for (const nav of navs) {
                if (this.includeHref(nav.link)) {
                    value.push(this.transformUrl(nav.link));
                    return value;
                }
                else if (nav.children) {
                    const v = this.getIndexPath(nav.children, [
                        ...value,
                        this.transformUrl(nav.link)
                    ]);
                    if (v.length) return v;
                }
            }
            return [];
        },
        transformUrl(url) {
            return toRelativePath(url, this.host);
        },
        includeHref(url) {
            let href = this.host
                ? location.protocol +
          '//' +
          this.host +
          location.pathname +
          location.search
                : location.href;
            return includeUrl(href, url);
        },
        onSelect(index, indexPath) {
            const data = indexPath.reduce((navs, link, index) => {
                if (!Array.isArray(navs)) return navs;

                const nav = navs.find(nav => nav.link === link);

                if (nav) return index === indexPath.length - 1 ? nav : nav.children;

                return nav;
            }, this.navs);
            /**
       * 当选择时触发
       * @arg index: {string} menu-item索引
       * @arg indexPath: {string[]} 完整路径
       */
            this.$emit('select', index, indexPath, data);
        }
    }
};
</script>

<style lang="less">
@import "../_styles/base.less";

.@{navigation} {
  a {
    font-weight: normal;
  }
}

.@{navigation}__popover {
  .@{sub-menu} {
    min-width: 220px;
  }

  .@{badge}__content {
    top: 20px;
    right: -7px;
  }

  a {
    font-weight: normal;
  }
}
</style>
