<template>
	<view class="loginbox">
		<view class="logintop">
			<image :src="`${imgPath}static/userui/wxloginbj.png`" style="width: 100%; height: 240px;" />
		</view>
		<view class="loginbotton padding flex flex-direction">

			<button v-if="isAgreed.length==0 " class="cu-btn lg bg-green text-white" @click="isAgreedChoose">
				<text class="cuIcon-weixin lg" style="font-size: 20px;"></text>
				<span style="margin-left: 10px; font-size: 15px;">微信一键登录</span>
			</button>
			<button v-else-if="phone != null && phone !=''" class="cu-btn lg bg-green text-white" @click="wxlogin">
				<text class="cuIcon-weixin lg" style="font-size: 20px;"></text>
				<span style="margin-left: 10px; font-size: 15px;">微信一键登录</span>
			</button>
			<button v-else class="cu-btn lg bg-green text-white" open-type="getPhoneNumber"
				@getphonenumber="getPhoneNumber">
				<text class="cuIcon-weixin lg" style="font-size: 20px;"></text>
				<span style="margin-left: 10px; font-size: 15px;">微信一键登录</span>
			</button>
			<view class="agreement">
				<checkbox-group class="checkbox-group">
					<label class="agreement-text flex align-center">
						<uni-data-checkbox style="width: 20px;" v-model="isAgreed" multiple :localdata="agreed" />
						<span style="color: rgb(173,173,175);">我已经阅读并同意
							<text class="terms-link" @click="openTerms">《法律条款和隐私政策》</text>
						</span>
					</label>
				</checkbox-group>
			</view>
		</view>
		<!-- 手机号登录/注册跳转区域 -->
		<view class="phone-login">
			<view class="phone-login-text"><span class="phone-login-span">———————</span> 手机号登录/注册 <span
					class="phone-login-span">———————</span></view>
			<view class="phone-login-button">
				<view class="iconborder flex justify-center align-center" @click="redirectToPhoneLogin">
					<image :src="`${imgPath}static/userui/icon/phone.png`" alt="" />
				</view>
			</view>
		</view>
	</view>
	<zero-loading v-if="isloading" color="#c1c1c0" type="wobble" mask="true"></zero-loading>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import * as api from '@/utils/api.js';
	import config from '@/utils/config';
	import {
		showModelMessage
	} from '@/utils/tools.js';
	const imgPath = config.imgPath;
	const isAgreed = ref([]); // 用来控制复选框的选中状态
	const isloading = ref(false);
	const phone = ref("");
	const openId = ref("");
	const agreed = ref([{
		value: true // true 表示选中
	}]);
	import {
		onLoad
	} from '@dcloudio/uni-app';
	const openTerms = () => {
		// 跳转到服务条款页面
		uni.navigateTo({
			url: '/pages/user/login/terms'
		});
	};
	onMounted(() => {

	})
	onLoad((options) => {
		login();
	})

	const login = () => {
		isloading.value = true;
		wx.login({
			success: (res) => {
				if (res.code) {
					api.callOrdereApi("ebikeUser/login?js_code=" + res.code, {}, "get").then(
						(wx) => {
							if (wx.code == 200) {
								openId.value = wx.data;
								api.callOrdereApi("ebikeUser/getInfoByOpenId?openId=" + wx.data, {},
										"get")
									.then((info) => {
										isloading.value = false;
										if (info.code == 200) {
											uni.setStorageSync('wechat_user', info.data);
											phone.value = info.data.mobile;
											if (!info.data.nickname) {
												updateUserProfile();
											}
										} else {
											let params = {
												"openId": wx.data,
												"status": 1,
											}
											api.callOrdereApi("ebikeUser/save", params).then(
												re => {
													if (re.code == 200) { 
														params.userId = re.data;
														uni.setStorageSync('wechat_user',
															params);
														updateUserProfile();
													}
												});
										}
									})
							} else {

								isloading.value = false;
							}
						}

					);

				} else {
					console.log('微信登录失败:', res.errMsg);
					isloading.value = false;
				}
			},
			fail: (err) => {
				console.log('wx.login 调用失败:', err);
				isloading.value = false;
			},

		});
	}

	// 获取头像和昵称并更新
	const updateUserProfile = () => {
		wx.getUserInfo({
			success: function(res) {
				console.log(res.userInfo.nickName); // 昵称
				console.log(res.userInfo.avatarUrl); // 头像URL
				let wechat_user = uni.getStorageSync('wechat_user');
				const params = {
					"userId": wechat_user.userId,
					"nickname": res.userInfo.nickName,
					"avatar": res.userInfo.avatarUrl
				};
				api.callOrdereApi("ebikeUser/update", params);
			}
		});
	}
	const isAgreedChoose = () => {
		// 检查是否同意条款
		if (isAgreed.value.length == 0) {
			// 弹出提示框，告知用户需要同意条款
			uni.showModal({
				title: '提示',
				content: '请同意并阅读《法律条款和隐私政策》',
				success: (res) => {
					if (res.confirm) {
						// 用户确认同意
						isAgreed.value = [true]; // 更新同意状态   
					}
				}
			});
		}
	}

	const getPhoneNumber = (e) => {
		if (e.detail.errMsg === 'getPhoneNumber:ok') {
			// 获取到手机号的加密数据  
			wx.login({
				success: (res) => {
					let wechat_user = uni.getStorageSync('wechat_user'); 
					const encryptedData = e.detail.encryptedData;
					const iv = e.detail.iv;
					const param = {
						"jsCode": res.code,
						"encryptedData": encryptedData,
						"iv": iv
					}
					api.callOrdereApi("ebikeUser/getEncryptInfo", param).then(info => {
						if (info.code == 200) {
							//更新手机号
							const params = {
								"userId": wechat_user.userId,
								"mobile": info.data
							}
							phone.value = info.data;
							api.callOrdereApi("ebikeUser/update", params);
							wxlogin();
						}
					});
				},
				fail: (err) => {
					console.log('wx.login 调用失败:', err);
				},

			});
		} else {
			console.log('用户拒绝授权');
			return;
		}
	}

	// 判断账号是否已经注销
	const isAccountDeactivated = () => {
		let wechat_user = uni.getStorageSync('wechat_user');
		if (wechat_user && wechat_user.status == -1) {
			return false;
		}
		return true;
	}


	const wxlogin = () => {
		if (!isAccountDeactivated()) {
			showModelMessage("您的账户已经注销,请联系管理员！");
		} else {
			// 调用 wx.login 获取登录凭证 code
			login();
			setTimeout(() => {
				uni.switchTab({
					url: "/pages/user/home/home"
				})
			}, 500);
		}


	};



	const gotoPhonelogin = () => {
		uni.navigateTo({
			url: '/pages/user/login/phone_login'
		})
	}
</script>

<style scoped>
	.loginbox {
		background-color: #fff;
	}

	.logintop {
		height: 240px;
	}

	.loginbotton {
		margin-top: 40px;
	}

	.agreement {
		margin-top: 20px;
		text-align: center;
	}

	.checkbox-group {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.agreement-text {
		font-size: 14px;
		color: #666;
	}

	.agreement-text .terms-link {
		color: rgb(227, 153, 98);
		cursor: pointer;
		text-decoration: underline;
	}

	/* 调整checkbox外观 */
	.checkbox {
		margin-right: 8px;
	}


	/* 优化手机号登录/注册部分 */
	.phone-login {
		margin-top: 220px;
		text-align: center;
	}

	.phone-login-text {
		font-size: 12px;
		color: #dddddd;
		margin-bottom: 10px;
	}

	.phone-login-span {
		color: #e1e1e1;
	}

	.phone-login-button {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.iconborder {
		width: 34px;
		height: 34px;
		border: solid 2px #c5c5c5;
		border-radius: 17px;
	}

	.iconborder image {
		width: 20px;
		height: 20px;
	}
</style>