import { fetchToken, login, onLogin } from "../api/auth";
import { fetchChargeStatus } from "../api/charge";
import { scanCode } from "../utils/code";

Component({
  data: {
    hidden: false,
    dialog: false,
    tabIndex: -1,
    tabs: [
      {
        path: "/pages/map/map",
        text: "充电地图",
      },
      {
        path: "",
        text: "扫码充电",
      },
      {
        path: "/pages/list/list",
        text: "电站列表",
      },
      {
        path: "/pages/user/user",
        text: "个人中心",
      },
    ],
    charging: "",
  },
  lifetimes: {
    ready() {
      fetchToken().then((token) => {
        const pages = getCurrentPages();
        const index = this.data.tabs.findIndex(
          (item) => item.path === `/${pages[pages.length - 1].route}`
        );
        this.setData({
          hidden: false,
          tabIndex: index,
          token,
        });
        if (!token) {
          onLogin((token) => {
            this.setData({
              token,
            });
          });
        }
      });
    },
  },
  methods: {
    switchTab(e) {
      fetchChargeStatus().then(res => {
        this.setData({
          charging: [1, 2].includes(res.chargeStatus) ? res.connectorId : ''
        })
      }).catch(() => {
        this.setData({
          charging: ''
        })
      })
      const data = e.currentTarget.dataset;
      const url = data.path;
      if (!url) {
        this.switchDialog();
        return;
      }
      this.setData({
        dialog: false,
      });
      wx.vibrateShort &&
        wx.vibrateShort({
          type: "light",
        });
      wx.switchTab({
        url,
      });
    },
    switchDialog() {
      this.setData({
        dialog: !this.data.dialog,
      });
    },
    hiddenTab() {
      this.setData({
        hidden: true,
      });
    },
    showTab() {
      this.setData({
        hidden: false,
      });
    },
    login(e) {
      login(e);
    },
    scanCode() {
      scanCode()
    },
    inputCode() {
      wx.navigateTo({
        url: "/pages-charge/codeing/codeing",
      });
    },
    toCharging() {
      wx.navigateTo({
        url: `/pages-charge/ordering/ordering?sn=${this.data.charging}&start=1`,
      });
    },
  },
});
