import { fetchToken } from "../api/auth";
import { isAuthenticated, requireAuth } from "../utils/auth";

Component({
  data: {
    hidden: false,
    tabIndex: -1,
    tabs: [
      {
        path: "/pages/map/map",
        text: "充电地图",
      },
      {
        path: "/pages-charge/camera/camera",
        text: "扫码充电",
      },
      {
        path: "/pages/user/user",
        text: "个人中心",
      },
    ],
  },
  lifetimes: {
    ready() {
      fetchToken().then(() => {
        const pages = getCurrentPages();
        const index = this.data.tabs.findIndex(
          (item) => item.path === `/${pages[pages.length - 1].route}`
        );
        this.setData({
          hidden: false,
          tabIndex: index,
        });
      });
    },
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset;
      const url = data.path;
      const index = data.index;

      if (index === 1 || index === 2) {
        if (!isAuthenticated()) {
          requireAuth(url);
          return;
        }
      }

      if (/camera/.test(url)) {
        wx.navigateTo({
          url,
        });
        return;
      }
      wx.vibrateShort &&
        wx.vibrateShort({
          type: "light",
        });
      wx.switchTab({
        url,
      });
    },
    hiddenTab() {
      this.setData({
        hidden: true,
      });
    },
    showTab() {
      this.setData({
        hidden: false,
      });
    },
  },
});
