<template>
	<view class="app-login-page">
		<view class="app-login">
			<view class="app-icon mb-30">
				<image src="https://sylwt.top/api/visitor/resources/image?name=/ydl/menber-center/login-icon.png"
					mode="aspectFit" style="height: 40px;"></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">我已阅读&#x300A;用户手册&#x300B;及隐私政策</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">
				<!-- v-if="canIUseGetUserProfile" -->
				<u-button  @click="getUserProfile" class="custom-button"
					style="width: 40px;" plain :hair-line="false">
					<image src="https://sylwt.top/api/visitor/resources/image?name=/ydl/menber-center/weixin.png"
						mode="aspectFit" style="width: 40px;height: 40px;" />
				</u-button>
				<!-- v-else -->
				<u-button  open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber" class="custom-button"
					style="width: 40px;" plain :hair-line="false">
					<image src="https://sylwt.top/api/visitor/resources/image?name=/ydl/menber-center/weixin.png"
						mode="aspectFit" style="width: 40px;height: 40px;" />
				</u-button>
				<u-button  @click="handleWxLogin()" class="custom-button"
					style="width: 40px;" plain :hair-line="false">
					<image src="https://sylwt.top/api/visitor/resources/image?name=/ydl/menber-center/weixin.png"
						mode="aspectFit" style="width: 40px;height: 40px;" />
				</u-button>
				<!-- <button type="default" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">获取手机号</button> -->
				<!-- <image src="https://sylwt.top/api/visitor/resources/image?name=/ydl/menber-center/weixin.png" mode="aspectFit" style="height: 40px;"></image> -->
			</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">&#x300A;用户手册&#x300B;及隐私政策</text>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		usernameLogin,
		getCaptchaImage,
		checknumberCaptcha,
		smsSend,
		loginPhone
	} from "@/api/user.js"
	import {
		msg,
		msgSuccess
	} from "@/utils/common.js"
	import {
		useAuthStore
	} from '@/store/authStore'
	import {
		encryptAESCBC
	} from "@/utils/crypto.js"
	export default {
		data() {
			return {
				getPhoneCapt: 0,
				canIUseGetUserProfile: false,
				loginCode: '',
				userBookModal: false,
				// ----验证码 start -----
				numberCaptchaForm: {
					numberCaptcha: '',
					numberCaptchaUuid: ''
				},
				numberCaptchaSrc: '',
				show: false,
				tips: '',
				seconds: 60,
				// ----验证码 end -----
				loginType: "phone",
				phoneForm: {
					phone: '18320082803',
					captcha: '',
					captchaUuid: ''
				},
				userNameForm: {
					username: "纪学卫",
					password: "123456"
				},
				userBook: false, //协议
			}
		},
		methods: {
			// 检查用户手册是否勾选
			checkUserBook() {
				if (!this.userBook) {
					this.userBookModal = true
					return false;
				}
				return true
			},
			// 用户手册模拟态确认勾选
			confirmModal() {
				this.userBook = true;
				const loginTypeHandler = {
					phone: this.phoneLoginHandle,
					username: this.userNameLoginHandle
				};
				// 调用相应的登录处理函数
				(loginTypeHandler[this.loginType] || (() => {})).call(this);
			},
			// 手机登录
			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;
				// console.log(this.phoneForm)
				uni.showLoading({
					title: '正在登录...'
				})
				loginPhone(this.phoneForm).then(res=>{
					// msg("登录成功");
					console.log(res);
				})
				// 联调
				// 1.登录 发送请求
				// 2.保存 token
				// 3.获取个人信息，保存个人新
				msg("登录成功");
				// setTimeout(() => {
				// 	this.useAuthStore.setAuthToken("test")
				// 	uni.setStorageSync("userinfo", {
				// 		userId: "2121",
				// 		isMember: true
				// 	})
				// 	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);
				usernameLogin(form).then(res => {
					// console.log(res, "登录")
					if (res.data.token) {
						msgSuccess("登录成功！")
						this.useAuthStore.setAuthToken(res.data.token)
						setTimeout(() => {
							uni.switchTab({
								url: "/pages/index/index"
							})
						}, 1000)
					}
				})
			},
			toPage(url) {
				uni.navigateTo({
					url: url
				})
			},
			// --------验证码 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 && codeResdata.captchaUuid){
					this.getPhoneCapt++;
					this.phoneForm.captchaUuid = codeRes.captchaUuid
					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() {
				try {
				    // 获取code
				    const loginRes = await uni.login({
				      provider: 'weixin'
				    });
				    const code = loginRes.code;
					console.log(11, loginRes);
				  } catch (error) {
				    console.error('微信登录失败:', error);
				  }
			},
			decryptPhoneNumber(e) {
				console.log(1111,e)
				if (e.detail.encryptedData) {
					const {
						encryptedData,
						iv,
						code
					} = e.detail;
					console.log(code)
					// 将 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() {
			const that = this;
			if (uni.getUserProfile) {
				console.log(1)
				that.canIUseGetUserProfile = true
			}
		}
	}
</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;
	}

	.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>