<!-- 登录 -->
<template>
	<view class="logo-pages" :style="{height:height + 'px'}">
		<view :style="{'height':statusBarHeight}"></view>
		<image src="https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/login/arrows.png" mode="" class="nav-bar-img" @click="goBack"></image>
		<view class="login-txt">登录</view>
		<view class="login-main">
			<view class="login-type">
				<view class="type-label">请输入手机号</view>
				<view class="type-txt" @click="changeLoginType">用{{type === 'password' ? '验证码' : '密码'}}登录</view>
			</view>
			<input type="text" placeholder="请输入手机号" class="phone-input" v-model="phone">
			<view class="login-status">请输入{{type === 'password' ? '密码' : '验证码'}}</view>
			<view class="code-input">
				<input type="password" placeholder="请输入8~12位字母数字组合密码" class="phone-input" v-if="type === 'password'"
					v-model="password">
				<input type="text" placeholder="请输入验证码" class="phone-input" v-if="type === 'code'" v-model="code">
				<view class="get-code" @click="getCode" v-if="type === 'code'">
					{{ countTime === 0 ? '获取验证码' : countTime + 's' }}</view>
			</view>
			<view class="agreement" @click="agreementClick">
				<image src="https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/login/select.png" mode="" class="agreement-select" v-if="agreementVisible"></image>
				<image src="https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/login/select-no.png" mode="" class="agreement-select" v-if="!agreementVisible">
				</image>
				我已同意<text class="agreement-txt" @click="goPage('agreement')">《用户协议》</text>和<text class="agreement-txt" @click="goPage('privacy')">《隐私政策》</text>
			</view>
			<view class="login-btn"
				:class="{'active':phone && ((type==='password'&&password) || (type==='code'&&code)) && agreementVisible}"
				@click="loginSubmit">登录</view>
			<view class="forget" @click="forget">
				如忘记密码，可<text class="forget-txt">点此找回</text>
			</view>
			<view class="register" @click="register">注册账号</view>
		</view>
		<view class="wx-login" @click="checkWeChatCode" v-if="isWeixin && footer">
			<image src="https://box-mall.oss-cn-hangzhou.aliyuncs.com/static/login/wx.png" mode="" class="wx-img"></image>
			<text class="wx-txt">微信登录</text>
		</view>
	</view>
</template>

<script>
	import { baseUrl } from '@/config/baseConfig.js'
	import {
		smsSend,
		smsCheck,
		loginApi,
		loginCode,
		loginWechat,
		wechatAppid,
		phoneWechat
	} from '@/API/login.js'
	var statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px'
	export default {
		data() {
			return {
				height:0,
				statusBarHeight,
				agreementVisible: true, //用户协议
				type: 'password', //登录类型：password code
				countTime: 0,
				phone: "15160201159",
				password: "111111",
				code: "",
				typeBack: "",
				isWeixin: false,//是否是微信浏览器
				footer: true,
				windowHeight: ''
			}
		},
		onShow(){
			console.log("baseUrl(weChatCode):",baseUrl('weChatCode'))
		},
		onLoad(opation) {
			// this.height = uni.getSystemInfoSync().windowHeight
			uni.getSystemInfo({
				success: (res)=> {
					this.windowHeight = res.windowHeight;
				}
			});    
			uni.onWindowResize((res) => {
				if(res.size.windowHeight < this.windowHeight){
					this.footer= false
				}else{
					this.footer = true
				}
			})
			
			
			console.log(this.height)
			uni.removeStorageSync('info')
			uni.removeStorageSync('userInfo')
			this.isWeixin = this.isWechat()
			console.log("this.getUrlCode('code'):",this.getUrlCode('code'))
			if(this.isWeixin && this.getUrlCode('code')){
				uni.showLoading()
				loginWechat({type:'jsapi',code:this.getUrlCode('code')}).then(res => {
					uni.hideLoading()
					console.log("res:",res)
					// this.$api.msg(res.message)
					if(res.code === 200){
						uni.setStorageSync('info', JSON.stringify(res.data))
						uni.switchTab({
							url:`/pages/home/index`
						})
					}else if(res.code === 400){
						this.$api.msg(res.message)
					}else if(res.code === 10001){
						uni.reLaunch({
							url:`/pages/login/bindPhone?data=${encodeURIComponent(JSON.stringify(res.data))}`
						})
					}
				}).carch(err => {
					uni.hideLoading()
				})
				// this.checkWeChatCode()//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
			}
			try {
				this.typeBack = opation.type
			} catch (e) {
				//TODO handle the exception
			}
		},
		methods: {
			showFooter(){
				this.footer= true;
			},
			hideFooter(){
				this.footer= false;
			},
			goBack(){
				uni.switchTab({
					url:`/pages/home/index`
				})
			},
			goPage(type){
				let path = ''
				if(type === 'agreement'){
					path = '/pages/agreement/index'
				}else{
					path = '/pages/agreement/privacy'
				}
				uni.navigateTo({
					url:path
				})
			},
			//方法：用来判断是否是微信内置的浏览器
			isWechat() {
					return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			//方法:用来提取code
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
					[, ''
					])[1]
					.replace(/\+/g, '%20')) || null
			},
			//检查浏览器地址栏中微信接口返回的code
			checkWeChatCode() {
				uni.showLoading()
				wechatAppid({type:'jsapi'}).then(res => {
					console.log(res)
					uni.hideLoading()
					console.log(`${baseUrl('weChatCode')}/get-weixin-code.html?appid=${res.data.appid}&redirect_uri=${res.data.redirectUrl}&state=1`)
					location.href =`${baseUrl('weChatCode')}/get-weixin-code.html?appid=${res.data.appid}&redirect_uri=${res.data.redirectUrl}&state=1`
					// location.href =
					// 	`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${res.data.appid}&response_type=code&scope=snsapi_base&redirect_uri=${res.data.redirectUrl}&state=1#wechat_redirect`;
					// location.href = `./login.html`
					// location.href = `https://app.box.mall.06zk.com/get-weixin-code.html?appid=${res.data.appid}&redirect_uri=${res.data.redirectUrl}`
				}).catch(err => {
					uni.hideLoading()
				})
			},
			// 切换登录方式
			changeLoginType() {
				this.code = "";
				this.password = "";
				if (this.type === 'password') {
					this.type = 'code'
				} else {
					this.type = 'password'
				}
			},
			// 是否同意用户协议
			agreementClick() {
				this.agreementVisible = !this.agreementVisible;
			},
			// 获取验证码
			getCode() {
				if (this.countTime > 0) {
					return;
				}
				if (!(/^1[2|3|4|5|6|7|8|9]\d{9}$/.test(this.phone))) {
					this.$api.msg('请输入正确的手机号');
					return;
				}
				smsSend({
					phone: this.phone
				}).then(res => {
					if (res.code === 200) {
						this.$api.msg('获取成功');
						this.countTime = 60;
						var id = setInterval(() => {
							this.countTime--;
							if (this.countTime === 0) {
								clearInterval(id);
							}
						}, 1000);
					} else {
						this.$api.msg(res.message);
					}
					console.log(res)
				}).catch(err => {
					this.$api.msg(err)
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 登录
			loginSubmit() {
				if(!this.phone){
					this.$api.msg('请输入手机号');
					return;
				}
				if (!(/^1[2|3|4|5|6|7|8|9]\d{9}$/.test(this.phone))) {
					this.$api.msg('请输入正确的手机号');
					return;
				}
				if (this.type === 'password' && !this.password) {
					this.$api.msg('请输入密码');
					return;
				}
				if (this.type === 'code' && !this.code) {
					this.$api.msg('请输入验证码');
					return;
				}
				if (!this.agreementVisible) {
					this.$api.msg('请阅读用户协议、隐私政策');
					return;
				}
				// 密码登录
				if (this.type === 'password') {
					uni.showLoading({
						title: "登录中"
					})
					loginApi({
						username: this.phone,
						password: this.password
					}).then(res => {
						console.log(res)
						if (res.code === 200) {
							uni.setStorageSync('info', JSON.stringify(res.data))
							uni.switchTab({
								url: `/pages/index/index`
							})
							if (this.typeBack === 'back') {
								uni.navigateBack()
							} else {
								uni.switchTab({
									url: `/pages/index/index`
								})
							}
						} else {
							this.$api.msg(res.message)
						}
					}).finally(() => {
						uni.hideLoading()
					})
				} else {
					uni.showLoading({
						title: "登录中"
					})
					loginCode({
						phone: this.phone,
						code: this.code
					}).then(res => {
						console.log(res)
						if (res.code === 200) {
							uni.setStorageSync('info', JSON.stringify(res.data))
							console.log(this.typeBack)
							uni.switchTab({
								url: `/pages/index/index`
							})
							// if (this.typeBack) {
							// 	uni.navigateBack()
							// } else {
							// 	uni.switchTab({
							// 		url: `/pages/home/index`
							// 	})
							// }
						} else {
							this.$api.msg(res.message)
						}
					}).finally(() => {
						uni.hideLoading()
					})
				}
			},
			// 注册
			register() {
				uni.navigateTo({
					url: `/pages/login/registerAndForget?type=register`
				})
			},
			// 忘记密码
			forget() {
				uni.navigateTo({
					url: `/pages/login/registerAndForget?type=forget`
				})
			},

			// 登陆
			// login() {
			// 	console.log("222")

			// 	uni.setStorageSync("auto_wx_login", "true");
			// 	location.href = './login.html'
			// 	uni.getProvider({
			// 		service: 'oauth',
			// 		success: function(res) {
			// 			console.log(res)
			// 			//支持微信、qq和微博等
			// 			if (~res.provider.indexOf('weixin')) {
			// 				uni.login({
			// 					provider: 'weixin',
			// 					success: function(loginRes) {
			// 						console.log("loginRes:", loginRes)
			// 						// 获取用户信息
			// 						uni.getUserInfo({
			// 							provider: 'weixin',
			// 							success: function(infoRes) {
			// 								console.log("infoRes:", infoRes)
			// 								let data = Object.assign(loginRes
			// 									.authResult, infoRes);
			// 							},
			// 							fail: function(err) {
			// 								uni.hideLoading();
			// 								uni.showToast({
			// 									icon: 'none',
			// 									title: err
			// 								})
			// 							}
			// 						});

			// 					}
			// 				})
			// 			}
			// 		},
			// 		fail: function(err) {
			// 			uni.hideLoading();
			// 			uni.showToast({
			// 				icon: 'none',
			// 				title: err
			// 			})
			// 		}
			// 	})
			// 	// uni.getProvider({
			// 	// 	service: 'oauth',
			// 	// 	success: function(res) {
			// 	// 		//支持微信、qq和微博等
			// 	// 		 if (~res.provider.indexOf('weixin')) {

			// 	// 		 }
			// 	// 	}
			// 	// })
			// 	// uni.switchTab({
			// 	// 	url:"/pages/index/index"
			// 	// })
			// },
		}
	}
</script>

<style lang="scss">
	.logo-pages {
		.nav-bar-img {
			margin-top: 56rpx;
			width: 24rpx;
			height: 40rpx;
			margin-left: 32rpx;
		}

		.login-txt {
			margin-top: 40rpx;
			width: 100%;
			text-align: center;
			font-size: 48rpx;
			color: #333333;
			font-weight: bold;
		}

		.login-main {
			padding: 0 40rpx;
			margin-top: 60rpx;

			.login-type {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.type-label {
					font-size: 28rpx;
					color: #AFB3C4;
				}

				.type-txt {
					font-size: 28rpx;
					color: #2FDBCB;
				}
			}

			.phone-input {
				color: #666666;
				font-size: 28rpx;
				width: 100%;
				padding-left: 40rpx;
				height: 90rpx;
				border: 2rpx solid #2FDBCB;
				border-radius: 46rpx;
				margin-top: 16rpx;
				padding-right: 140rpx;
			}

			.code-input {
				position: relative;

				.get-code {
					position: absolute;
					right: 20rpx;
					top: 30rpx;
					font-size: 24rpx;
					color: #3DC9C0;
				}
			}

			.login-status {
				font-size: 28rpx;
				color: #AFB3C4;
				margin-top: 20rpx;
			}

			.agreement {
				width: 100%;
				display: flex;
				align-items: center;
				margin-top: 32rpx;
				font-size: 28rpx;
				color: #858587;

				.agreement-select {
					width: 24rpx;
					height: 24rpx;
					margin-right: 32rpx;
				}

				.agreement-txt {
					color: #2FDBCB;
				}
			}

			.login-btn {
				width: 380rpx;
				height: 92rpx;
				background: #BAF2F1;
				border-radius: 46rpx;
				margin: 40rpx auto 36rpx auto;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 36rpx;
				color: #677D83;
				font-weight: 800;
			}

			.active {
				background-color: #3DC9C0;
				color: #333;
			}

			.forget {
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				color: #666666;

				.forget-txt {
					color: #2FDBCB;
				}
			}

			.register {
				margin-top: 12rpx;
				text-align: center;
				color: #2FDBCB;
				font-weight: 800;
				font-size: 24rpx;
			}
		}

		.wx-login {
			width: 100%;
			position: absolute;
			bottom: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;

			.wx-img {
				width: 100rpx;
				height: 100rpx;
			}

			.wx-txt {
				font-size: 28rpx;
				color: #333;
				margin-top: 20rpx;
			}
		}
	}
</style>
