import Sticky from "../sticky";
import Content from "./content";
import Title from "./title";
import create from "../utils/create";
import { unitToPx, addUnit } from "../utils/format/unit";
import scrollUtils from "../utils/dom/scroll";
import { scrollTopTo, scrollLeftTo } from "./utils";
import { route } from "../utils/router";
import { callInterceptor } from "../utils/interceptor";
import { isDef } from "../utils";
import { isHidden } from "../utils/dom/style";
import { BindEventMixin } from "../mixins/bind-event";
import { ParentMixin } from "../mixins/relation";
import { on, off } from "../utils/dom/event";
export default create({
  render: function render() {
    var _vm = this;

    var _h = _vm.$createElement;

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

    return _c('div', {
      class: _vm.b([_vm.type])
    }, [_vm.sticky ? _c('vm-sticky', {
      attrs: {
        "container": _vm.$el,
        "offsetTop": _vm.offsetTop
      },
      on: {
        "scroll": _vm.onStickyScroll
      }
    }, [_c('div', {
      ref: "wrap",
      class: [_vm.b('wrap', {
        scrollable: _vm.scrollable
      }), {
        'vm-hairline-top-bottom': _vm.type === 'line' && _vm.border
      }]
    }, [_c('div', {
      ref: "nav",
      class: _vm.b('nav', [_vm.type, {
        complete: _vm.scrollable
      }]),
      style: _vm.navStyle,
      attrs: {
        "role": "tablist"
      }
    }, [_vm._t("nav-left"), _vm._l(_vm.children, function (item, index) {
      return [_c('vm-title', {
        key: index,
        ref: "titles",
        refInFor: true,
        style: item.titleStyle,
        attrs: {
          "refInFor": "",
          "type": _vm.type,
          "dot": item.dot,
          "info": item.badge || item.info,
          "title": item.title,
          "color": _vm.color,
          "isActive": index === _vm.currentIndex,
          "disabled": item.disabled,
          "scrollable": _vm.scrollable,
          "activeColor": _vm.titleActiveColor,
          "inactiveColor": _vm.titleInactiveColor,
          "swipeThreshold": _vm.swipeThreshold
        },
        on: {
          "click": function click($event) {
            return _vm.onClick(item, index);
          }
        }
      }, [_vm._t("title", null, {
        "slot": "default",
        "title": item.title
      })], 2)];
    }), _vm.type === 'line' ? _c('div', {
      class: _vm.b('-line'),
      style: _vm.lineStyle
    }) : _vm._e(), _vm._t("nav-right")], 2)])]) : _c('div', {
      ref: "wrap",
      class: [_vm.b('wrap', {
        scrollable: _vm.scrollable
      }), {
        'vm-hairline-top-bottom': _vm.type === 'line' && _vm.border
      }]
    }, [_c('div', {
      ref: "nav",
      class: _vm.b('nav', [_vm.type, {
        complete: _vm.scrollable
      }]),
      style: _vm.navStyle,
      attrs: {
        "role": "tablist"
      }
    }, [_vm._t("nav-left"), _vm._l(_vm.children, function (item, index) {
      return _c('vm-title', {
        key: index,
        ref: "titles",
        refInFor: true,
        style: item.titleStyle,
        attrs: {
          "refInFor": "",
          "type": _vm.type,
          "dot": item.dot,
          "info": item.badge || item.info,
          "title": item.title,
          "color": _vm.color,
          "isActive": index === _vm.currentIndex,
          "disabled": item.disabled,
          "scrollable": _vm.scrollable,
          "activeColor": _vm.titleActiveColor,
          "inactiveColor": _vm.titleInactiveColor,
          "swipeThreshold": _vm.swipeThreshold
        },
        on: {
          "click": function click($event) {
            return _vm.onClick(item, index);
          }
        }
      }, [_vm._t("title", null, {
        "slot": "default",
        "title": item.title
      })], 2);
    }), _vm.type === 'line' ? _c('div', {
      class: _vm.b('-line'),
      style: _vm.lineStyle
    }) : _vm._e(), _vm._t("nav-right")], 2)]), _c('vm-content', {
      attrs: {
        "count": _vm.children.length,
        "animated": _vm.animated,
        "duration": _vm.duration,
        "swipeable": _vm.swipeable,
        "currentIndex": _vm.currentIndex
      },
      on: {
        "change": _vm.setCurrentIndex
      }
    }, [_vm._t("default")], 2)], 1);
  },
  components: {
    "vm-sticky": Sticky,
    "vm-content": Content,
    "vm-title": Title
  },
  name: "tabs",
  mixins: [ParentMixin("vmTabs"), BindEventMixin(function (bind) {
    if (!this.scroller) {
      this.scroller = scrollUtils.getScrollEventTarget(this.$el);
    }

    bind(window, "resize", this.resize, true);

    if (this.scrollspy) {
      bind(this.scroller, "scroll", this.onScroll, true);
    }
  })],
  model: {
    prop: "active"
  },
  props: {
    color: String,
    border: Boolean,
    sticky: Boolean,
    animated: Boolean,
    swipeable: Boolean,
    scrollspy: Boolean,
    background: String,
    lineWidth: [Number, String],
    lineHeight: [Number, String],
    beforeChange: Function,
    titleActiveColor: String,
    titleInactiveColor: String,
    type: {
      type: String,
      default: "line"
    },
    active: {
      type: [Number, String],
      default: 0
    },
    ellipsis: {
      type: Boolean,
      default: true
    },
    duration: {
      type: [Number, String],
      default: 0.3
    },
    offsetTop: {
      type: [Number, String],
      default: 0
    },
    lazyRender: {
      type: Boolean,
      default: true
    },
    swipeThreshold: {
      type: [Number, String],
      default: 5
    }
  },
  data: function data() {
    return {
      position: "",
      currentIndex: null,
      lineStyle: {
        backgroundColor: this.color
      }
    };
  },
  watch: {
    color: "setLine",
    active: function active(name) {
      if (name !== this.currentName) {
        this.setCurrentIndexByName(name);
      }
    },
    children: function children() {
      var _this = this;

      this.setCurrentIndexByName(this.currentName || this.active);
      this.setLine();
      this.$nextTick(function () {
        _this.scrollIntoView(true);
      });
    },
    currentIndex: function currentIndex() {
      this.scrollIntoView();
      this.setLine(); // scroll to correct position

      if (this.stickyFixed && !this.scrollspy) {
        scrollUtils.setRootScrollTop(Math.ceil(scrollUtils.getElementTop(this.$el) - this.offsetTopPx));
      }
    },
    scrollspy: function scrollspy(val) {
      if (val) {
        on(this.scroller, "scroll", this.onScroll, true);
      } else {
        off(this.scroller, "scroll", this.onScroll);
      }
    }
  },
  methods: {
    // @exposed-api
    resize: function resize() {
      this.setLine();
    },
    init: function init() {
      var _this2 = this;

      this.$nextTick(function () {
        _this2.inited = true;
        _this2.tabHeight = scrollUtils.getVisibleHeight(_this2.$refs.wrap);

        _this2.scrollIntoView(true);
      });
    },
    // update nav bar style
    setLine: function setLine() {
      var _this3 = this;

      var shouldAnimate = this.inited;
      this.$nextTick(function () {
        var titles = _this3.$refs.titles;

        if (!titles || !titles[_this3.currentIndex] || _this3.type !== "line" || isHidden(_this3.$el)) {
          return;
        }

        var title = titles[_this3.currentIndex].$el;
        var lineWidth = _this3.lineWidth,
            lineHeight = _this3.lineHeight;
        var left = title.offsetLeft + title.offsetWidth / 2;
        var lineStyle = {
          width: addUnit(lineWidth),
          backgroundColor: _this3.color,
          transform: "translateX(" + left + "px) translateX(-50%)"
        };

        if (shouldAnimate) {
          lineStyle.transitionDuration = _this3.duration + "s";
        }

        if (isDef(lineHeight)) {
          var height = addUnit(lineHeight);
          lineStyle.height = height;
          lineStyle.borderRadius = height;
        }

        _this3.lineStyle = lineStyle;
      });
    },
    // correct the index of active tab
    setCurrentIndexByName: function setCurrentIndexByName(name) {
      var matched = this.children.filter(function (tab) {
        return tab.computedName === name;
      });
      var defaultIndex = (this.children[0] || {}).index || 0;
      this.setCurrentIndex(matched.length ? matched[0].index : defaultIndex);
    },
    setCurrentIndex: function setCurrentIndex(currentIndex) {
      currentIndex = this.findAvailableTab(currentIndex);

      if (isDef(currentIndex) && currentIndex !== this.currentIndex) {
        var shouldEmitChange = this.currentIndex !== null;
        this.currentIndex = currentIndex;
        this.$emit("input", this.currentName);

        if (shouldEmitChange) {
          this.$emit("change", this.currentName, this.children[currentIndex].title);
        }
      }
    },
    findAvailableTab: function findAvailableTab(index) {
      var diff = index < this.currentIndex ? -1 : 1;

      while (index >= 0 && index < this.children.length) {
        if (!this.children[index].disabled) {
          return index;
        }

        index += diff;
      }
    },
    // emit event when clicked
    onClick: function onClick(item, index) {
      var _this4 = this;

      var _this$children$index = this.children[index],
          title = _this$children$index.title,
          disabled = _this$children$index.disabled,
          computedName = _this$children$index.computedName;

      if (disabled) {
        this.$emit("disabled", computedName, title);
      } else {
        callInterceptor({
          interceptor: this.beforeChange,
          args: [computedName],
          done: function done() {
            _this4.setCurrentIndex(index);

            _this4.scrollToCurrentContent();
          }
        });
        this.$emit("click", computedName, title);
        route(item.$router, item);
      }
    },
    // scroll active tab into view
    scrollIntoView: function scrollIntoView(immediate) {
      var titles = this.$refs.titles;

      if (!this.scrollable || !titles || !titles[this.currentIndex]) {
        return;
      }

      var nav = this.$refs.nav;
      var title = titles[this.currentIndex].$el;
      var to = title.offsetLeft - (nav.offsetWidth - title.offsetWidth) / 2;
      scrollLeftTo(nav, to, immediate ? 0 : +this.duration);
    },
    onStickyScroll: function onStickyScroll(params) {
      this.stickyFixed = params.isFixed;
      this.$emit("scroll", params);
    },
    // @exposed-api
    scrollTo: function scrollTo(name) {
      var _this5 = this;

      this.$nextTick(function () {
        _this5.setCurrentIndexByName(name);

        _this5.scrollToCurrentContent(true);
      });
    },
    scrollToCurrentContent: function scrollToCurrentContent(immediate) {
      var _this6 = this;

      if (immediate === void 0) {
        immediate = false;
      }

      if (this.scrollspy) {
        var target = this.children[this.currentIndex];
        var el = target == null ? void 0 : target.$el;

        if (el) {
          var to = scrollUtils.getElementTop(el, this.scroller) - this.scrollOffset;
          this.lockScroll = true;
          scrollTopTo(this.scroller, to, immediate ? 0 : +this.duration, function () {
            _this6.lockScroll = false;
          });
        }
      }
    },
    onScroll: function onScroll() {
      if (this.scrollspy && !this.lockScroll) {
        var index = this.getCurrentIndexOnScroll();
        this.setCurrentIndex(index);
      }
    },
    getCurrentIndexOnScroll: function getCurrentIndexOnScroll() {
      var children = this.children;

      for (var index = 0; index < children.length; index++) {
        var top = scrollUtils.getVisibleTop(children[index].$el);

        if (top > this.scrollOffset) {
          return index === 0 ? 0 : index - 1;
        }
      }

      return children.length - 1;
    }
  },
  mounted: function mounted() {
    this.init();
  },
  activated: function activated() {
    this.init();
    this.setLine();
  },
  computed: {
    // 导航是否可滚动
    scrollable: function scrollable() {
      return this.children.length > this.swipeThreshold || !this.ellipsis;
    },
    navStyle: function navStyle() {
      return {
        borderColor: this.color,
        background: this.background
      };
    },
    currentName: function currentName() {
      var activeTab = this.children[this.currentIndex];

      if (activeTab) {
        return activeTab.computedName;
      }
    },
    offsetTopPx: function offsetTopPx() {
      return unitToPx(this.offsetTop);
    },
    scrollOffset: function scrollOffset() {
      if (this.sticky) {
        return this.offsetTopPx + this.tabHeight;
      }

      return 0;
    }
  }
});