<template>
	<view class="fe-page fe-page--white reset-page">
		<scroll-view scroll-y class="reset-scroll" :show-scrollbar="false">
			<view class="reset-inner">
				<view class="reset-head">
					<text class="reset-head__title">重置密码</text>
					<text class="reset-head__desc">验证手机号后设置新登录密码</text>
				</view>

				<view class="fe-form-group">
					<text class="fe-form-label">手机号</text>
					<input
						class="fe-form-input"
						type="number"
						v-model="form.mobile"
						maxlength="11"
						placeholder="请输入注册手机号"
					/>
				</view>

				<view class="fe-form-group">
					<text class="fe-form-label">验证码</text>
					<view class="fe-form-row">
						<input
							class="fe-form-input"
							v-model="form.code"
							maxlength="6"
							placeholder="请输入验证码"
						/>
						<view
							class="fe-btn fe-btn--secondary reset-sms-btn"
							:class="{ 'reset-btn--disabled': smsCountdown > 0 || smsSending }"
							@tap="sendSmsCode"
						>{{ smsBtnText }}</view>
					</view>
				</view>

				<view class="fe-form-group">
					<text class="fe-form-label">新密码</text>
					<view class="reset-password-field">
						<input
							class="fe-form-input reset-password-field__input"
							v-model="form.password"
							:password="!showPassword"
							maxlength="64"
							placeholder="8-64 位，须含字母和数字"
						/>
						<view class="reset-password-field__eye" @tap="showPassword = !showPassword">
							<uni-icons
								:type="showPassword ? 'eye-filled' : 'eye-slash-filled'"
								color="#9CA3AF"
								size="22"
							></uni-icons>
						</view>
					</view>
				</view>

				<view class="fe-form-group">
					<text class="fe-form-label">确认新密码</text>
					<view class="reset-password-field">
						<input
							class="fe-form-input reset-password-field__input"
							v-model="form.confirmPassword"
							:password="!showConfirmPassword"
							maxlength="64"
							placeholder="请再次输入新密码"
						/>
						<view class="reset-password-field__eye" @tap="showConfirmPassword = !showConfirmPassword">
							<uni-icons
								:type="showConfirmPassword ? 'eye-filled' : 'eye-slash-filled'"
								color="#9CA3AF"
								size="22"
							></uni-icons>
						</view>
					</view>
				</view>

				<view
					class="fe-btn fe-btn--primary fe-btn--lg fe-btn--full"
					:class="{ 'reset-btn--disabled': submitting }"
					@tap="submit"
				>{{ submitting ? '提交中...' : '确认重置' }}</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { sendLoginSmsCode, resetPasswordBySms } from '@/api/login.js'
import { showToast } from '@/common/chat-data.js'
import { validateForm, mobile, password, confirmPassword } from '@/utils/formRules.js'
import { encryptPasswordWithFetch, fetchPasswordPublicKey } from '@/utils/rsaEncrypt.js'

const SMS_COUNTDOWN_SECONDS = 60

export default {
	data() {
		return {
			userType: 'enterprise',
			form: {
				mobile: '',
				code: '',
				password: '',
				confirmPassword: ''
			},
			smsCountdown: 0,
			smsSending: false,
			smsTimer: null,
			submitting: false,
			showPassword: false,
			showConfirmPassword: false
		}
	},
	computed: {
		smsBtnText() {
			if (this.smsSending) return '发送中...'
			if (this.smsCountdown > 0) return `${this.smsCountdown}s后重新获取`
			return '获取验证码'
		}
	},
	onLoad(options) {
		if (options.userType === 'worker' || options.userType === 'enterprise') {
			this.userType = options.userType
		}
		fetchPasswordPublicKey({ showError: false }).catch(() => {})
	},
	onUnload() {
		this.clearSmsTimer()
	},
	methods: {
		clearSmsTimer() {
			if (this.smsTimer) {
				clearInterval(this.smsTimer)
				this.smsTimer = null
			}
		},
		startSmsCountdown(seconds = SMS_COUNTDOWN_SECONDS) {
			this.clearSmsTimer()
			this.smsCountdown = seconds
			this.smsTimer = setInterval(() => {
				if (this.smsCountdown <= 1) {
					this.smsCountdown = 0
					this.clearSmsTimer()
				} else {
					this.smsCountdown -= 1
				}
			}, 1000)
		},
		async sendSmsCode() {
			if (this.smsCountdown > 0 || this.smsSending) return

			const check = mobile(this.form.mobile)
			if (!check.valid) {
				showToast(check.message)
				return
			}

			this.smsSending = true
			try {
				const res = await sendLoginSmsCode({
					mobile: this.form.mobile.trim(),
					userType: this.userType
				})
				showToast(res && res.mockEnabled ? '验证码已发送（测试环境：123456）' : '验证码已发送')
				this.startSmsCountdown(SMS_COUNTDOWN_SECONDS)
			} catch (e) {
				// request.js 统一提示
			} finally {
				this.smsSending = false
			}
		},
		validateFormData() {
			const base = validateForm(this.form, {
				mobile: { label: '手机号', rules: ['mobile'] },
				code: { label: '验证码', rules: ['smsCode'] },
				password: { label: '新密码', rules: ['password'] }
			})
			if (!base.valid) return base

			const confirmCheck = confirmPassword(
				this.form.confirmPassword,
				this.form.password,
				'两次输入的新密码不一致'
			)
			if (!confirmCheck.valid) {
				return { valid: false, message: confirmCheck.message }
			}

			if (this.form.password.trim() === this.form.mobile.trim()) {
				return { valid: false, message: '密码不能与手机号相同' }
			}

			return { valid: true, message: '' }
		},
		async submit() {
			if (this.submitting) return

			const validation = this.validateFormData()
			if (!validation.valid) {
				showToast(validation.message)
				return
			}

			this.submitting = true
			try {
				const encryptedPassword = await encryptPasswordWithFetch(this.form.password)
				const encryptedConfirmPassword = await encryptPasswordWithFetch(this.form.confirmPassword)

				await resetPasswordBySms({
					mobile: this.form.mobile.trim(),
					code: this.form.code.trim(),
					encryptedPassword,
					encryptedConfirmPassword
				})

				showToast('密码重置成功')
				setTimeout(() => {
					uni.navigateBack()
				}, 800)
			} catch (e) {
				if (e && e.message && !e.code) {
					showToast(e.message)
				}
			} finally {
				this.submitting = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.reset-page {
	min-height: 100vh;
}

.reset-scroll {
	height: 100vh;
}

.reset-inner {
	padding: 48rpx 32rpx;
	padding-bottom: calc(48rpx + #{$fe-h-safe-bottom});
}

.reset-head {
	margin-bottom: 48rpx;
}

.reset-head__title {
	display: block;
	font-size: 40rpx;
	font-weight: 700;
	color: $fe-foreground;
	margin-bottom: 12rpx;
}

.reset-head__desc {
	display: block;
	font-size: 28rpx;
	color: $fe-gray-500;
}

.reset-sms-btn {
	white-space: nowrap;
	padding: 0 24rpx;
	height: 96rpx;
	min-width: 200rpx;
}

.reset-btn--disabled {
	opacity: 0.5;
	pointer-events: none;
}

.reset-password-field {
	position: relative;
}

.reset-password-field__input {
	width: 100%;
	padding-right: 88rpx;
	box-sizing: border-box;
}

.reset-password-field__eye {
	position: absolute;
	right: 24rpx;
	top: 50%;
	transform: translateY(-50%);
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 8rpx;
	z-index: 2;
}
</style>
