<template>
	<view class="auth-page">
		<view class="auth-hero">
			<view class="auth-hero__brand">
				<text class="auth-hero__app">巴青农资商城</text>
				<text class="auth-hero__welcome">会员注册</text>
			</view>
		</view>

		<view class="auth-body">
			<view class="auth-card">
				<text class="auth-card__title">手机号注册</text>
				<text class="auth-card__sub">无需短信验证码，设置密码即可注册</text>

				<view v-if="!agreement.registrationOpen" class="auth-closed">
					<text>{{ agreement.message || '会员注册暂未开放' }}</text>
				</view>

				<template v-else>
					<view class="auth-field">
						<view class="auth-field__box">
							<u-icon name="phone" color="#6b7f72" size="22" />
							<input
								v-model="form.mobile"
								class="auth-field__input"
								type="number"
								maxlength="11"
								placeholder="请输入手机号"
								placeholder-class="auth-field__placeholder"
							/>
						</view>
					</view>

					<view class="auth-field">
						<view class="auth-field__box">
							<u-icon name="lock" color="#6b7f72" size="22" />
							<input
								v-model="form.password"
								class="auth-field__input"
								type="password"
								placeholder="请设置登录密码（至少6位）"
								placeholder-class="auth-field__placeholder"
							/>
						</view>
					</view>

					<view class="auth-field">
						<view class="auth-field__box">
							<u-icon name="lock-fill" color="#6b7f72" size="22" />
							<input
								v-model="form.confirmPassword"
								class="auth-field__input"
								type="password"
								placeholder="请再次输入密码"
								placeholder-class="auth-field__placeholder"
							/>
						</view>
					</view>

					<!-- <view class="auth-field">
						<view class="auth-field__box">
							<u-icon name="account" color="#6b7f72" size="22" />
							<input
								v-model="form.memberCode"
								class="auth-field__input"
								type="text"
								placeholder="会员名称/会员 ID（选填，不填自动生成）"
								placeholder-class="auth-field__placeholder"
							/>
						</view>
					</view> -->

					<agreement-block
						v-model="form.agreementAccepted"
						:enabled="agreement.enabled"
						:checkbox-label="agreement.checkboxLabel"
						:agreement-title="agreement.agreementTitle"
						:version-label="agreement.versionLabel"
						:content="agreement.content"
					/>

					<view
						:class="['auth-btn', { 'auth-btn--loading': loading }]"
						:disabled="loading"
						@click="handleRegister"
					>
						<text class="auth-btn__txt">{{ loading ? '提交中…' : '注 册' }}</text>
					</view>
				</template>

				<view class="auth-switch">
					<text>已有账号？</text>
					<text class="auth-switch__link" @click="goLogin">去登录</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { memberRegister } from '@/api/member'
import { loadServiceAgreement } from '@/utils/memberAgreement'
import { validateMobile, validatePassword } from '@/utils/memberValidate'
import { PAGE_LOGIN } from '@/utils/pageRoute'
import AgreementBlock from '@/components/account/AgreementBlock.vue'

import { useActionGuard } from '@/utils/actionGuard'

const registerGuard = useActionGuard()
const loading = registerGuard.locked
const agreement = reactive({
  enabled: false,
  registrationOpen: true,
  requireAgreementOnLogin: false,
  message: '',
  agreementTitle: '',
  versionLabel: '',
  content: '',
  checkboxLabel: ''
})

const form = reactive({
  mobile: '',
  password: '',
  confirmPassword: '',
  memberCode: '',
  agreementAccepted: false
})

onLoad(async (options) => {
  const cfg = await loadServiceAgreement()
  Object.assign(agreement, cfg)
  if (options && options.mobile) {
    form.mobile = decodeURIComponent(options.mobile)
  }
})

function goLogin() {
  const q = form.mobile ? `?account=${encodeURIComponent(form.mobile.trim())}` : ''
  uni.navigateTo({ url: `${PAGE_LOGIN}${q}` })
}

function validateForm() {
  const mobileMsg = validateMobile(form.mobile)
  if (mobileMsg) {
    uni.showToast({ title: mobileMsg, icon: 'none' })
    return false
  }
  const pwdMsg = validatePassword(form.password)
  if (pwdMsg) {
    uni.showToast({ title: pwdMsg, icon: 'none' })
    return false
  }
  if (form.password !== form.confirmPassword) {
    uni.showToast({ title: '两次输入的密码不一致', icon: 'none' })
    return false
  }
  if (agreement.enabled && !form.agreementAccepted) {
    uni.showToast({ title: '请先阅读并同意服务协议', icon: 'none' })
    return false
  }
  return true
}

function handleRegister() {
  if (!agreement.registrationOpen) return
  registerGuard.run(async () => {
    if (!validateForm()) return
    await memberRegister({
      mobile: form.mobile.trim(),
      password: form.password,
      confirmPassword: form.confirmPassword,
      memberCode: (form.memberCode || '').trim() || undefined,
      agreementAccepted: agreement.enabled ? form.agreementAccepted : true
    })
    uni.showToast({ title: '注册成功，请登录', icon: 'none', duration: 2000 })
    setTimeout(() => {
      goLogin()
    }, 1500)
  })
}
</script>

<style lang="scss" scoped>
@import '@/styles/auth.scss';
</style>
