<template>
	<view class="page">
		<!-- logo -->
		<view class="logo-wrap" v-if="pageStatus == 'home' || pageStatus == 'getWxRole'">
			<image mode="aspectFit" class="logo" src="https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/logo.png"></image>
			<!-- <u-image width="300" height="300" src="../../static/img/logo.png" mode="aspectFit"></u-image> -->
			<!-- <view class="app-name">书嗨</view> -->
		</view>
		<!-- <view class="" v-for="(item,index) in loglist" :key="index">
			{{item}}
		</view> -->
		<!-- 默认登录页面显示 -->
		<view style="width: 100%;" v-if="pageStatus == 'home'">
			<view class="text-area" @click="loginByWxFun">一键登录</view>
		</view>

		<!-- 微信授权登录，获取用户信息 -->
		<view style="width: 100%;" v-if="pageStatus == 'getWxRole'">
			<view class="info">为提供优质服务,需要获取你的以下信息 :</view>
			<view class="public">
				<view class="public-dot"></view>
				<view class="public-text">你的公开信息(头像、昵称等)</view>
			</view>
			<view class="text-enter" @click="getWxLoginRole">授权进入</view>
		</view>

		<!-- 微信登录小程序，再授权获取用户信息之后 -->
		<view class="loginWx" v-if="is_new_user">
			<view class="title">欢迎使用书嗨</view>
			<view class="desc">立即登录享受优质服务</view>
			<view class="avatar"><image mode="aspectFill" :src="wxLoginUserInfo.userInfo.avatarUrl"></image></view>
			<!--  v-if="is_new_user" -->
			<u-button type="success" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">手机号快捷登录</u-button>
			<!-- <u-button type="success" v-else @click.stop="handleLogin">一键登录</u-button> -->
		</view>

	

		<!-- 协议勾选 -->
		<view class="agree" v-if="pageStatus == 'home' || pageStatus == 'getWxRole'">
			<view class="agree_img" @click="changeAgreeFlag" v-show="!agree_flag"><image src="../../static/icon/check.png"></image></view>
			<view class="agree_img" @click="changeAgreeFlag" v-show="agree_flag"><image src="../../static/icon/checked.png"></image></view>
			<view class="agree_text">
				登录代表您已同意
				<span @click="goArticleDetail('agreement','用户协议')">《用户服务协议》</span><span @click="goArticleDetail('privacy_policy','隐私政策')">《隐私权政策》</span>
			</view>
		</view>
	</view>
</template>

<script>
import FunUniappTheme from '@/theme.scss';
import {articleOpar} from '@/pages-pub/mixins/article.js'
var _self;
export default {
	mixins:[articleOpar],
	data() {
		return {
			loglist:[],
			// 页面状态，默认为 home
			// getWxRole：获取微信权限页，loginByWx：微信授权登录页
			pageStatus: 'home',
			is_new_user:false,
			// 协议是否勾选
			agree_flag: false,
			// 微信授权的用户信息
			wxLoginUserInfo: {},
			// openid
			openId: '',
			// jscode:换取openid需要用到的code
			jscode:'',
			// 系统内用户信息
			userInfo: {},
		};
	},
	onLoad() {
		_self = this;
	},

	methods: {
		subScribeMsg(callBack) {
			uni.getSetting({
				withSubscriptions: true,
				success(res) {
					console.log('1', res, '订阅信息', res.subscriptionsSetting);
					if (!res.subscriptionsSetting.mainSwitch) {
						uni.openSetting({ //打开设置页
							success(res) {
								console.log('打开设置页', res.authSetting);
							}
						})
					} else {
						uni.requestSubscribeMessage({
							tmplIds: ['Sfa68XDGAUQveX50PcP_Ep6ngNz3luvXJNwzASjzzvQ',
								'_VxaYVnVTj3aG_wengF8KNFDI3WRhOrFseBerx8xvXE',
							],
							success(res) {
								console.log('requestSubscribeMessage 订阅信息', res);
								if (res['Sfa68XDGAUQveX50PcP_Ep6ngNz3luvXJNwzASjzzvQ'] == "accept") { // 用户点击确定后
									console.log('用户订阅点击确定按钮');
									// _self.getSubMsg()
								} else {
									console.log('拒绝');
								}
							},
							fail(errMessage) {
								console.log("订阅消息 失败 ", errMessage);
							},
							// 不管成功或失败都要执行
							complete() {
								// if (_self.ordercode == null) return _self.getOrder();
								// if (_self.ordercode != null) return _self.getPayOrder();
								// uni.navigateTo({
								// 	url: '/pages-mall/pages/order/detail?order_id='+_self.orderId
								// });
								callBack();
							}
						})
					}
				},
			})
		},
			
		// 勾选/取消用于协议
		changeAgreeFlag() {
			this.agree_flag = !this.agree_flag;
		},

		// 微信登录
		loginByWxFun() {
			if (!this.agree_flag) {
				uni.showToast({
					icon: 'none',
					title: '请先阅读并勾选协议'
				});
				return;
			}
			this.pageStatus = 'getWxRole';
		},

		// 自定义navbar的返回方法
		navbarBack() {
			this.pageStatus = 'home';
		},

		// 基于uni的获取code方法
		getWxCode(callBack) {
			_self.loglist.push('uni.login');
			uni.login({
				provider: 'weixin',
				onlyAuthorize: true,
				success: loginRes => {
					_self.loglist.push('116,loginRes::'+JSON.stringify(loginRes));
					this.jscode = loginRes.code;
					// return;
					callBack(loginRes.code);
				},
				fail(e) {
					_self.loglist.push('122::'+JSON.stringify(e));
				}
			});
		},
		// 微信授权 微信用户信息
		getWxLoginRole() {
			if (!this.agree_flag) {
				uni.showToast({
					icon: 'none',
					title: '请先阅读并勾选协议'
				});
				return;
			}
			// _self.subScribeMsg(()=>{
				
			
			// this.getUserInfoByWx(() => {
				this.getWxCode(code => {
					uni.showLoading({
						title: '登录中'
					});
					_self.loglist.push('140::登录中');
					this.$u.api.loginAjax({
						js_code:code
					}).then(res => {
						_self.loglist.push('144登录>>>>>'+JSON.stringify(res));
						uni.hideLoading();
						if(res.code==1){
							if(res.data.is_new_user==1){
								// 新用户注册
								_self.is_new_user = true;
								_self.pageStatus = 'loginByWx';
								return;
							}
							// 正常登录
							uni.showToast({
								icon: 'none',
								title: '登录成功~'
							});
							
							this.$store.commit("user/commitUserInfo",res.data);
							this.$store.commit("user/commitToken",res.data.token);
							uni.setStorage({
								key: 'token',
								data: res.data.token,
								success() {
									uni.$emit('getUserInfo');
									uni.navigateBack();
								},
							})
							
						}
						
					}).catch((error)=>{
						_self.loglist.push('164登录>>>>>'+JSON.stringify(error));
					});
					
				});
			// });
			// })
		},


		// 获取个人信息
		getUserInfoByWx(callBack) {
			let _self = this;
			console.log('>>>>>>:getUserInfoByWx');
			_self.$u.toast('>>>>>>:getUserInfoByWx');
			uni.getUserProfile({
				desc: '获取你的昵称、头像',
				success: function(data) {
					console.log(data);
					uni.setStorageSync({
						key: 'APP_WX_USERINFO',
						data: data
					});
					_self.wxLoginUserInfo = data;
					_self.pageStatus = 'loginByWx';
					callBack();
				},
				fail: function(error) {}
			});
		},

		// 获取手机号回调
		decryptPhoneNumber(e) {
			_self.loglist.push('197::>>'+JSON.stringify(e.detail));
			// 获取到code，调用接口去注册
			this.getWxCode(code => {
				_self.loglist.push('200::>>'+JSON.stringify({
					js_code:code,
					avatar:"",
					nickname:"微信用户",//this.wxLoginUserInfo.userInfo.nickName
					code:e.detail.code
				}));
				this.$u.api.loginAjax({
					js_code:code,
					avatar:"",
					nickname:"微信用户",
					code:e.detail.code
				}).then(res => {
					console.log(res);
					_self.loglist.push('207:::'+JSON.stringify(res))
					if(res.code==1){
						this.$store.commit("user/commitUserInfo",res.data);
						this.$store.commit("user/commitToken",res.data.token);
						uni.$emit('getUserInfo');
						uni.navigateBack();
					}
				}).catch((error)=>{
					_self.loglist.push('215:::'+JSON.stringify(error))
				});
			});
		},


	}
};
</script>

<style lang="scss" scoped>
.page {
	padding: 0 40rpx;
	background-color: $app-theme-bg-color;
}

.logo-wrap {
	display: flex;
	justify-content: center;
	padding-top: 100rpx;
	padding-bottom: 240rpx;
	flex-wrap: wrap;
	.logo {
		width: 300rpx;
		height: 300rpx;
	}
	.app-name {
		width: 100%;
		padding-top: 40rpx;
		text-align: center;
		font-size: 44rpx;
		font-weight: 500;
		color: $app-theme-text-black-color;
	}
}

.text-area {
	width: 100%;
	height: 96rpx;
	background: $app-theme-color;
	font-weight: 400;
	border-radius: 56rpx;
	color: $app-theme-text-white-color;
	line-height: 16px;
	font-size: 32rpx;
	text-align: center;
	line-height: 96rpx;
	/* background: url(../../static/img/logo_newhope.png); */
}

.info {
	font-size: 28rpx;
	font-weight: 400;
	color: $app-theme-text-black-color;
	line-height: 28rpx;
	margin-top: 180rpx;
}

.public {
	display: flex;
	align-items: center;
	margin-top: 30rpx;

	.public-dot {
		width: 6rpx;
		height: 6rpx;
		background: #999999;
		margin-right: 10rpx;
	}

	.public-text {
		font-size: 24rpx;
		font-weight: 400;
		color: #8f92a1;
		line-height: 24rpx;
	}
}

.text-enter {
	width: 100%;
	margin-top: 50rpx;
	height: 96rpx;
	background: $app-theme-color;
	font-weight: 400;
	border-radius: 56rpx;
	color: #ffffff;
	line-height: 16px;
	font-size: 32rpx;
	text-align: center;
	line-height: 96rpx;
}

.head {
	margin-top: 70rpx;
	width: 100%;
	display: flex;
	justify-content: space-between;
}

.back {
	width: 40rpx;
	height: 40rpx;
}

.login {
	text-align: center;
	font-size: 32rpx;
	font-weight: 400;
	color: $app-theme-color;
	line-height: 32rpx;
	margin-top: 48rpx;
}

.agree {
	position: fixed;
	left: 50%;
	transform: translate(-50%, 0);
	bottom: 66rpx;
	width: 100vw;
	display: flex;
	align-items: center;
	justify-content: center;
}

.agree_img image {
	width: 32rpx;
	height: 32rpx;
	display: flex;
	align-items: center;
}

.agree_text {
	margin-left: 8rpx;
	font-size: 24rpx;
	font-weight: 400;
	color: #8f92a1;
	line-height: 24rpx;
	display: flex;
	align-items: center;

	span {
		color: $app-theme-color;
	}
}

.loginWx {
	width: 100%;
	padding-top: 64rpx;
	.title {
		text-align: left;
		font-size: 22px;
		font-family: PingFang-SC-Regular, PingFang-SC;
		font-weight: 400;
		color: #171717;
		line-height: 30px;
		margin-bottom: 12rpx;
	}
	.desc {
		text-align: left;
		font-size: 14px;
		font-family: PingFang-SC-Regular, PingFang-SC;
		font-weight: 400;
		color: #8f92a1;
		line-height: 14px;
	}
	.avatar {
		width: 160rpx;
		height: 160rpx;
		overflow: hidden;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 128rpx auto 160rpx auto;
		image {
			width: 100%;
			height: 100%;
		}
	}
}

.loginSmsCode {
	width: 100%;
}
.smscode {
	font-size: 28rpx;
	font-family: PingFang-SC-Regular, PingFang-SC;
	font-weight: 400;
	color: $app-theme-color;
	line-height: 28rpx;
}
</style>
