<template>
  <view class="login-container">
    <view class="login-content">
      <image
        class="logo"
        src="/static/images/map-logo.png"
        mode="aspectFit"
      />
      <view class="title fs-36 fw-600 mt-40">欢迎使用充电桩</view>
      <view class="subtitle fs-28 color-666 mt-16">登录后可享受更多功能</view>
      <view class="btn-area mt-60">
        <button
          class="login-btn"
          open-type="getPhoneNumber"
          @getphonenumber="handleLogin"
        >
          微信手机号一键登录
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { login } from "@/api/auth";
import { isAuthenticated, isTabBarPage } from "@/utils/auth";
import { onLoad } from "@dcloudio/uni-app";
import { ref } from "vue";

const redirect = ref("");

onLoad((query: any) => {
  if (isAuthenticated()) {
    performRedirect(query?.redirect || "");
    return;
  }
  if (query?.redirect) {
    redirect.value = decodeURIComponent(query.redirect);
  }
});

const handleLogin = (e: any) => {
  login(e)
    .then(() => {
      uni.showToast({
        title: "登录成功",
        icon: "success",
        duration: 1000,
      });
      setTimeout(() => {
        performRedirect(redirect.value);
      }, 1000);
    })
    .catch(() => {});
};

const performRedirect = (url: string) => {
  if (url && isTabBarPage(url)) {
    uni.switchTab({ url });
    return;
  }
  if (url) {
    uni.navigateBack({
      fail() {
        uni.switchTab({ url: "/pages/map/map" });
      },
    });
    return;
  }
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack({
      fail() {
        uni.switchTab({ url: "/pages/map/map" });
      },
    });
  } else {
    uni.switchTab({ url: "/pages/map/map" });
  }
};
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fff;
  padding: 0 60rpx;
}

.login-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo {
  width: 180rpx;
  height: 180rpx;
}

.title {
  color: #000;
}

.subtitle {
  color: #999;
}

.btn-area {
  width: 100%;
}

.login-btn {
  width: 100%;
  height: 88rpx;
  background: var(--color-primary);
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  line-height: 88rpx;
  border: none;
}

.login-btn::after {
  border: none;
}
</style>
