<template>
  <view class="root">
    <view class="center">
      <image class="logo" src="/static/images/map-logo.png" mode="aspectFit" />

      <view class="spacer" />

      <button
        class="btn"
        open-type="getPhoneNumber"
        hover-class="btn-press"
        :loading="submitting"
        :disabled="submitting"
        @getphonenumber="handleLogin"
      >
        一键登录
      </button>

      <text v-if="errorMsg" class="err">{{ errorMsg }}</text>
    </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("");
const submitting = ref(false);
const errorMsg = ref("");

onLoad((query: Record<string, string | undefined>) => {
  if (isAuthenticated()) {
    performRedirect(query?.redirect || "");
    return;
  }
  if (query?.redirect) {
    redirect.value = decodeURIComponent(query.redirect);
  }
});

const handleLogin = (e: WechatMiniprogram.ButtonGetPhoneNumber) => {
  if (submitting.value) return;
  errorMsg.value = "";
  submitting.value = true;

  login(e)
    .then(() => {
      uni.showToast({ title: "登录成功", icon: "success", duration: 800 });
      setTimeout(() => performRedirect(redirect.value), 800);
    })
    .catch(() => {
      submitting.value = false;
      errorMsg.value = "登录失败，请重试";
    });
};

const performRedirect = (url: string) => {
  if (url && isTabBarPage(url)) return uni.switchTab({ url });
  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>
.root {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-sec);
  padding: 0 56rpx 160rpx;
}

.center {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

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

.spacer {
  height: 80rpx;
}

.btn {
  width: 100%;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--color-primary);
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 50rpx;
  border: none;
}

.btn::after {
  border: none;
}

.btn-press {
  opacity: 0.82;
}

.err {
  margin-top: 28rpx;
  font-size: 24rpx;
  color: var(--color-warning);
}
</style>
