"use strict";
const uni_modules_tdesignUniapp_components_common_src_instantiationDecorator = require("../common/src/instantiationDecorator.js");
const uni_modules_tdesignUniapp_components_tabs_props = require("./props.js");
const uni_modules_tdesignUniapp_components_common_config = require("../common/config.js");
const uni_modules_tdesignUniapp_components_mixins_touch = require("../mixins/touch.js");
const uni_modules_tdesignUniapp_components_common_utils = require("../common/utils.js");
const uni_modules_tdesignUniapp_components_common_wechat = require("../common/wechat.js");
const uni_modules_tdesignUniapp_components_common_utils_wxs = require("../common/utils.wxs.js");
const uni_modules_tdesignUniapp_components_common_relation_parentMap = require("../common/relation/parent-map.js");
const uni_modules_tdesignUniapp_components_common_relation_relation = require("../common/relation/relation.js");
const uni_modules_tdesignUniapp_components_tabs_computed = require("./computed.js");
const common_vendor = require("../../../../common/vendor.js");
const TSticky = () => "../sticky/sticky.js";
const TBadge = () => "../badge/badge.js";
const TIcon = () => "../icon/icon.js";
const name = `${uni_modules_tdesignUniapp_components_common_config.prefix}-tabs`;
const getUniqueID = uni_modules_tdesignUniapp_components_common_utils.uniqueFactory("tabs");
const _sfc_main = uni_modules_tdesignUniapp_components_common_src_instantiationDecorator.uniComponent({
  name,
  options: {
    styleIsolation: "shared"
  },
  controlledProps: [{
    key: "value",
    event: "change"
  }],
  externalClasses: [
    `${uni_modules_tdesignUniapp_components_common_config.prefix}-class`,
    `${uni_modules_tdesignUniapp_components_common_config.prefix}-class-item`,
    `${uni_modules_tdesignUniapp_components_common_config.prefix}-class-active`,
    `${uni_modules_tdesignUniapp_components_common_config.prefix}-class-track`,
    `${uni_modules_tdesignUniapp_components_common_config.prefix}-class-content`
  ],
  mixins: [uni_modules_tdesignUniapp_components_mixins_touch.touch, uni_modules_tdesignUniapp_components_common_relation_relation.ParentMixin(uni_modules_tdesignUniapp_components_common_relation_parentMap.RELATION_MAP.TabPanel)],
  components: {
    TSticky,
    TBadge,
    TIcon
  },
  props: {
    ...uni_modules_tdesignUniapp_components_tabs_props.props
  },
  emits: [
    "change",
    "scroll",
    "error",
    "click"
  ],
  watch: {
    value: {
      handler(e) {
        this.dataValue = e;
      },
      immediate: true
    },
    dataValue(name2) {
      if (name2 !== this.getCurrentName()) {
        this.setCurrentIndexByName(name2);
      }
    }
  },
  created() {
    this.children = this.children || [];
  },
  mounted() {
    uni_modules_tdesignUniapp_components_common_utils.nextTick().then(() => {
      this.setTrack();
    });
    uni_modules_tdesignUniapp_components_common_utils.getRect(this, `.${name}`).then((rect) => {
      this.containerWidth = rect.width;
    });
    this.tabID = getUniqueID();
  },
  data() {
    return {
      prefix: uni_modules_tdesignUniapp_components_common_config.prefix,
      classPrefix: name,
      tabs: [],
      currentLabels: [],
      currentIndex: -1,
      trackOption: {
        lineWidth: 0,
        distance: 0,
        isInit: true
      },
      offset: 0,
      scrollLeft: 0,
      tabID: "",
      placement: "top",
      tools: uni_modules_tdesignUniapp_components_common_utils_wxs.tools,
      dataValue: uni_modules_tdesignUniapp_components_common_utils.coalesce(this.value, this.defaultValue)
    };
  },
  methods: {
    trackStyle: uni_modules_tdesignUniapp_components_tabs_computed.trackStyle,
    animate: uni_modules_tdesignUniapp_components_tabs_computed.animate,
    innerAfterLinked(target) {
      this.initChildId();
      target.dataIndex = this.children.length - 1;
      this.updateTabs();
    },
    innerAfterUnlinked(target) {
      this.children = this.children.filter((item) => item.index !== target.dataIndex);
      this.updateTabs(() => this.setTrack());
      this.initChildId();
    },
    initChildId() {
      this.children.forEach((item, index) => {
        item.setId(`${this.tabID}_panel_${index}`);
      });
    },
    onScroll(e = {}) {
      const { scrollLeft } = e.detail || {};
      this.scrollLeft = scrollLeft;
    },
    updateTabs(cb) {
      const { children } = this;
      const tabs = children.map((child) => {
        const { label, badgeProps, disabled, icon, panel, value, lazy } = child;
        return {
          label,
          badgeProps,
          disabled,
          icon,
          panel,
          value,
          lazy
        };
      });
      tabs.forEach((item) => {
        if (typeof item.icon === "string") {
          item.icon = { name: item.icon };
        }
      });
      this.tabs = tabs;
      if (typeof cb === "function") {
        setTimeout(cb, 33);
      }
      this.setCurrentIndexByName(this.dataValue);
    },
    setCurrentIndexByName(name2) {
      const { children } = this;
      const index = children.findIndex((child) => child.getComputedName() === `${name2}`);
      if (index > -1) {
        this.setCurrentIndex(index);
      }
    },
    setCurrentIndex(index) {
      if (index <= -1 || index >= this.children.length)
        return;
      const Labels = [];
      this.children.forEach((child, idx) => {
        const isActive = index === idx;
        if (isActive !== child.active || !child.initialized) {
          child.render(isActive, this);
        }
        Labels.push(child.label);
      });
      const { currentIndex, currentLabels } = this;
      if (currentIndex === index && currentLabels.join("") === Labels.join(""))
        return;
      this.currentIndex = index;
      this.currentLabels = Labels;
      setTimeout(() => {
        this.setTrack();
      }, 33);
    },
    getCurrentName() {
      if (this.children) {
        const activeTab = this.children[this.currentIndex];
        if (activeTab) {
          return activeTab.getComputedName();
        }
      }
    },
    calcScrollOffset(containerWidth, targetLeft, targetWidth, offset) {
      return offset + targetLeft - 1 / 2 * containerWidth + targetWidth / 2;
    },
    // 外部无法获取虚拟组件节点位置信息
    getTabHeight() {
      return uni_modules_tdesignUniapp_components_common_utils.getRect(this, `.${name}`);
    },
    getTrackSize() {
      const { bottomLineMode } = this;
      const targetMap = {
        fixed: `.${uni_modules_tdesignUniapp_components_common_config.prefix}-tabs__track`,
        auto: `.${uni_modules_tdesignUniapp_components_common_config.prefix}-tabs__item--active .${uni_modules_tdesignUniapp_components_common_config.prefix}-tabs__item-inner`,
        full: `.${uni_modules_tdesignUniapp_components_common_config.prefix}-tabs__item--active`
      };
      return new Promise((resolve, reject) => {
        if (this.trackWidth) {
          resolve(this.trackWidth);
          return;
        }
        uni_modules_tdesignUniapp_components_common_utils.getRect(this, targetMap[bottomLineMode] || targetMap.fixed).then((res) => {
          if (res) {
            resolve(res.width);
          }
        }).catch(reject);
      });
    },
    async setTrack() {
      const { children } = this;
      if (!children)
        return;
      const { currentIndex } = this;
      if (currentIndex <= -1)
        return;
      try {
        const res = await uni_modules_tdesignUniapp_components_common_utils.getRect(this, `.${uni_modules_tdesignUniapp_components_common_config.prefix}-tabs__item`, true);
        const rect = res[currentIndex];
        if (!rect)
          return;
        let count = 0;
        let distance = 0;
        let totalSize = 0;
        res.forEach((item) => {
          if (count < currentIndex) {
            distance += item.width;
            count += 1;
          }
          totalSize += item.width;
        });
        if (this.containerWidth) {
          const offset = this.calcScrollOffset(this.containerWidth, rect.left, rect.width, this.scrollLeft);
          const maxOffset = totalSize - this.containerWidth;
          this.offset = Math.min(Math.max(offset, 0), maxOffset);
        } else if (!this._hasObserved) {
          this._hasObserved = true;
          uni_modules_tdesignUniapp_components_common_wechat.getObserver(this, `.${name}`).then(() => this.setTrack());
        }
        const lineWidth = await this.getTrackSize();
        if (this.theme === "line") {
          distance += (rect.width - lineWidth) / 2;
        }
        const isInit = this.previousIndex === void 0;
        if (isInit || this.previousIndex !== currentIndex || this.lastDistance !== distance) {
          this.previousIndex = currentIndex;
          this.trackOption = { lineWidth, distance, isInit };
          this.lastDistance = distance;
        }
      } catch (err) {
        this.$emit("error", err);
      }
    },
    onTabTap(event) {
      const { index } = event.currentTarget.dataset;
      this.changeIndex(index);
    },
    onTouchStart(event) {
      if (!this.swipeable)
        return;
      this.touchStart(event);
    },
    onTouchMove(event) {
      if (!this.swipeable)
        return;
      this.touchMove(event);
    },
    onTouchEnd() {
      if (!this.swipeable)
        return;
      const { direction, deltaX, offsetX } = this;
      const minSwipeDistance = 50;
      if (direction === "horizontal" && offsetX >= minSwipeDistance) {
        const index = this.getAvailableTabIndex(deltaX);
        if (index !== -1) {
          this.changeIndex(index);
        }
      }
    },
    onTouchScroll(event) {
      this._trigger("scroll", event);
    },
    changeIndex(index) {
      const currentTab = this.tabs[index];
      const { value, label } = currentTab;
      if (!(currentTab == null ? void 0 : currentTab.disabled) && index !== this.currentIndex) {
        this._trigger("change", { value, label });
      }
      this._trigger("click", { value, label });
    },
    getAvailableTabIndex(deltaX) {
      const step = deltaX > 0 ? -1 : 1;
      const { currentIndex, tabs } = this;
      const len = tabs.length;
      for (let i = step; currentIndex + step >= 0 && currentIndex + step < len; i += step) {
        const newIndex = currentIndex + i;
        if (newIndex >= 0 && newIndex < len && tabs[newIndex]) {
          if (!tabs[newIndex].disabled) {
            return newIndex;
          }
        } else {
          return currentIndex;
        }
      }
      return -1;
    },
    getBadgeCustomStyle(item, index) {
      if (item.disabled) {
        return "--td-badge-content-text-color: var(--td-tab-item-disabled-color, var(--td-text-color-disabled, var(--td-font-gray-4, rgba(0, 0, 0, .26))))";
      }
      if (this.currentIndex === index) {
        return "--td-badge-content-text-color: var(--td-tab-item-active-color, var(--td-brand-color, var(--td-primary-color-7, #0052d9)));";
      }
      return "";
    },
    getIconCustomStyle(item) {
      return uni_modules_tdesignUniapp_components_common_utils_wxs.tools._style([
        {
          fontSize: "var(--td-tab-icon-size, 18px)",
          marginRight: "calc(var(--td-spacer, 8px) / 4)"
        },
        item.icon.style || ""
      ]);
    }
  }
});
if (!Array) {
  const _easycom_t_icon2 = common_vendor.resolveComponent("t-icon");
  const _easycom_t_badge2 = common_vendor.resolveComponent("t-badge");
  const _easycom_t_sticky2 = common_vendor.resolveComponent("t-sticky");
  (_easycom_t_icon2 + _easycom_t_badge2 + _easycom_t_sticky2)();
}
const _easycom_t_icon = () => "../icon/icon.js";
const _easycom_t_badge = () => "../badge/badge.js";
const _easycom_t_sticky = () => "../sticky/sticky.js";
if (!Math) {
  (_easycom_t_icon + _easycom_t_badge + _easycom_t_sticky)();
}
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  return common_vendor.e({
    a: common_vendor.f(_ctx.tabs, (item, index, i0) => {
      return common_vendor.e({
        a: item.icon
      }, item.icon ? {
        b: common_vendor.o(($event) => item.icon.click || "", index),
        c: "7918ea5e-1-" + i0 + ",7918ea5e-0",
        d: common_vendor.p({
          ["t-class"]: _ctx.classPrefix + "__icon",
          ["custom-style"]: _ctx.getIconCustomStyle(item),
          prefix: item.icon.prefix,
          name: item.icon.name,
          size: item.icon.size,
          color: item.icon.color,
          ["aria-hidden"]: !!item.icon.ariaHidden,
          ["aria-label"]: item.icon.ariaLabel,
          ["aria-role"]: item.icon.ariaRole
        })
      } : {}, {
        e: item.badgeProps
      }, item.badgeProps ? {
        f: "7918ea5e-2-" + i0 + ",7918ea5e-0",
        g: common_vendor.p({
          color: item.badgeProps.color || "",
          content: item.label,
          count: item.badgeProps.count || 0,
          dot: item.badgeProps.dot || false,
          ["max-count"]: item.badgeProps.maxCount || 99,
          offset: item.badgeProps.offset || [],
          shape: item.badgeProps.shape || "circle",
          ["show-zero"]: item.badgeProps.showZero || false,
          size: item.badgeProps.size || "medium",
          ["t-class"]: _ctx.tools.cls(_ctx.classPrefix + "__badge", [["disabled", item.disabled], ["active", _ctx.currentIndex === index]]),
          ["custom-style"]: _ctx.getBadgeCustomStyle(item, index),
          ["t-class-content"]: item.badgeProps.tClassContent,
          ["t-class-count"]: item.badgeProps.tClassCount
        })
      } : {
        h: common_vendor.t(item.label)
      }, {
        i: common_vendor.n(_ctx.tools.cls(_ctx.classPrefix + "__item-inner", [_ctx.theme, ["active", _ctx.currentIndex === index]])),
        j: item.badgeProps.dot || item.badgeProps.count,
        k: _ctx.theme == "card" && _ctx.currentIndex - 1 == index
      }, _ctx.theme == "card" && _ctx.currentIndex - 1 == index ? {
        l: common_vendor.n(_ctx.classPrefix + "__item-prefix")
      } : {}, {
        m: _ctx.theme == "card" && _ctx.currentIndex + 1 == index
      }, _ctx.theme == "card" && _ctx.currentIndex + 1 == index ? {
        n: common_vendor.n(_ctx.classPrefix + "__item-suffix")
      } : {}, {
        o: index,
        p: index,
        q: common_vendor.n(_ctx.tools.cls(_ctx.classPrefix + "__item", [_ctx.theme, ["evenly", _ctx.spaceEvenly], _ctx.placement, ["disabled", item.disabled], ["active", _ctx.currentIndex === index]]) + " " + (_ctx.currentIndex === index ? _ctx.tClassActive : "") + " " + _ctx.tClassItem),
        r: _ctx.tabID + "_panel_" + index,
        s: _ctx.currentIndex === index,
        t: item.disabled,
        v: _ctx.ariaLabel || (item.badgeProps.dot || item.badgeProps.count ? item.label + _ctx.tools.getBadgeAriaLabel({
          ...item.badgeProps
        }) : ""),
        w: common_vendor.o((...args) => _ctx.onTabTap && _ctx.onTabTap(...args), index)
      });
    }),
    b: _ctx.theme == "line" && _ctx.showBottomLine
  }, _ctx.theme == "line" && _ctx.showBottomLine ? {
    c: common_vendor.n(_ctx.tools.cls(_ctx.classPrefix + "__track", [_ctx.placement]) + " " + _ctx.tClassTrack),
    d: common_vendor.s(_ctx.trackStyle(_ctx.trackOption))
  } : {}, {
    e: common_vendor.n(_ctx.tools.cls(_ctx.classPrefix + "__nav", [_ctx.placement, ["evenly", _ctx.spaceEvenly]])),
    f: common_vendor.n(_ctx.tools.cls(_ctx.classPrefix + "__scroll", [_ctx.placement, ["split", _ctx.split]])),
    g: _ctx.offset,
    h: common_vendor.o((...args) => _ctx.onScroll && _ctx.onScroll(...args)),
    i: common_vendor.n(_ctx.tools.cls(_ctx.classPrefix + "__wrapper", [_ctx.theme])),
    j: common_vendor.o(_ctx.onTouchScroll),
    k: common_vendor.p({
      ["t-class"]: _ctx.tools.cls(_ctx.classPrefix + "__sticky", [_ctx.placement]),
      disabled: !_ctx.sticky,
      ["z-index"]: _ctx.stickyProps && _ctx.stickyProps.zIndex || 1,
      ["offset-top"]: _ctx.stickyProps && _ctx.stickyProps.offsetTop || 0,
      container: _ctx.stickyProps && _ctx.stickyProps.container
    }),
    l: common_vendor.n(_ctx.classPrefix + "__content-inner " + _ctx.tClassContent),
    m: common_vendor.s(_ctx.animate({
      duration: _ctx.animation && _ctx.animation.duration,
      currentIndex: _ctx.currentIndex
    })),
    n: common_vendor.n(_ctx.tools.cls(_ctx.classPrefix + "__content", [["animated", _ctx.animation]])),
    o: common_vendor.o((...args) => _ctx.onTouchStart && _ctx.onTouchStart(...args)),
    p: common_vendor.o((...args) => _ctx.onTouchMove && _ctx.onTouchMove(...args)),
    q: common_vendor.o((...args) => _ctx.onTouchEnd && _ctx.onTouchEnd(...args)),
    r: common_vendor.o((...args) => _ctx.onTouchEnd && _ctx.onTouchEnd(...args)),
    s: common_vendor.s(_ctx.tools._style([_ctx.customStyle])),
    t: common_vendor.n(_ctx.tools.cls(_ctx.classPrefix, [_ctx.placement]) + " " + _ctx.tClass)
  });
}
const Component = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-7918ea5e"]]);
wx.createComponent(Component);
//# sourceMappingURL=../../../../../.sourcemap/mp-weixin/uni_modules/tdesign-uniapp/components/tabs/tabs.js.map
