<template>
  <div class="bgo-timeline-item" :class="getClass()" @click="onClick">
    <div class="bgo-timeline-item__dot"></div>
    <div class="bgo-timeline-item__tail"></div>
    <div class="bgo-timeline-item__wrapper">
      <div v-if="timestamp" class="bgo-timeline-item__timestamp">
        {{ timestamp }}
      </div>
      <div class="bgo-timeline-item__content">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<script>
/**
 * 扁平化VNode
 * @param {VNode[]} vnodes 虚拟节点
 */
function flatternVnode(vnodes) {
  const result = [];

  function traverse(vnodes) {
    vnodes.forEach((vnode) => {
      result.push(vnode);

      if (vnode.children) {
        traverse(vnode.children);
      }
    });
  }

  traverse(vnodes);
  return result;
}

export default {
  name: "BgoTimelineItem",
  inject: {
    parent: {
      default: null,
    },
  },
  props: {
    timestamp: {
      type: [String],
    },
  },
  computed: {
    index() {
      return this.parent.children.indexOf(this);
    },
    status() {
      if (this.index < this.parent.current) {
        return "past";
      }
      if (this.index > this.parent.current) {
        return "future";
      }

      return "current";
    },
  },
  mounted() {
    if (!this.parent || this.parent.children.indexOf(this) !== -1) {
      return;
    }

    const children = [...this.parent.children, this];
    const vnodes = flatternVnode(this.parent.$slots.default);
    children.sort(
      (a, b) => vnodes.indexOf(a.$vnode) - vnodes.indexOf(b.$vnode)
    );

    this.parent.children = children;
  },
  beforeDestroy() {
    this.parent.children = this.parent.children.filter((item) => item !== this);
  },
  methods: {
    getClass() {
      return "bgo-timeline-item--" + this.status;
    },
    onClick(event) {
      this.$emit("click", event);
    },
  },
};
</script>

<style lang="scss">
@import "./index";
</style>
