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

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

defineOptions({
  name: 'Register', // 注册
})

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

// 表单数据
const formData = ref({
  name: '',
  // phone 存储不带区号的手机号数字部分
  phone: '',
  verifyCode: '',
  pwd: '',
  code: '',
  // 固定区号入参
  areaCode: '88',
})

onLoad((options) => {
  const rawReferrer = (options as any)?.referrer ?? (options as any)?.code
  if (!rawReferrer)
    return

  if (formData.value.code?.trim())
    return

  try {
    formData.value.code = decodeURIComponent(String(rawReferrer))
  }
  catch {
    formData.value.code = String(rawReferrer)
  }
})

// 验证码倒计时
const countdown = ref(0)
const countdownTimer = ref<any>(null)

// 获取验证码
async function getVerificationCode() {
  // 验证手机号（不包含区号，固定 +88）
  if (!formData.value.phone.trim()) {
    toast.error(t('auth.register.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.register.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 || 'Failed to send verification code')
  }
}

// 注册处理
async function handleRegister() {
  try {
    // 表单验证
    const isValid = await validateForm()
    if (!isValid)
      return

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

    // 调用注册接口
    const registerData = {
      name: formData.value.name,
      // 发送时附带区号字段areaCode，phone字段为不带区号的手机号
      phone: formData.value.phone,
      areaCode: formData.value.areaCode,
      verifyCode: formData.value.verifyCode,
      pwd: formData.value.pwd,
      code: formData.value.code,
    }

    await register(registerData)

    uni.hideLoading()
    // 注册成功
    toast.success(t('auth.register.success.registered'))
    setTimeout(() => {
      toPage({ url: '/pages/login/login', params: { redirect: '/pages/index/index' }, isRedirect: true })
    }, 1500)
  }
  catch (error) {
    uni.hideLoading()
    toast.error(error.message || t('auth.register.error.registrationFailed'))
  }
}

// 表单验证
function validateForm() {
  return new Promise((resolve) => {
    // 验证必填字段
    if (!formData.value.name.trim()) {
      toast.error(t('auth.register.error.emptyUsername'))
      resolve(false)
      return
    }

    if (!formData.value.phone.trim()) {
      toast.error(t('auth.register.error.emptyPhone'))
      resolve(false)
      return
    }

    // 孟加拉手机号校验：支持 01xxxxxxxxx 或 1xxxxxxxxx
    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'))
      resolve(false)
      return
    }

    if (!formData.value.verifyCode.trim()) {
      toast.error(t('auth.register.error.emptyVerifyCode'))
      resolve(false)
      return
    }

    if (!formData.value.pwd.trim()) {
      toast.error(t('auth.register.error.emptyPassword'))
      resolve(false)
      return
    }

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

    resolve(true)
  })
}

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

<template>
  <view class="register-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" />

      <!-- 注册表单 -->
      <wd-form ref="form" :model="formData">
        <view class="mb-40rpx space-y-32rpx">
          <wd-input
            v-model="formData.name"
            prop="name"
            :placeholder="t('auth.register.username.placeholder')"
            no-border
            custom-class="bandhu-auth-input-field"
          />
          <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"
              :placeholder="t('auth.register.phone.placeholder')"
              no-border
              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.register.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.register.getCode') }}
            </wd-button>
          </view>
          <wd-input
            v-model="formData.pwd"
            prop="pwd"
            :placeholder="t('auth.register.password.placeholder')"
            no-border
            show-password
            custom-class="bandhu-auth-input-field"
          />
          <wd-input
            v-model="formData.code"
            :placeholder="t('auth.register.referrerCode.placeholder')"
            no-border
            custom-class="bandhu-auth-input-field"
          />
        </view>

        <!-- 注册按钮 -->
        <wd-button
          size="large"
          block
          custom-class="mb-40rpx"
          @click="handleRegister"
        >
          {{ $t('auth.register.button') }}
        </wd-button>
      </wd-form>

      <!-- 登录提示 -->
      <view class="text-center">
        <text class="text-28rpx text-#5C5C5C">
          {{ $t('auth.register.hasAccount') }}
        </text>
        <text class="ml-10rpx text-28rpx text-[var(--wot-color-theme)]" @click="toPage({ url: '/pages/login/login' })">
          {{ $t('auth.register.loginNow') }}
        </text>
      </view>
      <view class="absolute w-full text-center" :style="{ bottom: `${safeAreaInsets?.bottom + 20}px` }">
        <text class="text-28rpx text-#5C5C5C">
          By regstration,you agree to our
        </text>
        <view>
          <text class="ml-10rpx text-28rpx text-#007aff" @click="toPage({ url: '/pages/webLink/webLink', params: { title: t('setting.policies'), link: 'https://www.aisoco.net/privacy.html' } })">
            {{ t('setting.policies') }}
          </text>
          <text class="ml-10rpx text-28rpx text-#5C5C5C">
            and
          </text>
          <text class="ml-10rpx text-28rpx text-#007aff" @click="toPage({ url: '/pages/webLink/webLink', params: { title: t('setting.termsOfService'), link: 'https://www.aisoco.net/terms.html' } })">
            {{ t('setting.termsOfService') }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

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