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

<script lang="ts" setup>
import { getCode, updateUserPassword } from '@/api/login'
import { t } from '@/locale'
import { useUserStore } from '@/store'
import { goBack as goBackUtil, toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'ForgotPassword', // 忘记密码
})

const userStore = useUserStore()
const isLogined = computed(() => {
  return !!userStore.token
})

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

// 步骤控制：1-输入手机号，2-重置密码
const step = ref(1)

// 表单数据
const formData = ref({
  phone: isLogined.value ? userStore.userInfo.phoneNo : '',
  verifyCode: '',
  newPwd: '',
  confirmPwd: '',
})
// 验证码倒计时
const countdown = ref(0)
const countdownTimer = ref<any>(null)

// 获取验证码
async function getVerificationCode() {
  // 验证手机号
  if (!formData.value.phone.trim()) {
    toast.error(t('auth.forgotPassword.error.emptyPhone'))
    return
  }

  // 孟加拉手机号校验：可接受本地格式 01xxxxxxxxx (11 位) 或去掉前导 0 的 1xxxxxxxxx (10 位)
  const phoneDigits = formData.value.phone.replace(/\D/g, '')
  const bdPhoneRegex = /^0?1\d{9}$/
  if (!bdPhoneRegex.test(phoneDigits)) {
    toast.error(t('auth.register.error.invalidPhone'))
    return
  }

  // 防止重复点击
  if (countdown.value > 0) {
    return
  }

  try {
    // 显示加载状态
    uni.showLoading({
      title: t('common.loading'),
      mask: true,
    })

    // 调用获取验证码接口
    await getCode(`88${formData.value.phone}`)

    uni.hideLoading()
    toast.success(t('auth.forgotPassword.success.codeSent'))

    // 开始倒计时
    countdown.value = 60
    countdownTimer.value = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer.value!)
        countdownTimer.value = null
      }
    }, 1000)
  }
  catch (error) {
    uni.hideLoading()
    toast.error(error.message || t('auth.forgotPassword.error.sendCodeFailed'))
  }
}

// 第一步：验证手机号
function handleStep1() {
  // 验证手机号
  if (!formData.value.phone.trim()) {
    toast.error(t('auth.forgotPassword.error.emptyPhone'))
    return
  }

  // 孟加拉手机号校验：可接受本地格式 01xxxxxxxxx (11 位) 或去掉前导 0 的 1xxxxxxxxx (10 位)
  const phoneDigits = formData.value.phone.replace(/\D/g, '')
  const bdPhoneRegex = /^0?1\d{9}$/
  if (!bdPhoneRegex.test(phoneDigits)) {
    toast.error(t('auth.register.error.invalidPhone'))
    return
  }

  // 跳转到第二步
  step.value = 2
}

// 第二步：重置密码
async function handleResetPassword() {
  try {
    // 表单验证
    const isValid = await validateResetForm()
    if (!isValid)
      return

    // 显示加载状态
    uni.showLoading({
      title: t('common.saving'),
      mask: true,
    })

    // 调用重置密码接口
    const resetData = {
      phoneNo: formData.value.phone,
      newPwd: formData.value.newPwd,
      verifyCode: formData.value.verifyCode,
    }

    await updateUserPassword(resetData)

    uni.hideLoading()
    toast.success(t('auth.forgotPassword.success.passwordReset'))

    // 跳转到登录页
    setTimeout(() => {
      toPage({ url: '/pages/login/login', isReLaunch: true })
    }, 1500)
  }
  catch (error) {
    uni.hideLoading()
    toast.error(error.message || t('auth.forgotPassword.error.resetFailed'))
  }
}

// 重置密码表单验证
function validateResetForm() {
  return new Promise((resolve) => {
    // 验证验证码
    if (!formData.value.verifyCode.trim()) {
      toast.error(t('auth.forgotPassword.error.emptyVerifyCode'))
      resolve(false)
      return
    }

    // 验证新密码
    if (!formData.value.newPwd.trim()) {
      toast.error(t('auth.forgotPassword.error.emptyNewPassword'))
      resolve(false)
      return
    }

    // 验证密码长度
    if (formData.value.newPwd.length < 6 || formData.value.newPwd.length > 20) {
      toast.error(t('auth.forgotPassword.error.passwordLength'))
      resolve(false)
      return
    }

    // 验证确认密码
    if (!formData.value.confirmPwd.trim()) {
      toast.error(t('auth.forgotPassword.error.emptyConfirmPassword'))
      resolve(false)
      return
    }

    // 验证两次密码是否一致
    if (formData.value.newPwd !== formData.value.confirmPwd) {
      toast.error(t('auth.forgotPassword.error.passwordMismatch'))
      resolve(false)
      return
    }

    resolve(true)
  })
}

// 返回上一页
function goBack() {
  if (step.value === 2) {
    step.value = 1
  }
  else {
    goBackUtil()
  }
}

// 页面卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})
</script>

<template>
  <view class="forgot-password-page relative 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="thin-arrow-left" size="32rpx" @click="() => goBack()" />
        </view>
      </view>

      <!-- Logo和标语 -->
      <view class="pb-40rpx pt-134rpx text-center">
        <view class="mb-20rpx flex flex-col items-center justify-center">
          <image src="/static/login-logo.png" class="mb-18rpx h-56rpx w-350.48rpx" />
          <view>{{ $t('login.slogan') }}</view>
        </view>
      </view>
    </view>

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

      <!-- 第一步：输入手机号 -->
      <view v-if="step === 1">
        <wd-form ref="form" :model="formData">
          <view class="bandhu-auth-input-field phone-input-wrapper mb-60rpx" style="border: none; display:flex;align-items:center;">
            <view class="phone-area-code" style="padding:0 8rpx;font-size:28rpx;color:#333">
              +88
            </view>
            <wd-input
              v-model="formData.phone"
              prop="phone"
              :placeholder="t('auth.forgotPassword.phone.placeholder')"
              no-border
              :readonly="isLogined"
              type="number"
              custom-class="flex-1"
            />
          </view>

          <!-- 重置密码按钮 -->
          <wd-button
            size="large"
            block
            custom-class="mb-40rpx"
            @click="handleStep1"
          >
            {{ $t('auth.forgotPassword.button') }}
          </wd-button>
        </wd-form>
      </view>

      <!-- 第二步：重置密码 -->
      <view v-else>
        <wd-form ref="form" :model="formData">
          <view class="mb-40rpx space-y-32rpx">
            <view class="bandhu-auth-input-field phone-input-wrapper" style="border: none; display:flex;align-items:center;">
              <view class="phone-area-code" style="padding:0 8rpx;font-size:28rpx;color:#333">
                +88
              </view>
              <wd-input
                v-model="formData.phone"
                prop="phone"
                no-border
                readonly
                type="number"
                custom-class="flex-1"
              />
            </view>
            <view class="flex items-center gap-20rpx">
              <wd-input
                v-model="formData.verifyCode"
                prop="verifyCode"
                :placeholder="t('auth.forgotPassword.verifyCode.placeholder')"
                no-border
                type="number"
                custom-class="flex-1 bandhu-auth-input-field"
              />
              <wd-button
                plain
                :disabled="countdown > 0"
                custom-class="bandhu-auth-secondary-btn"
                @click="getVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}s` : t('auth.forgotPassword.getCode') }}
              </wd-button>
            </view>
            <wd-input
              v-model="formData.newPwd"
              prop="newPwd"
              :placeholder="t('auth.forgotPassword.newPassword.placeholder')"
              no-border show-password
              custom-class="bandhu-auth-input-field"
            />
            <wd-input
              v-model="formData.confirmPwd"
              prop="confirmPwd"
              show-password
              :placeholder="t('auth.forgotPassword.confirmPassword.placeholder')"
              no-border
              custom-class="bandhu-auth-input-field"
            />
          </view>

          <!-- 密码提示 -->
          <view class="mb-28rpx px-20rpx text-center text-#5C5C5C line-height-56rpx">
            {{ $t('auth.forgotPassword.passwordHint') }}
          </view>

          <!-- 重置密码按钮 -->
          <wd-button
            size="large"
            block
            custom-class="mb-40rpx"
            @click="handleResetPassword"
          >
            {{ $t('auth.forgotPassword.button') }}
          </wd-button>
        </wd-form>
      </view>

      <!-- 登录提示 -->
      <view v-if="!isLogined" class="absolute bottom-20rpx left-0 w-full text-center" :style="{ bottom: `${safeAreaInsets?.bottom + 20}px` }">
        <text class="text-28rpx text-#5C5C5C">
          {{ $t('auth.forgotPassword.hasAccount') }}
        </text>
        <text class="ml-10rpx text-28rpx text-[var(--wot-color-theme)]" @click="toPage({ url: '/pages/login/login' })">
          {{ $t('auth.forgotPassword.loginNow') }}
        </text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 忘记密码页面特有样式（如果有的话）
</style>
