<template>
	<view class="container">
		<!-- #ifdef MP-WEIXIN -->
		<image class="bg" src="/static/image/bg_login.png" mode="widthFix"></image>
		<view class="force-login-wrap">
			<view :style="{height:menuButtonInfo.height,marginTop:menuButtonInfo.top}" class="backImg">
				<image @tap="goBack()" src="/static/images/back.png"></image>
			</view>
			<view class="top-title">
				<view class="title-text">欢迎登录<text class="blue">小蜜蜂</text></view>
				<view class="login-notice">新用户首次登录即视为注册</view>
			</view>
			<view class="force-login__content">
				<view class="logintype">
					<view :class="current==0 ? 'logintype-item active':'logintype-item'" @click="changeType(0)">验证码登录
					</view>
					<view class="line"></view>
					<view :class="current==1 ? 'logintype-item active':'logintype-item'" @click="changeType(1)">密码登录
					</view>
				</view>

				<view class="input-form">
					<view class="input-item">
						<input v-if="current == 0" class="input-field" type="number" v-model="phone" placeholder="请输入手机号" maxlength="11" />
						<input v-else  class="input-field"  v-model="account" placeholder="请输入账号"  />

					</view>
					<view class="input-item code-input-item">
						<input v-if="current == 0" class="input-field code-input" type="number" v-model="verifyCode"
							placeholder="请输入验证码" maxlength="6" />
						<view v-else class="mima">
							<input class="input-field code-input" type="text" :password="showPassword"
								v-model="password" placeholder="请输入密码" />
							<image @click="closePwd"
								:src="showPassword?'/static/image/icon_invisible.png':'/static/image/icon_visible.png'"
								mode="aspectFill"></image>
						</view>
						<view v-if="current == 0" class="get-code-btn" @click="getVerifyCode">
							{{ codeText }}
						</view>
					</view>
				</view>
				<view class="forgot" v-if="current==1" @click="toForgetPassword">忘记密码？</view>
				<view class="encoding">企业编码：-</view>
				<view class="login-btn-wrap">
					<!-- <button class="login-btn" @click="handleLogin">{{ current == 0 ? '登录/注册用户' : '登录' }}</button> -->
					<button class="login-btn" @click="handleLogin">登录</button>
				</view>

				<view class="tips">
					<checkbox :checked="isAgreement" @click="handleAgreement()" />
					<view class="tips-text" @click="handleAgreement()">已阅读并接受</view>
					<view class="btn" @click="openH5('/web/userAgreement')">《用户注册协议》</view>
					<view class="btn" @click="openH5('/web/privacyPolicy')">《隐私保护政策》</view>
				</view>
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		sendSmsCode,//发送短信验证码
		smsLogin, // 校验短信验证码
		login, // 密码登录
	} from '@/api/user'
	// import {
	// 	loginByMiniApp,
	// 	getUserInfo,
	// 	loginByMp
	// } from '@/api/user'
	export default {
		data() {
			return {
				account:null,
				code: null, // 微信登录code
				isAgreement: false,
				current: 0, // 0-验证码登录 1-密码登录
				menuButtonInfo: {},
				phone: '', // 手机号
				verifyCode: '', // 验证码
				password: '', // 密码
				codeText: '获取验证码', // 验证码按钮文字
				countdown: 0, // 倒计时
				countdownTimer: null, // 倒计时定时器
				showPassword: true // 是否显示密码
			}
		},
		computed: {},
		onLoad(option) {
			this.getMenuButtonInfo()
			// #ifdef MP-WEIXIN
			uni.$on('refreshLogin', () => {
				uni.navigateBack({
					delta: 1
				})
			})
			//选获取CODE，防止后请求的时候腾讯服务端未同步报错
			this.getCode();
			// #endif

			// #ifdef H5
			if (this.checkWeixin()) {
				this.getWxCode()
			} else {
				uni.showToast({
					icon: 'none',
					title: "请在微信中打开",
				});
				//跳转到手机号密码登录
			}
			// #endif

		},
		onUnload() {
			// 清除倒计时
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer);
				this.countdownTimer = null;
			}
		},
		mounted() {

		},
		methods: {
			closePwd() {
				this.showPassword = !this.showPassword
			},
			// 获取胶囊按钮布局参数
			getMenuButtonInfo() {
				// 微信小程序API（Uniapp可直接用uni.getMenuButtonBoundingClientRect）
				const menuBtn = uni.getMenuButtonBoundingClientRect();
				if (menuBtn) {

					this.menuButtonInfo = {
						top: menuBtn.top + 'px', // 胶囊顶部距离
						height: menuBtn.height + 'px', // 胶囊高度
						centerY: (menuBtn.top + menuBtn.height / 2) + 'px', // 胶囊垂直居中Y坐标
						right: menuBtn.right + 'px' // 胶囊右侧距离
					};
				}
			},
			changeType(index) {
				this.current = index;
				// 切换时清空输入
				if (index == 0) {
					this.password = '';
				} else {
					this.verifyCode = '';
				}
			},
			// 返回主页
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 获取验证码
		getVerifyCode() {
			if (this.countdown > 0) {
				return;
			}
			if (!this.phone) {
				uni.showToast({
					icon: 'none',
					title: "请输入手机号",
				});
				return;
			}
			if (!/^1[3-9]\d{9}$/.test(this.phone)) {
				uni.showToast({
					icon: 'none',
					title: "请输入正确的手机号",
				});
				return;
			}
			// 调用发送验证码API
				uni.showLoading({
					title: "发送中..."
				});
				let params = {
					phone: this.phone,
					type: '0',
				}
				sendSmsCode(params)
					.then(res => {
						uni.hideLoading();
						if (res.code == 200) {
							uni.showToast({
								icon: 'success',
								title: "验证码已发送",
							});
							// 开始倒计时
							this.countdown = 60;
							this.countdownTimer = setInterval(() => {
								this.countdown--;
								this.codeText = this.countdown + '秒重新获取';
								if (this.countdown <= 0) {
									clearInterval(this.countdownTimer);
									this.countdownTimer = null;
									this.codeText = '获取验证码';
								}
							}, 1000);
						} else {
							uni.showToast({
								icon: 'none',
								title: res.message || "发送验证码失败",
							});
						}
					})
					.catch(err => {
						uni.hideLoading();
					});
		},
			// 登录
		handleLogin() {
			if (!this.isAgreement) {
				uni.showToast({
					icon: 'none',
					title: "请先同意协议后再登录",
				});
				return;
			}

			if (this.current == 0) {
				// 验证码登录
				if (!this.phone) {
					uni.showToast({
						icon: 'none',
						title: "请输入手机号",
					});
					return;
				}
				if (!/^1[3-9]\d{9}$/.test(this.phone)) {
					uni.showToast({
						icon: 'none',
						title: "请输入正确的手机号",
					});
					return;
				}
				if (!this.verifyCode) {
					uni.showToast({
						icon: 'none',
						title: "请输入验证码",
					});
					return;
				}
				this.loginByCode();
			} else {
				// 密码登录
				if (!this.account) {
					uni.showToast({
						icon: 'none',
						title: "请输入账号",
					});
					return;
				}
				if (!this.password) {
					uni.showToast({
						icon: 'none',
						title: "请输入密码",
					});
					return;
				}
				this.loginByPassword();
			}
		},
			// 验证码登录
		loginByCode() {
			uni.showLoading({
				title: "登录中..."
			});
			// 调用验证码登录接口
			const data = {
				phone: this.phone,
				code: this.verifyCode
			};
			smsLogin(data)
				.then(res => {
					uni.hideLoading();
					if (res.code == 200) {
						uni.showToast({
							icon: 'success',
							title: "登录成功",
						});
						uni.setStorageSync('AppToken', res.data.token);
						uni.setStorageSync('userInfo', res.data.user);
						uni.$emit('refreshLogin');
						uni.navigateBack({
							delta: 1
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: res.message || "登录失败",
						});
					}
				})
				.catch(err => {
					uni.hideLoading();
					
				});
		},
			// 密码登录
			loginByPassword() {
				uni.showLoading({
					title: "登录中..."
				});
			const data={
				account: this.account,
				 password: this.password
			}
				// 调用密码登录接口
				login(data)
					.then(res => {
						uni.hideLoading();
						if (res.code == 200) {
							uni.showToast({
								icon: 'success',
								title: "登录成功",
							});
							uni.setStorageSync('AppToken', res.data.token);
							uni.setStorageSync('userInfo', res.data.user);
							uni.$emit('refreshLogin');
							uni.navigateBack({
								delta: 1
							});
						} else {
							uni.showToast({
								icon: 'none',
								title: res.message || "登录失败",
							});
						}
					})
					.catch(err => {
						console.log(err)
						uni.hideLoading();
						
					});
			},
			checkWeixin() {
				var ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/micromessenger/i) == 'micromessenger') {
					return true;
				} else {
					return false;
				}
			},
			//URL地址是否存在CODE
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
					[, ''
					])[1]
					.replace(/\+/g, '%20')) || null
			},
			//获取微信CODE
			getWxCode() {
				//在微信公众号请求用户网页授权之前，开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中，修改授权回调域名。请注意，这里填写的是域名（是一个字符串），而不是URL，因此请勿加 http:// 等协议头； 
				//http://shequ.natapp1.cc/#/pages/index/index?deviceId=8
				var appId = "wx40593595e62f61ad";
				var url = "http://h5.yjf.runtzh.com";
				window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId +
					'&redirect_uri=' + encodeURIComponent(url + "/#/pages/auth/wxLogin") +
					'&response_type=code&scope=snsapi_userinfo&state=JeffreySu-954&connect_redirect=1#wechat_redirect';
				//console.log('https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appId+'&redirect_uri=' +encodeURIComponent("http://shequ.natapp1.cc/#/pages/index/index?deviceId="+this.deviceId) +'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect')
				// redirect_uri是授权成功后，跳转的url地址，微信会帮我们跳转到该链接，并且通过？的形式拼接code
			},
			handleAgreement() {
				this.isAgreement = !this.isAgreement;
			},
			openH5(url) {
				var requestPath = uni.getStorageSync('requestPath');
				uni.setStorageSync('url', requestPath + url);
				uni.navigateTo({
					url: '../home/web'
				})
			},
			toForgetPassword(){
				uni.navigateTo({
					url: '/pages/auth/forgetPassword'
				})
			},
			getCode() {
				var that = this;
				this.utils.getProvider()
					.then(provider => {
						console.log('当前的环境商', provider)
						if (!provider) {
							reject()
						}
						// uni登录
						uni.login({
							provider: provider,
							success: async loginRes => {
								that.code = loginRes.code
							}
						})
					})
					.catch(err => {

					})
			},
			// 微信用户手机号登录
			phoneLogin(e) {
				var that = this;
				if (!this.isAgreement) {
					uni.showToast({
						icon: 'none',
						title: "请先同意协议后再登录",
					});
					return false;
				}
				uni.showLoading({
					title: "处理中..."
				})
				console.log(e, "e")
				if (e.mp.detail.errMsg == 'getPhoneNumber:ok') {
					this.utils.getProvider()
						.then(provider => {
							console.log('当前的环境商', provider)
							if (!provider) {
								reject()
							}
							// uni登录
							uni.login({
								provider: provider,
								success: async loginRes => {
									console.log(loginRes)
									let code = loginRes.code // 获取开发code
									var userCode = uni.getStorageSync('userCode');
									loginByMiniApp({
											encryptedData: e.mp.detail.encryptedData,
											iv: e.mp.detail.iv,
											code: code,
											userCode: userCode
										})
										.then(res => {
											if (res.code == 200) {
												uni.hideLoading();
												uni.showToast({
													icon: 'none',
													title: "登录成功",
												});
												uni.setStorageSync('AppToken', res.token);
												uni.setStorageSync('userInfo', res.user);
												uni.hideLoading()
												//that.getUserInfo()
												uni.$emit('refreshLogin');
												uni.navigateBack({
													delta: 1
												})
											} else {
												uni.hideLoading();
												uni.showToast({
													icon: 'none',
													title: "授权登录失败,请重新登录",
												});
											}

										})
										.catch(error => {
											console.log(error)
											uni.hideLoading();
										})

								}
							})
						})
						.catch(err => {
							uni.showToast({
								icon: 'none',
								title: err,
							});
						})

				} else {
					uni.showToast({
						title: '已拒绝授权',
						icon: 'none',
						duration: 2000,
					})
				}
			},
			back() {
				uni.switchTab({
					url: '/pages/home/index'
				});
				// uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
	.container {
		flex: 1;
		padding: 0 24rpx;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		position: relative;

		.bg {
			width: 100%;
			position: absolute;
			top: 0;
			left: 0;
		}

		.backImg {
			display: flex;
			align-items: center;

			image {
				width: 40rpx;
				height: 40rpx;
			}

			margin-left: 32rpx;
			// position: absolute;
			// left: 30rpx;
			// z-index: 100;
		}
	}

	.force-login-wrap {
		width: 100%;
		height: 100vh;
		position: relative;

		.top-title {
			padding: 0 32rpx;
			text-align: left;
			margin-top: 20rpx;

			.title-text {
				font-weight: 600;
				font-size: 48rpx;
				color: #333333;
				margin-bottom: 20rpx;

				.blue {
					color: #157CF8;
				}
			}

			.login-notice {
				font-weight: 400;
				font-size: 32rpx;
				color: #666666;
				line-height: 40rpx;
			}
		}

		.force-login__content {
			margin-top: 54rpx;
			padding: 0 32rpx;
			position: relative;

			.bg-type {
				width: 100%;
				position: absolute;
				top: 0;
				left: 0;
			}

			.logintype {
				display: flex;
				align-items: center;
				margin-bottom: 66rpx;
				border-bottom: 2rpx solid #f0f0f0;

				.line {
					margin: 0 32rpx;
					width: 2rpx;
					height: 32rpx;
					background: #D7E1F0;
					border-radius: 0rpx 0rpx 0rpx 0rpx;
				}

				.logintype-item {
					// flex: 1;
					text-align: center;
					padding-top: 36rpx;
					padding-bottom: 48rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 32rpx;
					color: #666666;
					position: relative;



					&.active {
						font-size: 36rpx;
						color: #333333;
						font-weight: 600;

						&::after {
							content: '';
							position: absolute;
							bottom: 30rpx;
							left: 50%;
							transform: translateX(-50%);
							width: 52rpx;
							height: 6rpx;
							background: #157CF8;
							border-radius: 42rpx;
						}
					}
				}
			}

			.input-form {
				margin-bottom: 60rpx;

				.input-item {
					background: #FFFFFF;
					border-radius: 16rpx;
					padding: 30rpx 40rpx;
					margin-bottom: 48rpx;
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

					&::last-child {
						margin-bottom: 0
					}

					.input-field {
						width: 100%;
						font-size: 30rpx;
						font-family: PingFang SC;
						color: #333333;

						&::placeholder {
							color: #CCCCCC;
						}
					}

					.mima {
						width: 100%;
						display: flex;
						align-items: center;
						justify-content: space-between;

						image {
							width: 32rpx;
							height: 32rpx;
						}
					}

					&.code-input-item {
						display: flex;
						align-items: center;

						.code-input {
							flex: 1;
						}

						.get-code-btn {
							font-size: 28rpx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #157CF8;
							padding-left: 20rpx;
							white-space: nowrap;
						}
					}
				}
			}

			.forgot {
				font-weight: 400;
				font-size: 24rpx;
				color: #388BFF;
				line-height: 40rpx;
				display: flex;
				justify-content: flex-end;
				margin: -40rpx 0 24rpx;
			}

			.encoding {
				width: 100%;
				height: 104rpx;
				line-height: 104rpx;
				text-align: center;
				background: #EDEFF2;
				border-radius: 16rpx 16rpx 16rpx 16rpx;
				font-size: 32rpx;
				color: #999999;
			}

			.login-btn-wrap {
				margin-bottom: 40rpx;
				margin-top: 140rpx;

				.login-btn {
					width: 100%;
					height: 88rpx;
					background: rgba(56, 139, 255, 1);
					border-radius: 44rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #FFFFFF;
					border: none;
					display: flex;
					align-items: center;
					justify-content: center;

					&::after {
						border: none;
					}
				}
			}
		}
	}

	.tips {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
		color: #666666;
		flex-wrap: nowrap;
		padding: 0 60rpx;

		checkbox {
			margin-right: 10rpx;
			flex-shrink: 0;
			transform: scale(0.8);
		}

		.tips-text {
			margin-right: 4rpx;
			white-space: nowrap;
		}

		.btn {
			color: #157CF8;
			margin: 0 2rpx;
			white-space: nowrap;
		}
	}


	.wx-login {
		background: rgba(0, 0, 0, 0.7);
		z-index: 99999;
		position: fixed;
		top: 0;
		left: 0;
		height: 100%;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;

		.form {
			border-radius: 20rpx;
			padding: 60rpx 30rpx;
			width: 500upx;
			height: 300upx;
			background-color: #fff;

			.title {
				font-size: 32upx;
				font-family: PingFang SC;
				font-weight: bold;

			}

			.desc {
				font-size: 28upx;
				margin: 60upx 0upx 60upx 0upx;
				font-family: PingFang SC;
				font-weight: 500;
			}

			.btn-box {
				margin-top: 30rpx;
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;

				.btn {
					display: flex;
					align-items: center;
					justify-content: center;
					margin-left: 10upx;
					width: 50%;
					height: 80rpx;
					border-radius: 5rpx;
					background-color: #0bb3f2;
					font-size: 30rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #fff;
					position: relative;
				}

				.btn-close {
					margin-right: 10upx;
					width: 50%;
					height: 80rpx;
					border-radius: 5rpx;
					border: 2rpx solid #0bb3f2;
					background: none;
					font-size: 30rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #0bb3f2;
				}
			}
		}
	}

	.auth_btn {
		width: 100%;
		height: 100%;
		top: 0upx;
		position: absolute;
		opacity: 0.0;
	}
</style>