<template>
	<view class="fe-page fe-page--white login-page">
		<scroll-view scroll-y class="login-scroll" :show-scrollbar="false">
			<view class="login-inner">
				<view class="login-card-header">
					<text class="login-card-header__title">{{ loginTab === 'enterprise' ? '企业登录' : '临时工登录' }}</text>
					<text
						v-if="!lockRole"
						class="login-card-header__switch"
						@tap="switchLoginTab(loginTab === 'enterprise' ? 'worker' : 'enterprise')"
					>{{ loginTab === 'enterprise' ? '切换到临时工登录' : '切换到企业登录' }}</text>
				</view>

				<view class="fe-login-visual">
					<text class="fe-login-visual__title">智能用工，轻松管理</text>
					<text class="fe-login-visual__desc">AI驱动的企业灵活用工一站式解决方案</text>
					<view class="fe-login-feature">
						<text class="fe-login-feature__check">✓</text>
						<text>对话式操作，无需复杂表单</text>
					</view>
					<view class="fe-login-feature">
						<text class="fe-login-feature__check">✓</text>
						<text>智能草稿生成，一键确认</text>
					</view>
					<view class="fe-login-feature">
						<text class="fe-login-feature__check">✓</text>
						<text>成本透明对比，精打细算</text>
					</view>
					<view class="fe-login-feature">
						<text class="fe-login-feature__check">✓</text>
						<text>全流程合规，安全可追溯</text>
					</view>
				</view>

				<view class="fe-login-card">
					<!-- 手机号 / 验证码登录 -->
					<view v-if="loginView === 'phone'">
						<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 v-if="authMode === 'sms'" 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 login-sms-btn"
										:class="{ 'login-btn--disabled': smsCountdown > 0 || smsSending }"
										@tap="sendSmsCode"
									>{{ smsBtnText }}</view>
								</view>
							</view>
							<view v-else>
								<view class="fe-form-group">
									<text class="fe-form-label">登录密码</text>
									<view class="login-password-field">
										<input
											class="fe-form-input login-password-field__input"
											v-model="form.password"
											:password="!showLoginPassword"
											maxlength="64"
											placeholder="请输入登录密码"
										/>
										<view class="login-password-field__eye" @tap="showLoginPassword = !showLoginPassword">
											<uni-icons
												:type="showLoginPassword ? '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="fe-form-row login-captcha-row">
										<input
											class="fe-form-input"
											v-model="form.captcha"
											maxlength="4"
											placeholder="请输入图形验证码"
										/>
										<jp-verification-literalness
											ref="literalness"
											:content-width="100"
											:content-height="42"
											background-color="#F5F3FF"
											:color-list="captchaColorList"
											:line-color-list="captchaLineColorList"
											:is-case-check="false"
										/>
									</view>
								</view>
							</view>
						</view>

						<view class="login-agreement">
							<view class="login-agreement__row">
								<view class="login-agreement__checkbox" @tap.stop="toggleAgreed">
									<checkbox :checked="agreed" color="#7C3AED" />
								</view>
								<text class="login-agreement__text" @tap="toggleAgreed">
									已阅读并同意
									<text class="login-agreement__link" @tap.stop="showServiceAgreement">《服务协议》</text>
									<text class="login-agreement__link" @tap.stop="showPrivacyPolicy">《隐私政策》</text>
									<text class="login-agreement__link" @tap.stop="showAccountNotice">《账号服务须知》</text>
									，未注册手机号将自动创建账号
								</text>
							</view>
						</view>

						<view
							class="login-auth-switch"
							:class="{ 'login-auth-switch--end': authMode === 'sms' }"
						>
							<text
								v-if="authMode === 'password'"
								class="login-forgot-link"
								@tap="goResetPassword"
							>忘记密码</text>
							<text
								class="login-auth-switch__link"
								@tap="switchAuthMode(authMode === 'sms' ? 'password' : 'sms')"
							>{{ authMode === 'sms' ? '切换到账号密码登录' : '切换到验证码登录' }}</text>
						</view>

						<view
							class="fe-btn fe-btn--primary fe-btn--lg fe-btn--full login-submit-btn"
							:class="{ 'login-btn--disabled': !agreed || loggingIn }"
							@tap="submitLogin"
						>
							{{ loginBtnText }}
						</view>

						<view class="fe-login-divider">其他登录</view>
						<view class="login-other-icon">
							<image
								class="login-other-icon__img"
								src="/packageA/static/images/wechat.png"
								mode="aspectFit"
								@tap="switchLoginView('wechat')"
							/>
						</view>
					</view>

					<!-- 微信快捷登录 -->
					<view v-else class="login-wechat-panel">
						<view class="login-agreement login-agreement--wechat">
							<view class="login-agreement__row">
								<view class="login-agreement__checkbox" @tap.stop="toggleAgreed">
									<checkbox :checked="agreed" color="#7C3AED" />
								</view>
								<text class="login-agreement__text" @tap="toggleAgreed">
									已阅读并同意
									<text class="login-agreement__link" @tap.stop="showServiceAgreement">《服务协议》</text>
									<text class="login-agreement__link" @tap.stop="showPrivacyPolicy">《隐私政策》</text>
									<text class="login-agreement__link" @tap.stop="showAccountNotice">《账号服务须知》</text>
									，未注册手机号将自动创建账号
								</text>
							</view>
						</view>

						<view
							class="fe-btn fe-btn--wechat fe-btn--lg fe-btn--full login-wechat-submit"
							:class="{ 'login-btn--disabled': !agreed }"
							@tap="submitWechatLogin"
						>
							微信一键登录
						</view>

						<view class="fe-login-divider">其他登录</view>
						<view class="login-other-icon">
							<image
								class="login-other-icon__img login-other-icon__img--sms"
								src="/packageA/static/images/sms.png"
								mode="aspectFit"
								@tap="switchLoginView('phone')"
							/>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

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

const SMS_COUNTDOWN_SECONDS = 60

export default {
	data() {
		return {
			loginTab: 'enterprise',
			lockRole: '',
			redirectUrl: '',
			authMode: 'sms',
			loginView: 'phone',
			agreed: false,
			form: {
				mobile: '',
				code: '',
				password: '',
				captcha: ''
			},
			captchaColorList: ['#7C3AED', '#6366F1', '#4F46E5', '#8B5CF6'],
			captchaLineColorList: ['rgba(124, 58, 237, 0.35)', 'rgba(99, 102, 241, 0.35)', 'rgba(79, 70, 229, 0.35)'],
			smsCountdown: 0,
			smsSending: false,
			smsTimer: null,
			loggingIn: false,
			showLoginPassword: false
		}
	},
	computed: {
		smsBtnText() {
			if (this.smsSending) return '发送中...'
			if (this.smsCountdown > 0) return `${this.smsCountdown}s后重新获取`
			return '获取验证码'
		},
		loginBtnText() {
			if (this.loggingIn) return '登录中...'
			return '登录'
		}
	},
	onLoad(options) {
		const opts = options || {}
		const role = opts.role === 'worker' || opts.role === 'enterprise' ? opts.role : ''
		this.lockRole = role
		if (role) this.loginTab = role
		if (opts.redirect) {
			try {
				this.redirectUrl = decodeURIComponent(opts.redirect)
			} catch (e) {
				this.redirectUrl = opts.redirect
			}
		}
	},
	onShow() {
		if (!(store.getState().loggedIn && getToken())) return
		this.continueAfterAuthed()
	},
	onUnload() {
		this.clearSmsTimer()
	},
	methods: {
		toast: showToast,
		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.loginTab
				})
				showToast(res && res.mockEnabled ? '验证码已发送（测试环境：123456）' : '验证码已发送')
				this.startSmsCountdown(SMS_COUNTDOWN_SECONDS)
			} catch (e) {
				// 错误提示由 request.js 统一处理
			} finally {
				this.smsSending = false
			}
		},
		switchLoginTab(type) {
			if (this.lockRole) return
			this.loginTab = type
		},
		switchLoginView(view) {
			this.loginView = view
		},
		switchAuthMode(mode) {
			this.authMode = mode
			this.form.captcha = ''
			if (mode === 'password') {
				fetchPasswordPublicKey({ showError: false }).catch(() => {})
				this.$nextTick(() => this.refreshCaptcha())
			}
		},
		refreshCaptcha() {
			const literalness = this.$refs.literalness
			if (literalness && typeof literalness.refresh === 'function') {
				literalness.refresh()
			}
		},
		goResetPassword() {
			uni.navigateTo({
				url: `/packageA/auth/reset-password?userType=${this.loginTab}`
			})
		},
		toggleAgreed() {
			this.agreed = !this.agreed
		},
		appendRedirectQuery(url) {
			if (!this.redirectUrl) return url
			const join = url.indexOf('?') >= 0 ? '&' : '?'
			return `${url}${join}redirect=${encodeURIComponent(this.redirectUrl)}`
		},
		continueAfterAuthed() {
			const state = store.getState()
			const role = state.role === 'worker' ? 'worker' : 'enterprise'

			if (this.lockRole === 'worker' && role !== 'worker') {
				store.logout()
				showToast('请使用临时工账号登录')
				return
			}

			if (this.redirectUrl) {
				if (role === 'worker' && !store.isWorkerRegistered()) {
					uni.reLaunch({
						url: this.appendRedirectQuery('/packageA/worker/register')
					})
					return
				}
				uni.reLaunch({ url: this.redirectUrl })
				return
			}

			uni.reLaunch({
				url: store.getLoginEntryUrl(role)
			})
		},
		ensureAgreed() {
			if (!this.agreed) {
				showToast('请先阅读并同意相关协议')
				return false
			}
			return true
		},
		showServiceAgreement() {
			showToast('服务协议弹框待接入')
		},
		showPrivacyPolicy() {
			showToast('隐私政策弹框待接入')
		},
		showAccountNotice() {
			showToast('账号服务须知弹框待接入')
		},
		redirectAfterLogin(role, needRegister) {
			if (this.redirectUrl) {
				// 仅临时工未登记时强制去登记；企业可先逛后认证
				if (needRegister && role === 'worker') {
					uni.reLaunch({ url: this.appendRedirectQuery('/packageA/worker/register') })
					return
				}
				uni.reLaunch({ url: this.redirectUrl })
				return
			}
			uni.reLaunch({
				url: store.getLoginEntryUrl(role, needRegister)
			})
		},
		resolveLoginRole(info, loginRes, fallbackTab) {
			if (info && info.userType) {
				return info.userType === 'worker' ? 'worker' : 'enterprise'
			}
			if (loginRes && loginRes.userType) {
				return loginRes.userType === 'worker' ? 'worker' : 'enterprise'
			}
			return fallbackTab === 'worker' ? 'worker' : 'enterprise'
		},
		async finishLoginAndRedirect(loginRes, mobile) {
			const role = this.lockRole || (loginRes && loginRes.userType) || this.loginTab
			const hasNewUserFlag = !!(loginRes && typeof loginRes.newUser === 'boolean')
			const fallbackNeedRegister = hasNewUserFlag ? !!loginRes.newUser : true

			const loginOptions = {
				userId: loginRes && loginRes.userId,
				mobileMask: loginRes && loginRes.mobileMask,
				nickname: loginRes && loginRes.nickname,
				mobile
			}
			if (hasNewUserFlag) {
				loginOptions.newUser = loginRes.newUser
			}
			store.login(role, loginOptions)

			let info = null
			try {
				info = await store.syncProfile({ showError: false })
			} catch (e) {
				// syncProfile 失败时按未登记处理
			}

			const finalRole = this.lockRole || this.resolveLoginRole(info, loginRes, this.loginTab)
			// 企业不强制登记；临时工仍按 registered 跳转登记页
			const needRegister = finalRole === 'enterprise'
				? false
				: (info ? !info.registered : fallbackNeedRegister)

			showToast('登录成功')
			this.redirectAfterLogin(finalRole, needRegister)
		},
		async submitLogin() {
			if (!this.ensureAgreed()) return
			if (this.loggingIn) return

			if (this.authMode === 'password') {
				await this.submitPasswordLogin()
				return
			}

			const { valid, message } = validateForm(this.form, {
				mobile: { label: '手机号', rules: ['mobile'] },
				code: { label: '验证码', rules: ['smsCode'] }
			})
			if (!valid) {
				showToast(message)
				return
			}

			this.loggingIn = true
			try {
				const res = await loginBySms({
					mobile: this.form.mobile.trim(),
					code: this.form.code.trim(),
					userType: this.loginTab
				})
				await this.finishLoginAndRedirect(res, this.form.mobile.trim())
			} catch (e) {
				// 错误提示由 request.js 统一处理
			} finally {
				this.loggingIn = false
			}
		},
		async submitPasswordLogin() {
			const { valid, message } = validateForm(this.form, {
				mobile: { label: '手机号', rules: ['mobile'] },
				password: { label: '登录密码', rules: ['password'] }
			})
			if (!valid) {
				showToast(message)
				return
			}

			const captcha = (this.form.captcha || '').trim()
			if (!captcha) {
				showToast('请输入图形验证码')
				return
			}

			const literalness = this.$refs.literalness
			if (!literalness || !literalness.verification(captcha)) {
				showToast('图形验证码错误')
				this.form.captcha = ''
				this.refreshCaptcha()
				return
			}

			await this.doPasswordLogin()
		},
		async doPasswordLogin() {
			if (this.loggingIn) return

			this.loggingIn = true
			try {
				const encryptedPassword = await encryptPasswordWithFetch(this.form.password)
				const res = await loginByPassword({
					account: this.form.mobile.trim(),
					encryptedPassword
				})
				await this.finishLoginAndRedirect(res, this.form.mobile.trim())
			} catch (e) {
				if (e && e.message && !e.code) {
					showToast(e.message)
				}
			} finally {
				this.loggingIn = false
			}
		},
		submitWechatLogin() {
			if (!this.ensureAgreed()) return
			if (this.loginTab === 'worker') {
				this.loginWorker()
			} else {
				this.loginEnterprise()
			}
		},
		loginEnterprise() {
			store.login('enterprise')
			this.redirectAfterLogin('enterprise', false)
		},
		loginWorker() {
			store.login('worker')
			this.redirectAfterLogin('worker', !store.isWorkerRegistered())
		}
	}
}
</script>

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

.login-scroll {
	height: 100vh;
}

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

.login-card-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 40rpx;
}

.login-card-header__title {
	font-size: 28rpx;
	font-weight: 500;
	color: $fe-gray-500;
}

.login-card-header__switch {
	font-size: 40rpx;
	color: $fe-primary;
	font-weight: 700;
	background: #F5F3FF;
	border-radius: $fe-radius-sm;
	padding: 8rpx 20rpx;
}

.login-auth-switch {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 24rpx;

	&--end {
		justify-content: flex-end;
	}
}

.login-forgot-link {
	font-size: 26rpx;
	color: $fe-info;
	font-weight: 500;
}

.login-auth-switch__link {
	font-size: 28rpx;
	color: $fe-info;
	font-weight: 500;
}

.login-agreement {
	margin-top: 8rpx;
	margin-bottom: 16rpx;
}

.login-agreement--wechat {
	margin-top: 0;
	margin-bottom: 48rpx;
}

.login-agreement__row {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.login-agreement__checkbox {
	flex-shrink: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	transform: scale(0.72);
	transform-origin: center center;
}

.login-agreement__text {
	flex: 1;
	font-size: 24rpx;
	line-height: 1.6;
	color: $fe-gray-500;
}

.login-agreement__link {
	color: $fe-primary;
	font-weight: 600;
}

.login-submit-btn {
	margin-top: 0;
}

.login-wechat-panel {
	padding-top: 8rpx;
}

.login-wechat-submit {
	margin-top: 0;
}

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

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

.login-captcha-row {
	align-items: center;
}

.login-captcha-row .fe-form-input {
	flex: 1;
	min-width: 0;
}

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

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

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

.login-other-icon {
	display: flex;
	justify-content: center;
	margin-top: 8rpx;
}

.login-other-icon__img {
	width: 96rpx;
	height: 96rpx;
}

.login-other-icon__img--sms {
	width: 88rpx;
	height: 88rpx;
}

.login-note {
	display: block;
	text-align: center;
	margin-top: 32rpx;
	font-size: 26rpx;
	color: $fe-gray-500;
}
</style>
