<template>
	<view class="fe-page fe-page--white set-password-page">
		<scroll-view scroll-y class="set-password-scroll" :show-scrollbar="false">
			<view class="set-password-inner">
				<view class="set-password-head">
					<text class="set-password-head__title">{{ pageTitle }}</text>
					<text class="set-password-head__desc">{{ pageDesc }}</text>
				</view>

				<view v-if="loading" class="set-password-loading">
					<text class="set-password-loading__text">加载中...</text>
				</view>

				<block v-else>
					<view v-if="passwordSet && usernameMask" class="set-password-tip">
						<text>当前登录用户名：{{ usernameMask }}</text>
					</view>

					<view v-if="!passwordSet" class="fe-form-group">
						<text class="fe-form-label">登录用户名</text>
						<input
							class="fe-form-input"
							v-model="form.username"
							maxlength="20"
							placeholder="6-20 位，字母开头"
						/>
						<text class="set-password-hint">设置后可用于账号密码登录</text>
					</view>

					<view v-if="passwordSet" class="fe-form-group">
						<text class="fe-form-label">原密码</text>
						<view class="set-password-field">
							<input
								class="fe-form-input set-password-field__input"
								v-model="form.oldPassword"
								:password="!showOldPassword"
								maxlength="64"
								placeholder="请输入原密码"
							/>
							<view class="set-password-field__eye" @tap="showOldPassword = !showOldPassword">
								<uni-icons
									:type="showOldPassword ? 'eye-filled' : 'eye-slash-filled'"
									color="#9CA3AF"
									size="22"
								></uni-icons>
							</view>
						</view>
					</view>

					<view class="fe-form-group">
						<text class="fe-form-label">{{ passwordSet ? '新密码' : '登录密码' }}</text>
						<view class="set-password-field">
							<input
								class="fe-form-input set-password-field__input"
								v-model="form.password"
								:password="!showPassword"
								maxlength="64"
								placeholder="8-64 位，须含字母和数字"
							/>
							<view class="set-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="set-password-field">
							<input
								class="fe-form-input set-password-field__input"
								v-model="form.confirmPassword"
								:password="!showConfirmPassword"
								maxlength="64"
								placeholder="请再次输入密码"
							/>
							<view class="set-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="{ 'set-password-btn--disabled': submitting }"
						@tap="submit"
					>{{ submitting ? '提交中...' : submitBtnText }}</view>
				</block>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { getPasswordStatus, setLoginPassword } from '@/api/login.js'
import store from '@/common/store.js'
import { showToast } from '@/common/chat-data.js'
import { getToken } from '@/utils/request.js'
import { validateForm, confirmPassword } from '@/utils/formRules.js'
import { encryptPasswordWithFetch, fetchPasswordPublicKey } from '@/utils/rsaEncrypt.js'

export default {
	data() {
		return {
			from: '',
			loading: true,
			passwordSet: false,
			usernameMask: '',
			form: {
				username: '',
				oldPassword: '',
				password: '',
				confirmPassword: ''
			},
			submitting: false,
			showOldPassword: false,
			showPassword: false,
			showConfirmPassword: false
		}
	},
	computed: {
		pageTitle() {
			return this.passwordSet ? '修改登录密码' : '设置登录密码'
		},
		pageDesc() {
			return this.passwordSet
				? '验证原密码后设置新登录密码'
				: '首次设置登录用户名与密码，之后可使用账号密码登录'
		},
		submitBtnText() {
			return this.passwordSet ? '确认修改' : '确认设置'
		}
	},
	onLoad(options) {
		if (options.from === 'worker' || options.from === 'enterprise') {
			this.from = options.from
		}
	},
	onShow() {
		if (!getToken() || !store.getState().loggedIn) {
			uni.redirectTo({ url: '/packageA/auth/login' })
			return
		}
		this.loadStatus()
	},
	methods: {
		async loadStatus() {
			this.loading = true
			try {
				const res = await getPasswordStatus({ showError: true })
				this.passwordSet = !!(res && res.passwordSet)
				this.usernameMask = (res && res.usernameMask) || ''
				uni.setNavigationBarTitle({ title: this.pageTitle })
			} catch (e) {
				setTimeout(() => {
					uni.navigateBack()
				}, 800)
			} finally {
				this.loading = false
				fetchPasswordPublicKey({ showError: false }).catch(() => {})
			}
		},
		validateFormData() {
			const schema = {
				password: { label: this.passwordSet ? '新密码' : '登录密码', rules: ['password'] }
			}
			if (!this.passwordSet) {
				schema.username = { label: '登录用户名', rules: ['username'] }
			} else {
				schema.oldPassword = { label: '原密码', rules: ['password'] }
			}

			const base = validateForm(this.form, schema)
			if (!base.valid) return base

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

			const mobile = store.getState().user && store.getState().user.mobile
			const mobilePlain = mobile ? String(mobile).replace(/\*/g, '') : ''
			if (mobilePlain && this.form.password.trim() === mobilePlain) {
				return { valid: false, message: '密码不能与手机号相同' }
			}

			return { valid: true, message: '' }
		},
		async submit() {
			if (this.submitting || this.loading) 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)
				const payload = {
					encryptedPassword,
					encryptedConfirmPassword
				}

				if (!this.passwordSet) {
					payload.username = this.form.username.trim()
				} else {
					payload.encryptedOldPassword = await encryptPasswordWithFetch(this.form.oldPassword)
				}

				await setLoginPassword(payload)
				showToast(this.passwordSet ? '密码修改成功' : '密码设置成功')
				setTimeout(() => {
					uni.navigateBack()
				}, 800)
			} catch (e) {
				if (e && e.message && !e.code) {
					showToast(e.message)
				}
			} finally {
				this.submitting = false
			}
		}
	}
}
</script>

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

.set-password-scroll {
	height: 100vh;
}

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

.set-password-head {
	margin-bottom: 48rpx;
}

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

.set-password-head__desc {
	display: block;
	font-size: 28rpx;
	color: $fe-gray-500;
	line-height: 1.5;
}

.set-password-loading {
	padding: 80rpx 0;
	text-align: center;
}

.set-password-loading__text {
	font-size: 28rpx;
	color: $fe-gray-500;
}

.set-password-tip {
	margin-bottom: 32rpx;
	padding: 20rpx 24rpx;
	background: #F5F3FF;
	border-radius: $fe-radius-sm;
	font-size: 26rpx;
	color: $fe-primary;
}

.set-password-hint {
	display: block;
	margin-top: 12rpx;
	font-size: 24rpx;
	color: $fe-gray-500;
}

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

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

.set-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;
}

.set-password-btn--disabled {
	opacity: 0.5;
	pointer-events: none;
}
</style>
