<template>
  <div class="anchor-wrapper">
    <el-timeline @click.native="wrapperClick">
      <el-timeline-item
        v-for="(anchor, index) in anchorAry"
        :type="anchor.selected?'primary':''"
        :key="index"
      >
        <a class="anchor-link" :href="genHref(anchor.alias)">{{anchor.content}}</a>
      </el-timeline-item>
    </el-timeline>
  </div>
</template>
<script>
export default {
  props: {
    anchors: Array
  },
  data() {
    return {
      array: []
    };
  },
  computed: {
    anchorAry: function() {
      if (this.array && this.array.length > 0) {
        return this.array;
      }
      this.anchors &&
        this.anchors.forEach(item => {
          this.array.push(Object.assign({ selected: false }, item));
        });
      return this.array;
    }
  },
  mounted() {
    this.$route.hash && this.updateTarget(this.$route.hash);
    this.$router.afterEach((to, from) => {
      to.hash && this.updateTarget(to.hash);
    });
  },
  methods: {
    wrapperClick: function(e) {
      e.target.hash && this.updateTarget(e.target.hash);
    },
    updateTarget: function(t) {
      if (!t || t.constructor != String) {
        return;
      }
      let index = t.lastIndexOf("#");
      if ( index != -1) {
        t = t.substr(index + 1);
      }
      this.anchorAry.forEach(item => {
        if (item.alias == t) {
          item.selected = true;
        } else {
          item.selected = false;
        }
      });
    },
    genHref(anchor){
      if(this.$router.mode=="history"){
        return "#"+anchor;
      }
      return "/#"+this.$route.path+"#" + anchor;
    }
  }
};
</script>
<style lang="scss" scoped>
.anchor-wrapper {
  position: fixed;
}

.el-timeline-item {
  padding-bottom: 7px;
}

.anchor-link {
  display: block;
  position: relative;
  transition: all 0.3s;
  color: rgba(0, 0, 0, 0.65);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 6px;
  text-decoration: none;
}

.anchor-link:hover {
  color: #1890ff;
}
</style>