<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
  },
}
</route>

<script lang="ts" setup>
import { useUserStore } from '@/store/user'
import { goBack, toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'Login', // 登录
})

// 获取屏幕边界到安全区域距离
const systemInfo = uni.getSystemInfoSync()
const safeAreaInsets = systemInfo.safeAreaInsets

// 用户状态管理
const userStore = useUserStore()

// 表单数据
const formData = ref({
  username: '',
  password: '',
})

// 表单验证
function validateForm() {
  return new Promise((resolve) => {
    // 验证用户名
    if (!formData.value.username.trim()) {
      toast.error('Please enter username or phone number')
      resolve(false)
      return
    }

    // 验证密码
    if (!formData.value.password.trim()) {
      toast.error('Please enter password')
      resolve(false)
      return
    }

    // 验证密码长度
    if (formData.value.password.length < 6 || formData.value.password.length > 20) {
      toast.error('Password should be 6-20 characters')
      resolve(false)
      return
    }

    resolve(true)
  })
}

// 登录处理
async function handleLogin() {
  try {
    // 表单验证
    const isValid = await validateForm()
    if (!isValid)
      return

    // 准备登录数据
    const loginData = {
      account: formData.value.username,
      pwd: formData.value.password,
    }

    // 获取页面参数中的跳转地址（如果有的话）
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1] as any
    const redirectUrl = currentPage?.options?.redirect

    // 调用 userStore 中的登录方法，传入跳转地址
    await userStore.login(loginData, redirectUrl)
  }
  catch (error) {
    // 错误处理已在 userStore.login 中处理
    console.error('Login error:', error)
  }
}
</script>

<template>
  <view class="login-page min-h-screen bg-white">
    <!-- 背景图片区域 -->
    <view class="auth-bg-section relative">
      <!-- 自定义导航栏 -->
      <view :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
        <view class="h-88rpx flex items-center px-24rpx">
          <wd-icon name="arrow-left" size="48rpx" color="#333" @click="goBack" />
        </view>
      </view>

      <!-- Logo和标语 -->
      <view class="pb-60rpx pt-60rpx text-center">
        <view class="mb-20rpx flex items-center justify-center">
          <image src="/static/logo.png" class="mr-16rpx h-60rpx w-60rpx" />
        </view>
      </view>
    </view>

    <!-- 表单内容区域 -->
    <view class="flex flex-col px-20rpx">
      <view class="mb-40rpx" />

      <!-- 登录表单 -->
      <wd-form ref="form" :model="formData">
        <view class="mb-40rpx space-y-32rpx">
          <wd-input
            v-model="formData.username"
            prop="username"
            placeholder="Mobile number / Username"
            no-border
            custom-class="bandhu-auth-input-field"
          />
          <wd-input
            v-model="formData.password"
            prop="password"

            placeholder="Password 6-20 characters"
            no-border show-password
            custom-class="bandhu-auth-input-field"
          />
        </view>

        <!-- 登录按钮 -->
        <wd-button
          type="error"
          size="large"
          custom-class="mb-60rpx w-full bandhu-auth-primary-btn"
          @click="handleLogin"
        >
          Login
        </wd-button>
      </wd-form>

      <!-- 注册提示 -->
      <view class="mb-200rpx text-center">
        <text class="text-28rpx text-#5C5C5C">
          Do Not Have An Account Yet?
        </text>
        <view class="mt-52rpx">
          <wd-button
            type="error"
            plain
            custom-style="width: 200rpx; height: 72rpx; border-radius: 36rpx; font-size: 28rpx;"
            @click="toPage('/pages/register/register')"
          >
            Register
          </wd-button>
        </view>
      </view>

      <!-- 忘记密码 -->
      <view class="text-center">
        <text class="text-28rpx text-#5C5C5C" @click="toPage('/pages/forgotPassword/forgotPassword')">
          Forgot Password?
        </text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 登录页面特有样式（如果有的话）
</style>
