import "./index.css";
import "core-js/modules/web.dom.iterable";

/* script */
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
import merge from 'lodash/merge';
import Icon from '../Icon';
import request from '../request';
import cache from '../cache';
import { on, off } from '../_utils/dom.js';
import { createComponentName, componentMixin } from '../_utils/component';
import data from './defaultData';
import User from './User';
import GdLink from './Link';
import { toRelativePath, includeUrl } from '../_utils/url';
import Badge from '../Badge';

function setNavConfig(navs) {
  navs.forEach(nav => {
    let config;

    try {
      config = typeof nav.config === 'string' ? JSON.parse(nav.config) : nav.config;

      if (typeof config === 'string') {
        config = {};
      }
    } catch (error) {
      config = {};
    }

    nav.config = merge({
      type: 'url',
      title: ''
    }, config || {});

    if (nav.children && nav.children.length) {
      setNavConfig(nav.children);
    }
  });
}

setNavConfig(data);
const __vue_script__ = {
  name: createComponentName('header'),
  components: {
    Icon,
    User,
    Badge,
    GdLink
  },
  mixins: [componentMixin],
  props: {
    // 当前页面的域名, 会将相同域名的地址转换为相对路径
    host: {
      type: String
    },
    // 半透明 用于专题页
    translucent: {
      type: Boolean,
      default: false
    },
    // 是否登录
    isLogined: {
      type: Boolean,
      default: false
    },
    // 处理导航数据
    handleNavigations: {
      // (navs: object[]) => object[]
      type: Function
    },
    // 触发退出
    logout: {
      type: Function,
      required: true
    },
    // 触发登录
    login: {
      type: Function,
      required: true
    }
  },

  data() {
    return {
      navs: data,
      visibleKey: null,
      isSubNav: false,
      opacity: 0.5,
      isShowMore: false,
      mounted: false,
      activeIds: []
    };
  },

  computed: {
    type() {
      if (this.isScene) {
        return 'scene';
      } else if (this.translucent) {
        return 'feature';
      }

      return '';
    },

    isScene() {
      if (!this.activeIds.length) return false;
      const id = this.activeIds[0];
      const nav = this.navs.find(nav => nav.id === id);
      if (!nav) return false;
      return !!nav.children.length;
    },

    showMore() {
      if (!this.isScene) return true;
      return this.isShowMore;
    },

    currentRootNav() {
      let key = this.visibleKey;

      if (this.isScene && (key === null || this.isSubNav)) {
        key = this.activeIds[0] || null;
      }

      return this.navs.find(nav => nav.id === key) || null;
    },

    arrowLeft() {
      if (!this.mounted) return 0;
      const nav = this.currentRootNav;

      if (nav && nav.children.length && this.$refs[`nav${nav.id}`]) {
        const el = this.$refs[`nav${nav.id}`][0].$el;
        const rect = el.getBoundingClientRect();
        return rect.left + rect.width / 2 - 5;
      }

      return 0;
    },

    subMenuGroup() {
      return this.getMenuGroup(this.currentRootNav);
    }

  },
  watch: {
    $route() {
      this.$nextTick(() => {
        this.resetActvieNavIds();
      });
    }

  },

  beforeCreate() {
    this.GdLink = GdLink;
  },

  created() {
    on(window, 'scroll', this.onScroll);
    const data = cache.localCache.get('navigations');

    if (data) {
      setNavConfig(data);
      this.navs = data;
    }

    this.resetActvieNavIds();
    this.resetData();
  },

  mounted() {
    this.mounted = true;
    this.onScroll();
  },

  beforeDestroy() {
    off(window, 'scroll', this.onScroll);
  },

  methods: {
    // @vuese
    // 重置导航数据， 登录后需要使用，获取不同的灰度数据
    resetData() {
      request.get('/api/navigations').then(res => {
        cache.localCache.set('navigations', res.data);
        setNavConfig(res.data);

        if (this.handleNavigations) {
          res.data = this.handleNavigations(res.data) || res.data;
        }

        ;
        this.navs = res.data;
        this.resetActvieNavIds();
      });
    },

    // 重新设置当前应该高亮的导航 ID， 应该在更新导航数据或者路由更变的时候，重新修改
    resetActvieNavIds() {
      if (!this.$isServer) {
        const value = this.getActvieNavIds(this.navs, []);
        this.activeIds = value;
      }

      return [];
    },

    onClick(nav) {
      // 点击导航触发
      // @arg nav: object
      this.$emit('select', nav);
    },

    changeVisibleKey(nav) {
      if (!nav) {
        this.visibleKey = null;
      } else {
        this.visibleKey = nav.id;
      }
    },

    isActiveRoute(nav) {
      let isActive = false;

      if (!this.visibleKey) {
        isActive = this.activeIds.indexOf(nav.id) > -1;
      }

      if (!isActive) {
        isActive = this.visibleKey === nav.id;
      }

      return isActive;
    },

    changeShowMore(value) {
      if (this.isScene) {
        this.isShowMore = value;
      }
    },

    // 不需要计算得很精确
    getMenuGroup(rootMenu) {
      if (!rootMenu) return [];
      let group = [];
      let arr = [];

      for (let i = 0, v = 0; i < rootMenu.children.length; i++) {
        v = v + 24 + rootMenu.children[i].title.length * 14;

        if (v > 800) {
          group.push(arr);
          arr = [];
          v = 0;
        }

        arr.push(rootMenu.children[i]);
      }

      group.push(arr);
      return group;
    },

    onScroll() {
      const top = document.documentElement.scrollTop || document.body.scrollTop;
      const isEqueal = top >= 66 === this.isSubNav;

      if (!isEqueal && this.isScene) {
        this.isSubNav = !this.isSubNav;
      }

      if (this.translucent) {
        this.opacity = Math.min(0.4 + top / 300 * 0.6, 0.98);
      }
    },

    _isHideMenu(nav) {
      if (!this.isHideMenu) return false;
      return this.isHideMenu(this.transformUrl(nav.link), this.indexPath(), nav);
    },

    // 获取当前 高亮的导航 ID
    getActvieNavIds(navs, value, parentNav) {
      for (const nav of navs) {
        let isFuzzy = !!parentNav;

        if ('fuzzy' in nav.config) {
          isFuzzy = nav.config.fuzzy;
        }

        if (this.includeHref(nav.link, isFuzzy)) {
          if (parentNav && value.indexOf(parentNav.id) === -1) {
            value.push(parentNav.id);
          }

          value.push(nav.id);
        }

        if (nav.children) {
          const v = this.getActvieNavIds(nav.children, value, nav);
          if (v.length) return v;
        }
      }

      return value;
    },

    transformUrl(url) {
      return toRelativePath(url, this.host);
    },

    includeHref(url, fuzzy = false) {
      let href = this.host ? location.protocol + '//' + this.host + location.pathname + location.search : location.href;
      return includeUrl(href, url, fuzzy);
    }

  }
};
/* template */

var __vue_render__ = function () {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c("div", {
    class: _vm.bem("wrapper", [_vm.type])
  }, [_c("header", {
    class: _vm.bem({
      "sub-nav": _vm.isSubNav && _vm.isScene,
      blur: _vm.translucent
    }),
    on: {
      mouseleave: function ($event) {
        _vm.changeVisibleKey(null);
      }
    }
  }, [_c("div", {
    class: _vm.bem("nav"),
    style: _vm.translucent ? {
      "background-color": "rgba(17,17,17," + _vm.opacity + ")"
    } : undefined
  }, [_c("div", {
    class: _vm.bem("content")
  }, [_c("GdLink", {
    attrs: {
      url: _vm.transformUrl("https://www.gaoding.com")
    }
  }, [_c("div", {
    class: _vm.bem("logo")
  }, [_c("Icon", {
    attrs: {
      name: "logo"
    }
  })], 1)]), _vm._v(" "), _c("div", {
    class: _vm.bem("nav-list")
  }, [_vm._l(_vm.navs, function (nav) {
    return [!nav.title || nav.config.divider ? _c("div", {
      key: nav.id,
      class: _vm.bem("divider"),
      style: _vm.translucent ? {
        opacity: _vm.opacity
      } : undefined
    }) : _c("GdLink", {
      key: nav.id,
      ref: "nav" + nav.id,
      refInFor: true,
      class: _vm.bem("nav-item", {
        active: _vm.isActiveRoute(nav)
      }),
      attrs: {
        tag: _vm.GdLink,
        url: _vm.transformUrl(nav.link),
        target: nav.config.target,
        theme: "light"
      },
      on: {
        click: function ($event) {
          _vm.onClick(nav);
        }
      },
      nativeOn: {
        mouseenter: function ($event) {
          _vm.changeVisibleKey(nav);
        }
      }
    }, [_vm._v("\n\n                            " + _vm._s(nav.title) + "\n                        ")])];
  })], 2), _vm._v(" "), _c("div", {
    directives: [{
      name: "show",
      rawName: "v-show",
      value: _vm.arrowLeft,
      expression: "arrowLeft"
    }],
    class: _vm.bem("arrow"),
    style: {
      left: _vm.arrowLeft + "px"
    }
  }), _vm._v(" "), _c("User", {
    attrs: {
      isLogined: _vm.isLogined,
      logout: _vm.logout,
      login: _vm.login
    }
  }, [_vm._t("nick")], 2)], 1)]), _vm._v(" "), _c("div", {
    directives: [{
      name: "show",
      rawName: "v-show",
      value: _vm.currentRootNav && _vm.currentRootNav.children.length,
      expression: "currentRootNav && currentRootNav.children.length"
    }],
    class: _vm.bem("sub-nav"),
    on: {
      mouseenter: function ($event) {
        _vm.changeShowMore(true);
      },
      mouseleave: function ($event) {
        _vm.changeShowMore(false);
      }
    }
  }, [_c("div", {
    class: _vm.bem("content")
  }, [_c("GdLink", {
    class: _vm.bem("logo"),
    attrs: {
      url: "/"
    }
  }, [_c("img", {
    attrs: {
      src: require("./assets/logo.svg"),
      alt: ""
    }
  }), _vm._v(" "), _c("div", {
    class: _vm.bem("divider")
  }), _vm._v("\n                    " + _vm._s(_vm.currentRootNav ? _vm.currentRootNav.config.title : "") + "\n                ")]), _vm._v(" "), _c("div", {
    class: _vm.bem("nav-list")
  }, _vm._l(_vm.showMore ? _vm.getMenuGroup(_vm.currentRootNav) : _vm.getMenuGroup(_vm.currentRootNav).slice(0, 1), function (subNavs, i) {
    return _c("div", {
      key: i,
      class: _vm.bem("nav-row")
    }, [_vm._l(subNavs, function (nav) {
      return _c("GdLink", {
        key: nav.id,
        class: _vm.bem("sub-nav-item", {
          active: _vm.isActiveRoute(nav),
          new: nav.is_new
        }),
        attrs: {
          url: _vm.transformUrl(nav.link),
          target: nav.config.target
        },
        on: {
          click: function ($event) {
            _vm.onClick(nav);
          }
        }
      }, [nav.is_new ? _c("badge", {
        attrs: {
          value: "New"
        }
      }, [_vm._v(_vm._s(nav.title))]) : _c("span", [_vm._v(_vm._s(nav.title))])], 1);
    }), _vm._v(" "), i == 0 && _vm.getMenuGroup(_vm.currentRootNav).length > 1 && !_vm.showMore ? _c("span", {
      class: _vm.bem("sub-nav-item")
    }, [_vm._v("\n                            更多\n                            "), _c("Icon", {
      attrs: {
        name: "triangle-down"
      }
    })], 1) : _vm._e()], 2);
  }), 0)], 1)])])]);
};

var __vue_staticRenderFns__ = [];
__vue_render__._withStripped = true;
/* style */

const __vue_inject_styles__ = undefined;
/* scoped */

const __vue_scope_id__ = undefined;
/* module identifier */

const __vue_module_identifier__ = undefined;
/* functional template */

const __vue_is_functional_template__ = false;
/* component normalizer */

import __vue_normalize__ from '../_utils/vue-normalize-component.js';
/* style inject */

/* style inject SSR */

export default __vue_normalize__({
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__
}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined);