<template>
  <div class="det-navbar" v-if="showNavBar">
    <cr-tabbar v-model="active" active-color="#333" inactive-color="#666" @change="scrollTo">
      <cr-tabbar-item v-for="(item, index) in navList" :key="index">
        {{ item.label }}
      </cr-tabbar-item>
    </cr-tabbar>
  </div>
</template>

<script>
const SCROLL_ACHOR_CHANGE_EVENT = "input";
export default {
  name: "NavTab",
  props: {
    value: null,
    navList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      active: "",
      showNavBar: false
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.active = val;
      }
    },
    active: {
      handler(val) {
        this.$emit(SCROLL_ACHOR_CHANGE_EVENT, val);
      }
    }
  },
  mounted() {
    // 监听滚动事件
    window.addEventListener("scroll", this.onScroll, false);
  },
  destroy() {
    // 必须移除监听器，不然当该vue组件被销毁了，监听器还在就会出错
    window.removeEventListener("scroll", this.onScroll);
  },
  methods: {
    // 滚动监听器
    onScroll() {
      // 获取所有锚点元素
      const navContents = document.querySelectorAll("div[id*=det_]");
      // 所有锚点元素的 offsetTop
      const offsetTopArr = [];
      navContents.forEach(item => {
        offsetTopArr.push(item.offsetTop);
      });
      // 获取当前文档流的 scrollTop
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      // 定义当前点亮的导航下标
      let navIndex = 0;
      for (let n = 0; n < offsetTopArr.length; n++) {
        // 如果 scrollTop 大于等于第n个元素的 offsetTop 则说明 n-1 的内容已经完全不可见
        // 那么此时导航索引就应该是n了
        if (scrollTop >= offsetTopArr[n]) {
          navIndex = n;
        }
      }
      this.active = navIndex;
      this.showNavBar = scrollTop > 300;
    },
    // 跳转到指定索引的元素
    scrollTo(index) {
      const _val = this.navList[index].value;
      // 获取目标的 offsetTop
      const targetOffsetTop = document.querySelector(`#det_${_val}`).offsetTop;
      document.body.scrollTop = targetOffsetTop;
      document.documentElement.scrollTop = targetOffsetTop;
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../../../style/var.less";
@import "../../../../style/mixins.less";
.det-navbar {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 200;
  width: 100%;
  .cr-tabbar {
    background-color: @white;
    font-size: @font-size-16;
    border-bottom: 1px #ece9e9 solid;
    padding: 10px 0;
    height: 30px;
    &-item {
      position: relative;
      line-height: 22px;
      &::after {
        position: absolute;
        left: 0;
        right: 0;
        margin: auto;
        top: 32px;
        // transition: width .2s linear;
        content: " ";
        display: block;
        width: 0;
        height: 4px;
        background: @orange-light;
        border-radius: @border-radius-lx;
      }
      &--active {
        font-weight: 600;
        &::after {
          width: 32px;
        }
      }
    }
  }
}
</style>
