<template>
	<view class="app-login-page">
		<view class="app-login">
			<view class="app-icon mb-30">
				<image :src="`${FILE_URL}/login-icon.png`"
					mode="aspectFit" style="height: 80rpx;"></image>
			</view>
			<view class="app-title mb-30">
				欢迎使用会员服务中心
			</view>
			<view class="mb-30 login-form">
				<view class="loginType">
					<text :class="[loginType=='phone'? 'loginType-text-active': 'loginType-text']"
						@click="loginType = 'phone'">手机登录</text>
					<text :class="[loginType=='username'? 'loginType-text-active': 'loginType-text']"
						@click="loginType = 'username'">账号登录</text>
				</view>
				<view class="phone-form" v-if="loginType=='phone'">
					<view class="form-item">
						<u-input height="80" placeholder="请输入手机号" border-color="#d0d0d0" v-model="phoneForm.phone"
							:border="true" class="form-item-input" type="number" @confirm="phoneLoginHandle" />
					</view>
					<view class="form-item">
						<u-input height="80" placeholder="请输入验证码" border-color="#d0d0d0" v-model="phoneForm.captcha"
							:border="true" class="form-item-input" @confirm="phoneLoginHandle" />
						<text class="form-item-text" @click="getCode">{{tips}}</text>
						<!-- <text class="form-item-text" v-if="!isCounting" @click="requestVerificationCode">
							发送验证码</text>
						<text class="form-item-text" v-else>
							{{ `发送验证码(${countdown})` }}</text> -->
					</view>
					<view class="form-button" @click="phoneLoginHandle">
						立即登录
					</view>
				</view>
				<view class="phone-form" v-if="loginType=='username'">
					<view class="form-item">
						<u-input height="80" placeholder="请输入账号" border-color="#d0d0d0" v-model="userNameForm.username"
							:border="true" class="form-item-input" @confirm="userNameLoginHandle" />
					</view>
					<view class="form-item">
						<u-input height="80" placeholder="请输入密码" border-color="#d0d0d0" v-model="userNameForm.password"
							:border="true" class="form-item-input" @confirm="userNameLoginHandle" type="password"
							password-icon />
					</view>
					<view class="form-button" @click="userNameLoginHandle">
						立即登录
					</view>
				</view>
				<view class="risgiter-forget">
					<view @click="toPage('/pages/forget/forget')">忘记密码？</view>
					<view @click="toPage('/pages/register/register')">无账号？<text class="text-red">立即注册</text></view>
				</view>
			</view>
			<view class="app-user-book  mb-30">
				<u-checkbox-group style="display: flex;justify-content: center;">
					<u-checkbox v-model="userBook" name="yes" shape="circle" labelDisabled>
						我已阅读<text @click="toPrivacyAgree('user')">&#x300A;用户手册&#x300B;
						</text>及<text @click="toPrivacyAgree('privacy')">隐私政策</text>
					</u-checkbox>
				</u-checkbox-group>
			</view>
			<u-divider bg-color="transparent" margin-bottom="30" color="#010101" border-color="#010101"
				half-width="200">使用第三方账号登录</u-divider>
			<view class="app-icon mb-30">
				<!-- <u-button @click="handleWxLogin()" class="custom-button" style="width: 40px;" plain :hair-line="false">
					<image :src="`${FILE_URL}/weixin.png`"
						mode="aspectFit" style="width: 40px;height: 40px;" />
				</u-button> -->
				<u-button v-if="userBook" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber" class="custom-button" style="width: 40px;" plain :hair-line="false">
					<image :src="`${FILE_URL}/weixin.png`"
						mode="aspectFit" style="width: 40px;height: 40px;" />
				</u-button>
				<u-button v-else class="custom-button" style="width: 40px;" plain :hair-line="false" @click="checkBook">
					<image :src="`${FILE_URL}/weixin.png`"
						mode="aspectFit" style="width: 40px;height: 40px;" />
				</u-button>
			</view>
		</view>
		<u-verification-code :seconds="seconds" ref="uCode1" @change="codeChange"></u-verification-code>
		<u-popup v-model="show" mode="center" border-radius="10">
			<view class="popup">
				<text class="popup-title">请输入验证码</text>
				<view class="popup-content">
					<u-input height="80" placeholder="请输入验证码" border-color="#d0d0d0"
						v-model="numberCaptchaForm.numberCaptcha" :border="true" class="form-item-input"
						style="flex-grow: 1;" @confirm="submitCode" />
					<image :src="numberCaptchaSrc" mode="aspectFit"
						style="height:40px;margin-left:20rpx;width: 180rpx;flex: 0 0 auto;" @click="loadImage"></image>
				</view>
				<view class="popup-btn">
					<u-button type="primary" @click="submitCode" style="width: 48%;flex: 0 0 auto;">提交</u-button>
					<u-button type="default" @click="closePopup" style="width: 48%;flex: 0 0 auto;">取消</u-button>
				</view>
			</view>
		</u-popup>
		<u-modal v-model="userBookModal" mask-close-able class="modal" show-cancel-button
			:title-style="{fontWeight: 'bold'}" @confirm="confirmModal">
			<view class="modal-content">
				为了更好地保障你的合法权益，进行下一步前，请阅读并同意
				<text class="content-a" @click="toPrivacyAgree('user')">&#x300A;用户手册&#x300B;</text>
				及
				<text class="content-a" @click="toPrivacyAgree('privacy')">&#x300A;隐私政策&#x300B;</text>
			</view>
		</u-modal>
		<u-modal v-model="weixinUserBookModal" mask-close-able class="modal" show-cancel-button
			:title-style="{fontWeight: 'bold'}" @confirm="confirmModalWeixin">
			<view class="modal-content">
				为了更好地保障你的合法权益，进行下一步前，请阅读并同意
				<text class="content-a" @click="toPrivacyAgree('user')">&#x300A;用户手册&#x300B;</text>
				及
				<text class="content-a" @click="toPrivacyAgree('privacy')">&#x300A;隐私政策&#x300B;</text>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		usernameLogin,
		getCaptchaImage,
		checknumberCaptcha,
		smsSend,
		loginPhone,
		wxLoginOpenid, wxloginPhone
	} from "@/api/login.js"
	import {
		msg,
		msgSuccess
	} from "@/utils/common.js"
	import {
		useAuthStore
	} from '@/store/authStore'
	import {
		encryptAESCBC
	} from "@/utils/crypto.js"
	import {
		me
	} from '@/api/user.js'
	import configService from '@/utils/baseurl.js'
	export default {
		data() {
			return {
				FILE_URL: configService.FILE_URL,
				getPhoneCapt: 0,
				canIUseGetUserProfile: false,
				loginCode: '',
				userBookModal: false,
				weixinUserBookModal: false,
				// ----验证码 start -----
				numberCaptchaForm: {
					numberCaptcha: '',
					numberCaptchaUuid: ''
				},
				numberCaptchaSrc: '',
				show: false,
				tips: '',
				seconds: 60,
				// ----验证码 end -----
				loginType: "phone",
				phoneForm: {
					phone: '',
					captcha: '',
					captchaUuid: ''
				},
				userNameForm: {
					username: "",
					password: ""
				},
				userBook: false, //协议
				redirect: null
			}
		},
		methods: {
			toPrivacyAgree(mode){
				uni.navigateTo({
					url: "/pages/agreement/privacyAgree/privacyAgree?mode="+ mode
				})
			},
			// 检查用户手册是否勾选
			checkUserBook() {
				if (!this.userBook) {
					this.userBookModal = true
					return false;
				}
				return true
			},
			checkWeixinUserBook(){
				if (!this.userBook) {
					this.weixinUserBookModal = true
					return false;
				}
				return true
			},
			// 用户手册模拟态确认勾选
			confirmModal() {
				this.userBook = true;
				const loginTypeHandler = {
					phone: this.phoneLoginHandle,
					username: this.userNameLoginHandle
				};
				// 调用相应的登录处理函数
				(loginTypeHandler[this.loginType] || (() => {})).call(this);
			},
			confirmModalWeixin() {
				this.userBook = true;
			},
			// 手机登录
			async phoneLoginHandle() {
				const {
					phone,
					captcha
				} = this.phoneForm;

				// 手机号正则验证
				if (!/^1[3-9]\d{9}$/.test(phone)) {
					msg("请输入正确的手机号");
					return;
				}

				if (this.getPhoneCapt <= 0) {
					msg("请先获取手机验证码");
					return;
				}

				// 验证码存在性检查
				if (!captcha) {
					msg("请输入验证码");
					return;
				}

				let checkUserBook = await this.checkUserBook()
				if (!this.checkUserBook()) return;
				uni.showLoading({
					title: '正在登录...'
				})
				let res = await loginPhone(this.phoneForm)
				if (res.data.token) {
					msgSuccess("登录成功！")
					this.useAuthStore.setAuthToken(res.data.token, res.data.tokenExp)
					this.initUser()
					// const loginRes = await wx.login();
					// const code = loginRes.code;
					// wxLoginOpenid({code}).then(resp=>{
					// 	if(resp?.data){
					// 		const { openid, sessionKey } = resp.data
					// 		this.useAuthStore.setOpenid(openid)
					// 	}
					// 	setTimeout(() => {
					// 		if(this.redirect){
					// 			uni.reLaunch({
					// 				url: this.redirect.url+'?id='+this.redirect.id+'&title='+this.redirect.title
					// 			})
					// 		}else{
					// 			uni.switchTab({
					// 				url: "/pages/index/index"
					// 			})
					// 		}
					// 	}, 1000)
					// })
				}
			},
			// 账号登录
			async userNameLoginHandle() {
				if (!this.userNameForm.username) {
					msg("请输入账号")
					return;
				}
				if (!this.userNameForm.password) {
					msg("请输入密码")
					return;
				}
				let checkUserBook = await this.checkUserBook()
				if (!this.checkUserBook()) {
					return;
				};
				const form = {
					...this.userNameForm
				}
				form.password = encryptAESCBC(form.password);
				uni.showLoading({
					title: '正在登录...'
				})
				let res = await usernameLogin(form)
				if (res.data.token) {
					msgSuccess("登录成功！")
					this.useAuthStore.setAuthToken(res.data.token, res.data.tokenExp)
					this.initUser()
				}
			},
			toPage(url) {
				uni.navigateTo({
					url: url
				})
			},
			async initUser(){
				const loginRes = await wx.login();
				const code = loginRes.code;
				let userRes = await me();
				let wxRes = await wxLoginOpenid({code})
				// 加载用户信息
				if(userRes && userRes?.code===0){
					this.useAuthStore.setUserInfo(userRes.data)
				}
				// 加载openid
				if(wxRes && wxRes?.data){
					const { openid, sessionKey } = wxRes.data
					this.useAuthStore.setOpenid(openid)
				}
				setTimeout(() => {
					if(this.redirect){
						uni.removeStorageSync("redirect")
						uni.reLaunch({
							url: this.redirect.url+'?id='+this.redirect.id+'&title='+this.redirect.title
						})
					}else{
						uni.switchTab({
							url: "/pages/index/index"
						})
					}
				}, 1000)
			},
			// --------验证码 start---------
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				let {
					phone
				} = this.phoneForm
				if (!/^1[3-9]\d{9}$/.test(phone)) {
					msg("请输入正确的手机号");
					return;
				}
				if (this.$refs.uCode1.canGetCode) {
					this.showPopup()
				} else {
					msg('倒计时结束后再发送');
				}
			},
			end() {
				msg('倒计时结束');
			},
			start() {
				msg('倒计时开始');
			},
			// 数字校验码
			showPopup() {
				// 模拟向后端请求验证码
				// 1.获取数字校验码图片
				// 2.显示弹窗
				this.loadImage()
				this.show = true;
			},
			closePopup() {
				this.show = false;
				this.numberCaptchaForm.numberCaptcha = ''; // 清空输入框
			},
			async submitCode() {
				if (this.numberCaptchaForm.numberCaptcha.length !== 4) {
					uni.showToast({
						title: '请输入4位验证码',
						icon: 'none'
					});
					return;
				}
				// 联调 检验是否正确
				uni.showLoading({
					title: '正在校验验证码'
				})

				const checkRes = await checknumberCaptcha(this.numberCaptchaForm);
				if (!checkRes.data.valid) {
					uni.showToast({
						title: '验证码输入错误',
						icon: 'none'
					});
					return;
				}
				// // 发送手机验证码
				const codeRes = await smsSend({
					phone: this.phoneForm.phone
				});

				if (codeRes && codeRes.data.captchaUuid) {
					this.getPhoneCapt++;
					this.phoneForm.captchaUuid = codeRes.data.captchaUuid
					// console.log(this.phoneForm)
					this.closePopup();
					this.$refs.uCode1.start()
				}

				uni.hideLoading();
			},
			// 加载验证码图片
			async loadImage() {
				// 联调
				uni.showLoading({
					title: '正在获取图片'
				})
				const img = await getCaptchaImage();
				if (!img.data.numberCaptchaSrc) {
					return
				}
				this.numberCaptchaForm.numberCaptchaUuid = img.data.numberCaptchaUuid
				this.numberCaptchaSrc = img.data.numberCaptchaSrc;
				uni.hideLoading();
			},

			// --------验证码 end---------
			async handleWxLogin() {
				const loginRes = await wx.login();
				const code = loginRes.code;
				wxLoginOpenid({code}).then(res=>{
					if(res?.data){
						const { openid, sessionKey } = res.data
					}
				})
			},
			async checkBook(){
				let checkUserBook = await this.checkWeixinUserBook()
				if (!this.checkWeixinUserBook()) {
					return;
				};
			},
			async decryptPhoneNumber(e){
				if (e.detail.encryptedData) {
					const {
						encryptedData,
						iv,
						code
					} = e.detail;
					const loginRes = await wx.login();
					const wxcode = loginRes.code;
					try{
						const openidRes = await wxLoginOpenid({code : wxcode})
						if(openidRes?.data){
							const { openid, sessionKey,tokenExp } = openidRes.data
							this.useAuthStore.setOpenid(openid)
							const phoneRes = await wxloginPhone({ openid, phoneCode: code})
							const { phone, token, isNewUser } = phoneRes.data;
							this.useAuthStore.setPhone(phone);
							this.useAuthStore.setAuthToken(token, tokenExp);
							// uni.reLaunch({
							// 	url: "/pages/register/register?mode=refine"
							// })
							if(isNewUser){
								//新用户，跳转：完善用户信息
								// console.log("完善用户信息")
								uni.reLaunch({
									url: "/pages/register/register?mode=refine"
								})
							}else{
								// 老用户，跳转至：首页
								msgSuccess("授权成功！")
								uni.showLoading({
									title: '正在登录...'
								})
								let userRes = await me()
								if(userRes && userRes?.code===0){
									this.useAuthStore.setUserInfo(userRes.data)
								}
								msgSuccess("登录成功！")
								setTimeout(()=>{
									if(this.redirect){
										uni.reLaunch({
											url: this.redirect.url+'?id='+this.redirect.id+'&title='+this.redirect.title
										})
									}else{
										uni.switchTab({
											url: "/pages/index/index"
										})
									}
								}, 1000)
							}
						}
					}catch(err){
						console.log("ee", err)
					}

					// 将 encryptedData 和 iv 发送到后端进行解密
				} else {
					msg('取消授权手机号');
				}
			},
			getUserProfile() {
				// this.toPage("/pages/wxLogin/wxLogin")
				// 用户微信登录
				let that = this;
				// 推荐使用uni.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
				// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
				uni.getUserProfile({
					desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (resp) => {
						//登录远程服务器
						console.log(2222, resp)
						// if (that.loginCode) {
						// 	//登录远程服务器
						// 	console.log("登录远程服务器")
						// 	// that.loginByWeixin(resp)
						// } else {
						// 	uni.login({
						// 		success: function(resp) {
						// 			if (resp.code) {
						// 				that.code = resp.code
						// 				console.log(resp)
						// 				// that.loginByWeixin(resp)
						// 			}
						// 		}
						// 	});
						// }
					}
				})
			}
		},
		// 在组件销毁时清理定时器
		beforeDestroy() {
			// 在组件销毁时清理定时器
		},
		computed: {
			useAuthStore() {
				return useAuthStore(); // 获取 store 实例
			}
		},
		onLoad(option) {
			const that = this;
			if (uni.getUserProfile) {
				// console.log(1)
				that.canIUseGetUserProfile = true
			}
			// if(option.redirect){
			// 	const decodedRedirect = decodeURIComponent(option.redirect);
			// 	uni.setStorageSync("redirect", JSON.parse(decodedRedirect))
			// }
			if(uni.getStorageSync("redirect")){
				this.redirect = uni.getStorageSync("redirect")
			}
		}
	}
</script>
<style lang="scss">
	.form-item .u-input--border {
		border-radius: 16rpx !important;
	}

	.custom-button {
		.u-btn {
			display: block !important;
			width: fit-content;
			padding: 0 !important;
			border-radius: 50rpx;
		}

		.u-btn--default {
			border: none !important;
			background-color: transparent !important;
		}
	}
</style>
<style lang="scss" scoped>
	.app-login-page {
		background-color: #f7f7f7;
		width: 100vw;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.app-login {
		width: 90%;
	}

	.app-icon {
		// text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 90rpx;
		text-align: center;
	}

	.app-title {
		text-align: center;
		font-size: 44rpx;
		letter-spacing: 2px;
		font-weight: 700;
	}

	.mb-30 {
		margin-bottom: 30rpx;
	}

	.text-red {
		color: #df0505;
	}

	.login-form {
		background-color: #ffffff;
		width: 100%;
		padding: 50rpx 40rpx;
		border-radius: 15rpx;
		box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
		border: 1px solid #036df6;
	}

	.loginType {
		color: #000000;
		margin-bottom: 15rpx;

		.loginType-text {
			font-size: 30rpx;
			margin-right: 30rpx;
		}

		.loginType-text-active {
			font-size: 40rpx;
			margin-right: 30rpx;
		}
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 60rpx;

		.form-item-input {
			width: 100%;
			background-color: #f7f7f7 !important;
		}

		.form-item-text {
			width: 200rpx;
			flex: 0 0 auto;
			text-align: center;
			color: #000000;
			// margin: 0 20px;
		}
	}

	.form-button {
		background: linear-gradient(90deg, #006af5, #21b0fc);
		border-radius: 20rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		margin-bottom: 50rpx;
	}

	.risgiter-forget {
		font-size: 30rpx;
		display: flex;
		justify-content: space-between;
	}

	// 数字验证码
	.popup {
		padding: 40rpx;
		border-radius: 20rpx;

		.popup-title {
			font-size: 18px;
			text-align: center;
			display: inline-block;
			width: 100%;
			// margin-bottom: 15px;
		}

		.popup-content {
			display: flex;
			align-items: center;
			margin: 50rpx 0;
		}

		.popup-btn {
			display: flex;
			justify-content: space-between;
		}
	}

	// 用户手册模拟态
	.modal {
		.modal-content {
			padding: 50rpx;

			.content-a {
				color: #2979ff;
			}
		}
	}
</style>
