<template>
	<view class="auth-page">
		<view class="page-inner">
			<view class="nav-back" @tap="goBack">
				<FaIcon name="chevron-left" color="#303133" :size="18" />
				<text class="nav-text">返回</text>
			</view>

			<view class="header">
				<text class="title">注册账号</text>
				<text class="subtitle">按租户创建管理员账号</text>
			</view>

			<view class="form-card">
				<view class="form">
					<view class="field">
						<u-input
							v-model="form.tenant_name"
							placeholder="租户名称"
							border="none"
							color="#303133"
							:customStyle="inputStyle"
							:placeholderStyle="placeholderStyle"
						/>
					</view>
					<view class="field">
						<u-input
							v-model="form.account"
							placeholder="账号"
							border="none"
							color="#303133"
							:customStyle="inputStyle"
							:placeholderStyle="placeholderStyle"
						/>
					</view>
					<view class="field">
						<u-input
							v-model="form.name"
							placeholder="姓名"
							border="none"
							color="#303133"
							:customStyle="inputStyle"
							:placeholderStyle="placeholderStyle"
						/>
					</view>
					<view class="field">
						<u-input
							v-model="form.phone"
							placeholder="手机号"
							type="number"
							maxlength="11"
							border="none"
							color="#303133"
							:customStyle="inputStyle"
							:placeholderStyle="placeholderStyle"
						/>
					</view>
					<view class="field field-row">
						<u-input
							v-model="form.sms_code"
							placeholder="短信验证码"
							type="number"
							maxlength="6"
							border="none"
							color="#303133"
							:customStyle="inputStyle"
							:placeholderStyle="placeholderStyle"
						/>
						<text
							class="code-link"
							:class="{ disabled: countdown > 0 || codeLoading }"
							@tap="handleSendCode"
						>{{ countdown > 0 ? `${countdown}s` : (codeLoading ? '发送中' : '获取验证码') }}</text>
					</view>
					<view class="field">
						<u-input
							v-model="form.email"
							placeholder="邮箱（可选）"
							border="none"
							color="#303133"
							:customStyle="inputStyle"
							:placeholderStyle="placeholderStyle"
						/>
					</view>
					<view class="field">
						<u-input
							v-model="form.password"
							placeholder="密码"
							type="password"
							border="none"
							color="#303133"
							:customStyle="inputStyle"
							:placeholderStyle="placeholderStyle"
						/>
					</view>
					<view class="field">
						<u-input
							v-model="form.confirm_password"
							placeholder="确认密码"
							type="password"
							border="none"
							color="#303133"
							:customStyle="inputStyle"
							:placeholderStyle="placeholderStyle"
						/>
					</view>

					<view class="btn-primary" :class="{ disabled: loading }" @tap="handleSubmit">
						{{ loading ? '提交中...' : '注 册' }}
					</view>
					<view class="footer-link" @tap="goBack">
						<text>已有账号？去登录</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { reactive, ref, onUnmounted } from 'vue'
import { register, sendRegisterCode } from '@/api/auth.js'
import { setTenantName } from '@/utils/auth.js'

const loading = ref(false)
const codeLoading = ref(false)
const countdown = ref(0)
let timer = null

const form = reactive({
	tenant_name: '',
	account: '',
	name: '',
	phone: '',
	sms_code: '',
	email: '',
	password: '',
	confirm_password: ''
})

const inputStyle = {
	backgroundColor: 'transparent',
	padding: '0 8rpx',
	height: '96rpx',
	fontSize: '28rpx'
}
const placeholderStyle = 'color: #909399; font-size: 28rpx'

function startCountdown() {
	countdown.value = 60
	if (timer) clearInterval(timer)
	timer = setInterval(() => {
		countdown.value -= 1
		if (countdown.value <= 0) {
			clearInterval(timer)
			timer = null
		}
	}, 1000)
}

async function handleSendCode() {
	if (codeLoading.value || countdown.value > 0) return
	if (!form.tenant_name || !form.account || !form.phone) {
		uni.showToast({ title: '请先填写租户、账号和手机号', icon: 'none' })
		return
	}
	if (!/^1\d{10}$/.test(form.phone)) {
		uni.showToast({ title: '请输入正确手机号', icon: 'none' })
		return
	}
	codeLoading.value = true
	try {
		await sendRegisterCode({
			tenant_name: form.tenant_name.trim(),
			account: form.account.trim(),
			phone: form.phone.trim()
		})
		uni.showToast({ title: '验证码已发送', icon: 'success' })
		startCountdown()
	} catch {
		// handled
	} finally {
		codeLoading.value = false
	}
}

async function handleSubmit() {
	if (loading.value) return
	if (!form.tenant_name.trim() || !form.account.trim() || !form.phone.trim()) {
		uni.showToast({ title: '请填写租户、账号和手机号', icon: 'none' })
		return
	}
	if (!form.password) {
		uni.showToast({ title: '请输入密码', icon: 'none' })
		return
	}
	if (form.password !== form.confirm_password) {
		uni.showToast({ title: '两次密码不一致', icon: 'none' })
		return
	}
	loading.value = true
	try {
		await register({
			tenant_name: form.tenant_name.trim(),
			account: form.account.trim(),
			name: form.name.trim(),
			phone: form.phone.trim(),
			sms_code: form.sms_code.trim(),
			email: form.email.trim(),
			password: form.password,
			confirm_password: form.confirm_password
		})
		setTenantName(form.tenant_name.trim())
		uni.showToast({ title: '注册成功，请登录', icon: 'success' })
		setTimeout(() => {
			uni.navigateBack({ fail: () => uni.reLaunch({ url: '/pages/login/login' }) })
		}, 500)
	} catch {
		// handled
	} finally {
		loading.value = false
	}
}

function goBack() {
	uni.navigateBack({ fail: () => uni.reLaunch({ url: '/pages/login/login' }) })
}

onUnmounted(() => {
	if (timer) clearInterval(timer)
})
</script>

<style lang="scss" scoped>
@import '@/src/styles/page-common.scss';

.auth-page {
	min-height: 100vh;
	background: $color-bg-page;
}

.page-inner {
	padding: 0 48rpx;
	padding-top: calc(var(--status-bar-height, 44px) + 24rpx);
	padding-bottom: 60rpx;
}

.nav-back {
	display: flex;
	align-items: center;
	gap: 4rpx;
	margin-bottom: 32rpx;
	padding: 8rpx 0;
}

.nav-text {
	font-size: 28rpx;
	color: $color-text;
}

.header {
	margin-bottom: 40rpx;
}

.title {
	display: block;
	font-size: 44rpx;
	font-weight: 600;
	color: $color-text;
}

.subtitle {
	display: block;
	font-size: 26rpx;
	color: $color-text-muted;
	margin-top: 12rpx;
}

.form-card {
	@include card;
	padding: 32rpx 28rpx;
}

.form {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.field {
	background: $color-bg-page;
	border-radius: $radius-md;
	padding: 0 24rpx;
	overflow: hidden;
}

.field-row {
	display: flex;
	align-items: center;
}

.code-link {
	flex-shrink: 0;
	font-size: 26rpx;
	color: $color-primary;
	padding-left: 16rpx;
	white-space: nowrap;

	&.disabled {
		color: $color-text-muted;
	}
}

.btn-primary {
	height: 96rpx;
	background: $color-primary;
	border-radius: $radius-md;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	font-weight: 600;
	color: #fff;
	margin-top: 12rpx;

	&:active {
		background: $color-primary-dark;
	}

	&.disabled {
		opacity: 0.7;
	}
}

.footer-link {
	text-align: center;
	font-size: 26rpx;
	color: $color-primary;
	padding: 16rpx 0 4rpx;
}
</style>
