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

<script lang="ts" setup>
import { getCode, register } from '@/api/login'
import DialogBox from '@/components/DialogBox/DialogBox.vue'
import { DialogUtils } from '@/components/DialogBox/utils'
import { t } from '@/locale'
import { 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: '',
  verifyCode: '',
  pwd: '',
  code: '',
  // 固定区号入参
  areaCode: '88',
})
onLoad((options) => {
  if (options.referrer) {
    formData.value.code = options.referrer as string
  }
})
// 验证码倒计时
const countdown = ref(0)
const countdownTimer = ref<any>(null)

// 获取验证码
async function getVerificationCode() {
  // 验证手机号
  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')
  }
}
// DialogBox 函数式调用配置
const dialogConfig = ref<any>({})
// 显示取消订单确认对话框
function showSuccessDialog() {
  Object.assign(dialogConfig.value, DialogUtils.success(
    'Register Successfully',
    {
      confirmText: 'Download App Now',
    },
  ))
}
// 处理对话框确认事件
function handleDialogConfirm() {
  // 关闭对话框
  handleDialogClose()
  // 跳转到应用商店下载页面
  window.location.href = 'https://static-mp-489f4121-636a-44cd-b309-a132a68309a7.next.bspapp.com/download' // 替换为实际的应用商店链接
}

// 处理对话框关闭事件
function handleDialogClose() {
  dialogConfig.value.show = false
}

// 注册处理
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'))
    showSuccessDialog()
  }
  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">
      <!-- Logo和标语 -->
      <view class="pb-40rpx pt-234rpx 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
              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
              custom-class="flex-1 bandhu-auth-input-field"
            />
            <wd-button
              type="error"
              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
          type="error"
          size="large"
          custom-class="mb-200rpx w-full bandhu-auth-primary-btn"
          @click="handleRegister"
        >
          {{ $t('auth.register.button') }}
        </wd-button>
      </wd-form>

      <!-- 登录提示 -->
      <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>
        <text class="ml-10rpx text-28rpx text-[var(--wot-color-theme)]">
          Security Privacy
        </text>
      </view>
    </view>
    <!-- DialogBox 函数式调用 -->
    <DialogBox
      v-bind="dialogConfig"
      @confirm="handleDialogConfirm"
      @cancel="handleDialogClose"
      @close="handleDialogClose"
    />
  </view>
</template>

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