/**
 * 负责渲染页面的组件
 */
const TabViewComponent = {
  name: "tab-view",
  functional: true,
  props: {
    path: {
      type: String
    },
    propsData: {}
  },
  render(_, { props, children, parent, data }) {
    const h = parent.$createElement;
    data.props = props.propsData;
    let comp = parent.$tabView.views[props.path];

    if (comp) {
      return h(comp.default, data, children);
    } else {
      return h("div", {}, ["没有找到注册的组件[" + props.path + "]"]);
    }
  }
};


export default class TabView {
  forceFirst = true;
  active = "首页";
  viewList = [{ name: "首页", path: "/" }];
  views = {};

  constructor(config) {
    Object.assign(this, config);
  }

  addView(name, path, propsData) {
    let idx = this.viewList.findIndex(item => item.name === name);
    if (idx === -1) this.viewList.push({ name, path, propsData,key: this.viewList.length});
    this.active = name;
  }

  removeView(name) {
    let idx = this.viewList.findIndex(item => item.name === name);
    if (idx > -1) {
      this.active = this.viewList[idx - 1].name;
      this.viewList.splice(idx, 1);
    }
  }
  changeName(oldName, newName) {
    let idx = this.viewList.findIndex(item => item.name === oldName);
    if (idx > -1) {
      this.viewList[idx].name = this.active = newName;
    }
  }
  removeOther() {
    this.removeBefore();
    this.removeAfter();
  }
  removeAfter() {
    let idx = this.viewList.findIndex(item => item.name === this.active);
    this.viewList.splice(idx + 1);
  }
  removeBefore() {
    let idx = this.viewList.findIndex(item => item.name === this.active);
    if (this.forceFirst) {
      this.viewList.splice(1, idx - 1);
    } else {
      this.viewList.splice(0, idx - 1);
    }
  }
  removeAll() {
    if (this.forceFirst) {
      this.viewList.splice(1);
      this.active = this.viewList[0].name;
    } else {
      this.viewList.splice(0);
    }
  }
}

TabView.install = function install(Vue, option) {
  const isDef = v => v !== undefined;

  Vue.mixin({
    beforeCreate() {
      if (isDef(this.$root.$options.tabView)) {
        this._tabView = this.$root.$options.tabView;
        Vue.util.defineReactive(this, "_tabView", this._tabView);
      }
    }
  });
  Object.defineProperty(Vue.prototype, "$tabView", {
    get() {
      return this._tabView;
    }
  });
  Vue.component("TabView", TabViewComponent);
};
