<template>
	<view class="page">
		<view class="logo-area">
			<image class="logo" src="https://cdn.csybhelp.com/images/cytx/logo.png" mode="aspectFit" />
			<text class="title">肠愈同行</text>
			<text class="subtitle">患者关爱</text>
		</view>

		<view class="btn-area">
			<!-- #ifdef MP-WEIXIN -->
			<view v-if="mpLoginMode === 'wx'">
				<button class="login-btn" @tap="handleWxLogin" :loading="loading">
					微信一键登录
				</button>
			</view>
			<view v-else class="phone-form">
				<view class="form-item">
					<input class="form-input" type="number" v-model="phone" placeholder="请输入手机号" maxlength="11" />
				</view>
				<view class="form-item code-row">
					<input class="form-input code-input" type="number" v-model="smsCode" placeholder="请输入验证码" maxlength="6" />
					<button class="sms-btn" :disabled="countdown > 0" @tap="sendSms">
						{{ countdown > 0 ? countdown + 's' : '获取验证码' }}
					</button>
				</view>
				<button class="login-btn" @tap="handlePhoneLogin" :loading="loading">
					登录
				</button>
			</view>
			<button class="mode-switch-btn" @tap="toggleMpLoginMode">
				<u-icon
					:name="mpLoginMode === 'wx' ? 'phone-fill' : 'weixin-fill'"
					size="30"
					:color="mpLoginMode === 'wx' ? '#0F78E9' : '#07C160'"
				/>
			</button>
			<!-- #endif -->

			<!-- #ifdef H5 -->
			<!-- 二维码模式 -->
			<view v-if="h5Mode === 'qrcode'" class="qrcode-area">
				<text class="qrcode-tip">肠愈同行小程序已上线</text>
				<text class="qrcode-tip">请长按识别二维码进入小程序</text>
				<image class="qrcode-img" src="https://cdn.csybhelp.com/images/cytx/cytx_qrcode.jpg" mode="aspectFit" show-menu-by-longpress />
				<text class="switch-phone-btn" @tap="h5Mode = 'phone'">继续使用手机号登录</text>
			</view>
			<!-- 手机号模式 -->
			<view v-else class="phone-form">
				<text class="switch-qrcode-btn" @tap="h5Mode = 'qrcode'">← 使用小程序</text>
				<view class="form-item">
					<input class="form-input" type="number" v-model="phone" placeholder="请输入手机号" maxlength="11" />
				</view>
				<view class="form-item code-row">
					<input class="form-input code-input" type="number" v-model="smsCode" placeholder="请输入验证码" maxlength="6" />
					<button class="sms-btn" :disabled="countdown > 0" @tap="sendSms">
						{{ countdown > 0 ? countdown + 's' : '获取验证码' }}
					</button>
				</view>
				<button class="login-btn" @tap="handlePhoneLogin" :loading="loading">
					登录
				</button>
			</view>
			<!-- #endif -->

			<!-- #ifdef MP-WEIXIN -->
			<view class="agree-row">
				<u-checkbox-group v-model="agreementValues" @change="handleAgreementChange">
					<u-checkbox name="agree" shape="circle" activeColor="#0F78E9" size="18" />
				</u-checkbox-group>
				<text class="agree-text" @tap="toggleAgreement">请阅读并同意</text>
				<text class="link" @tap.stop="goService">《用户服务协议》</text>
				<text class="agree-text" @tap="toggleAgreement">和</text>
				<text class="link" @tap.stop="goPrivacy">《隐私政策》</text>
			</view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<view v-if="h5Mode === 'phone'" class="tip">登录即表示同意
				<text class="link" @tap="goPrivacy">《隐私政策》</text>
			</view>
			<!-- #endif -->
		</view>
	</view>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'
import { post } from '@/utils/request.js'
import { setToken, setUserInfo } from '@/utils/cache.js'

const loading = ref(false)
const phone = ref('')
const smsCode = ref('')
const countdown = ref(0)
const agreementValues = ref([])
const h5Mode = ref('qrcode')
const mpLoginMode = ref('wx')
let timer = null

onUnmounted(() => {
	if (timer) { clearInterval(timer); timer = null }
})

const loginSuccess = (res) => {
	setToken(res.data.token)
	setUserInfo(res.data.userInfo)
	uni.showToast({ title: '登录成功', icon: 'success' })
	setTimeout(() => {
		const pages = getCurrentPages()
		if (pages.length > 1) {
			uni.navigateBack()
		} else {
			uni.switchTab({ url: '/pages/profile/profile' })
		}
	}, 500)
}

const checkAgreement = () => {
	// #ifdef MP-WEIXIN
	if (!agreementValues.value.includes('agree')) {
		uni.showToast({ title: '请先阅读并同意相关协议', icon: 'none' })
		return false
	}
	// #endif
	return true
}

// #ifdef MP-WEIXIN
const toggleAgreement = () => {
	agreementValues.value = agreementValues.value.includes('agree') ? [] : ['agree']
}

const handleAgreementChange = (values) => {
	agreementValues.value = values || []
}

const toggleMpLoginMode = () => {
	mpLoginMode.value = mpLoginMode.value === 'wx' ? 'phone' : 'wx'
}

const handleWxLogin = async () => {
	if (loading.value) return
	if (!checkAgreement()) return
	loading.value = true
	try {
		const code = await new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: (res) => resolve(res.code),
				fail: () => reject({ msg: '微信登录失败' })
			})
		})
		const res = await post('/api/mp/login', { code })
		loginSuccess(res)
	} catch (e) {
		if (e && e.msg) uni.showToast({ title: e.msg, icon: 'none' })
	} finally {
		loading.value = false
	}
}
// #endif

const sendSms = async () => {
	if (countdown.value > 0) return
	if (!checkAgreement()) return
	if (!phone.value || phone.value.length !== 11) {
		return uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
	}
	try {
		const res = await post('/api/mp/sendSmsCode', { mobile: phone.value, bizType: 'login' })
		if (res.data && res.data.code) {
			uni.showToast({ title: `验证码: ${res.data.code}`, icon: 'none', duration: 3000 })
		} else {
			uni.showToast({ title: '验证码已发送', icon: 'none' })
		}
		countdown.value = 60
		timer = setInterval(() => {
			countdown.value--
			if (countdown.value <= 0) { clearInterval(timer); timer = null }
		}, 1000)
	} catch (e) {
		if (e && e.msg) uni.showToast({ title: e.msg, icon: 'none' })
	}
}

const handlePhoneLogin = async () => {
	if (loading.value) return
	if (!checkAgreement()) return
	if (!phone.value || phone.value.length !== 11) {
		return uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
	}
	if (!smsCode.value || smsCode.value.length !== 6) {
		return uni.showToast({ title: '请输入6位验证码', icon: 'none' })
	}
	loading.value = true
	try {
		const res = await post('/api/mp/phoneLogin', { mobile: phone.value, code: smsCode.value })
		loginSuccess(res)
	} catch (e) {
		if (e && e.msg) uni.showToast({ title: e.msg, icon: 'none' })
	} finally {
		loading.value = false
	}
}

const goPrivacy = () => {
	// #ifdef H5
	uni.navigateTo({ url: '/pages/content/content?key=privacy_policy_h5' })
	// #endif
	// #ifdef MP-WEIXIN
	uni.navigateTo({ url: '/pages/content/content?key=privacy_policy' })
	// #endif
}

const goService = () => {
	uni.navigateTo({ url: '/pages/content/content?key=service_policy' })
}
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
	background: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-top: 10vh;
}

.logo-area {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 80rpx;

	.logo {
		width: 180rpx;
		height: 180rpx;
		border-radius: 24rpx;
		margin-bottom: 32rpx;
	}

	.title {
		font-size: 44rpx;
		font-weight: 600;
		color: #303133;
		margin-bottom: 8rpx;
	}

	.subtitle {
		font-size: 26rpx;
		color: #b0b3b8;
		letter-spacing: 2rpx;
	}
}

.btn-area {
	width: 100%;
	padding: 0 64rpx;
	box-sizing: border-box;

	.login-btn {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		background: #0F78E9;
		color: #fff;
		font-size: 32rpx;
		border-radius: 44rpx;
		border: none;

		&::after {
			border: none;
		}

		&:active {
			opacity: 0.85;
		}
	}

	.tip {
		text-align: center;
		font-size: 24rpx;
		color: #909399;
		margin-top: 32rpx;

		.link {
			color: #0F78E9;
		}
	}

	.agree-row {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-wrap: wrap;
		margin-top: 32rpx;

		.agree-text {
			font-size: 24rpx;
			color: #909399;
			margin-left: 8rpx;
		}

		.link {
			font-size: 24rpx;
			color: #0F78E9;
		}
	}

	.mode-switch-btn {
		width: 96rpx;
		height: 96rpx;
		line-height: 1;
		border-radius: 50%;
		margin: 40rpx auto 0;
		padding: 0;
		background: #fff;
		border: 1rpx solid #e5e6eb;
		box-shadow: 0 8rpx 24rpx rgba(15, 120, 233, 0.12);
		display: flex;
		align-items: center;
		justify-content: center;

		&::after {
			border: none;
		}

		&:active {
			transform: scale(0.96);
			opacity: 0.9;
		}
	}
}

.phone-form {
	width: 100%;

	.form-item {
		margin-bottom: 24rpx;
	}

	.form-input {
		width: 100%;
		height: 88rpx;
		border: 1rpx solid #dcdfe6;
		border-radius: 44rpx;
		padding: 0 36rpx;
		font-size: 30rpx;
		box-sizing: border-box;
		background: #f8f9fa;
	}

	.code-row {
		display: flex;
		gap: 20rpx;

		.code-input {
			flex: 2;
		}
	}

	.sms-btn {
		flex: 1;
		height: 88rpx;
		line-height: 88rpx;
		padding: 0;
		background: #0F78E9;
		color: #fff;
		border: none;
		border-radius: 44rpx;
		font-size: 26rpx;
		white-space: nowrap;
		text-align: center;

		&::after {
			border: none;
		}

		&[disabled] {
			background: #a0cfff;
			color: #fff;
		}
	}

	.login-btn {
		margin-top: 16rpx;
	}
}

.qrcode-area {
	display: flex;
	flex-direction: column;
	align-items: center;

	.qrcode-tip {
		font-size: 28rpx;
		color: #606266;
		line-height: 1.6;
	}

	.qrcode-img {
		width: 400rpx;
		height: 400rpx;
		margin: 40rpx 0;
	}
}

.switch-phone-btn {
	font-size: 24rpx;
	color: #c0c4cc;
	text-align: center;
}

.switch-qrcode-btn {
	display: block;
	font-size: 28rpx;
	color: #0F78E9;
	margin-bottom: 32rpx;
	font-weight: 500;
}
</style>
