<template>
	<view :style="colorStyle">
		<view class="system-height" :style="{ height: statusBarHeight }"></view>
		<!-- #ifdef MP -->
		<view class="title-bar" style="height: 43px;">
			<!-- <view class="icon" @click="back" v-if="!isHome">
				<image src="../static/left.png"></image>
			</view>
			<view class="icon" @click="home" v-else>
				<image src="../static/home.png"></image>
			</view> -->
			小程序登录
		</view>
		<!-- #endif -->



		<view class="w_login">

			<view class="circle">
			</view>
			<view class="info1">
				欢迎进入中意购
			</view>
			<view class="info2">
				为您提供优质服务,中意够需要获取以下信息
				您的公开信息 (昵称、头像)
			</view>

			<button class="now" open-type="getPhoneNumber" hover-class="none" @getphonenumber="getPhoneNumber">
				使用微信权限登录
			</button>
			<button class="not_now" @click="cancelLogin">
				暂不登录
			</button>
		</view>
		<block v-if="isUp">
			<mobileLogin :isUp="isUp" @close="maskClose" :wxcode="code" :authKey="authKey" @wechatPhone="wechatPhone">
			</mobileLogin>
		</block>
		<block v-if="isPhoneBox">
			<routinePhone :logoUrl="logoUrl" :isPhoneBox="isPhoneBox" @close="bindPhoneClose" :authKey="authKey">
			</routinePhone>
		</block>
	</view>
</template>

<script>
const app = getApp();
let statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
import mobileLogin from '../components/login_mobile/index.vue';
import routinePhone from '../components/login_mobile/routine_phone.vue';
import {
	getLogo,
	silenceAuth,
	getUserPhone,
	wechatAuthV2
} from '@/api/public';
import {
	LOGO_URL,
	EXPIRES_TIME,
	USER_INFO,
	STATE_R_KEY
} from '@/config/cache';
import {
	getUserInfo
} from '@/api/user.js';
import {
	bindParentId
} from '@/api/groupon.js';
import {
	postLoginAuth
} from '@/api/home.js';
import Routine from '@/libs/routine';
import wechat from '@/libs/wechat';
import colors from '@/mixins/color.js';
export default {
	mixins: [colors],
	data () {
		return {
			inviteUserId:'',
			isUp: false,
			phone: '',
			statusBarHeight: statusBarHeight,
			isHome: false,
			isPhoneBox: false,
			logoUrl: '',
			code: '',
			authKey: '',
			options: '',
			userInfo: {},
			codeNum: 0,
			canUseGetUserProfile: false
		};
	},
	components: {
		mobileLogin,
		routinePhone
	},
	onLoad (options) {
		this.inviteUserId=this.$Cache.get("INVITE_USER_ID")
		console.log("+++++++++INVITE_USER_ID+++++++++++++",this.inviteUserId)
		if (uni.getUserProfile) {
			this.canUseGetUserProfile = true
		}
		this.logoUrl = "https://demo26.crmeb.net/statics/system_images/login_logo.jpeg";
		// getLogo().then(res => {
		// 	this.logoUrl = res.data.logo_url;
		// });
		let that = this;
		// #ifdef MP
		Routine.getCode()
			.then(code => {
				this.code = code
			})
		// #endif
		// #ifdef H5
		document.body.addEventListener('focusout', () => {
			setTimeout(() => {
				const scrollHeight = document.documentElement.scrollTop || document.body
					.scrollTop ||
					0;
				window.scrollTo(0, Math.max(scrollHeight - 1, 0));
			}, 100);
		});
		const {
			code,
			state,
			scope
		} = options;
		this.options = options;
		// 获取确认授权code
		this.code = code || '';
		if (code && this.options.scope !== 'snsapi_base') {
			let spread = app.globalData.spid ? app.globalData.spid : '';
			//公众号授权登录回调
			wechat
				.auth(code, state)
				.then(res => {
					if (res.key !== undefined && res.key) {
						that.authKey = res.key;
						that.isUp = true;
					} else {
						let time = res.expires_time - that.$Cache.time();
						that.$store.commit('LOGIN', {
							token: res.token,
							time: time
						});
						that.userInfo = res.userInfo;
						that.$store.commit('SETUID', res.userInfo.userId);
						that.$store.commit('UPDATE_USERINFO', res.userInfo);
						that.wechatPhone();
					}
				})
				.catch(error => {
					// location.replace("/");
				});
		}
		// #endif
		let pages = getCurrentPages();
		let prePage = pages[pages.length - 2];
		if (prePage && prePage.route == 'pages/order_addcart/order_addcart') {
			this.isHome = true;
		} else {
			this.isHome = false;
		}
	},
	methods: {
		back () {
			uni.navigateBack();
		},
		home () {
			uni.switchTab({
				url: '/pages/index/index'
			})
		},
		// 弹窗关闭
		maskClose () {
			this.isUp = false;
		},
		bindPhoneClose (data) {
			if (data.isStatus) {
				this.isPhoneBox = false;
				this.$util.Tips({
					title: this.$t(`登录成功`),
					icon: 'success'
				}, {
					tab: 3
				});
			} else {
				this.isPhoneBox = false;
			}
		},
		cancelLogin () {
			uni.switchTab({
				url: '/pages/index/index'
			})
		},
		getPhoneNumber (e) {
			let _this = this;
			console.log(e)
			if (e.detail.errMsg === 'getPhoneNumber:fail user deny' || !e.detail.code) {
				console.log("用户拒绝获取手机号");
				return
			}
			uni.showLoading({
				title: this.$t(`正在登录中`)
			});
			let data = {
				code: '',
				getPhoneNumberCode: ''
			}
			data.getPhoneNumberCode = e.detail.code
			uni.login({
				"provider": "weixin",
				"onlyAuthorize": true, // 微信登录仅请求授权认证
				success: function (event) {
					console.log(event.code)
					data.code = event.code
					console.log(data)
					//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
					postLoginAuth(data).then(res => {
						if (res.code === 200) {
							_this.$store.commit('LOGIN', {
								token: res.data.access_token,
								time: res.data.expires_in
							});
							_this.$store.commit('OPENID', res.data.openId);
							_this.getUserInfo();
							// 登录成功，跳转首页
							uni.showToast({
								title: "登录成功，即将跳转首页",
								icon: 'none',
								duration: 2000
							});
							console.log("+++++++++INVITE_USER_ID+++++++++111111111111++++",_this.inviteUserId)

							if (_this.inviteUserId && _this.inviteUserId !== "null"){
								console.log("+++++++++INVITE_USER_ID++++++22222222222+++++++",_this.inviteUserId)

								bindParentId(_this.inviteUserId).then(res =>{
									_this.$Cache.clear('INVITE_USER_ID');
								})
								console.log("+++++++++INVITE_USER_ID++++++3333333333333+++++++",_this.inviteUserId)
							}


							setTimeout(() => {
								// 自动登录失败时，跳转用户注册
								uni.switchTab({
									url: '/pages/index/index',
									success: (success) => {
										//获取当前页面的实例按照数组的顺序排列[0]开始首页，因为我就是首页和我的页面所以分别为0和1
										let page = getCurrentPages().pop()
										console.log(page,success, '肏！',page.$vm.$refs.diy);
										page.$vm.$refs.diy.$refs.latestGroupBuying.onLoadData(0);
									},
								})
							}, 2000);

						} else {
							uni.hideLoading();
							uni.showToast({
								title: "登录失败",
								icon: 'none',
								duration: 2000
							});

						}
					}).catch(res => {
						uni.hideLoading();
					});

				},
				fail: function (err) {
					// 登录授权失败
					uni.$u.toast('登录失败,错误代码：' + err.code);
				}
			})


		},

		getPhoneCode (e) {
			console.log(e)
			if (e.detail.errMsg == 'getPhoneNumber:fail user deny' || !e.detail.code) {
				console.log("用户拒绝获取手机号");
				return
			}
			uni.showLoading({
				title: this.$t(`正在登录中`)
			});
			postLoginAuth({
				getPhoneNumberCode: e.detail.code,
				// iv: iv,
				code: this.code,
				// spread_spid: app.globalData.spid,
				// spread_code: app.globalData.code
			})
				.then(res => {
					if (res.code == 200) {
						this.$store.commit('LOGIN', {
							token: res.data.access_token,
							time: res.data.expires_in
						});
						this.$store.commit('OPENID', res.data.openId);
						this.getUserInfo();
					} else {
						uni.hideLoading();
						uni.showToast({
							title: "手机号暂未注册,即将跳转注册界面",
							icon: 'none',
							duration: 2000
						});
						setTimeout(() => {
							// 自动登录失败时，跳转用户注册
							uni.navigateTo({
								url: '/pages/users/register/index?account=' + res.data
							})
						}, 2000);
					}
				})
				.catch(res => {
					uni.hideLoading();
				});
		},
		// #ifdef MP
		// 小程序获取手机号码
		getphonenumber (e) {
			uni.showLoading({
				title: this.$t(`正在登录中`)
			});
			Routine.getCode()
				.then(code => {
					this.getUserPhoneNumber(e.detail.encryptedData, e.detail.iv, code);
				})
				.catch(error => {
					uni.$emit('closePage', false);
					uni.hideLoading();
				});
		},
		// 小程序获取手机号码回调
		getUserPhoneNumber (encryptedData, iv, code) {
			console.log(this.code);
			console.log(code);
			postLoginAuth({
				getPhoneNumberCode: code,
				// iv: iv,
				code: this.code,
				// spread_spid: app.globalData.spid,
				// spread_code: app.globalData.code
			})
				.then(res => {
					let time = res.data.expires_time - this.$Cache.time();
					this.$store.commit('LOGIN', {
						token: res.data.token,
						time: time
					});
					this.userInfo = res.data.userInfo;
					this.$store.commit('SETUID', res.data.userInfo.userId);
					this.$store.commit('UPDATE_USERINFO', res.data.userInfo);
					this.$Cache.clear('snsapiKey');
					this.$util.Tips({
						title: this.$t(`登录成功`),
						icon: 'success'
					}, {
						tab: 4
					});
				})
				.catch(res => {
					uni.hideLoading();
				});
		},
		/**
		 * 获取个人用户信息
		 */
		getUserInfo: function () {
			console.log("获取个人信息+++++++++++++++++++++++++++++++++")
			let that = this;
			getUserInfo().then(res => {
				uni.hideLoading();
				that.userInfo = res.data;
				that.$store.commit('SETUID', res.data.userId);
				that.$store.commit('UPDATE_USERINFO', res.data);
				let GOOD_ID_LOGIN = this.$Cache.get('GOOD_ID_LOGIN')
				if (GOOD_ID_LOGIN) {
					that.$util.Tips({
						title: that.$t(`登录成功`),
						icon: 'success'
					});
				} else {
					that.$util.Tips({
						title: that.$t(`登录成功`),
						icon: 'success'
					}, {
						tab: 3
					});
				}
			});
		},
		setUserInfo (e) {
			uni.showLoading({
				title: this.$t(`正在登录中`)
			});
			Routine.getCode()
				.then(code => {
					this.getWxUser(code);
				})
				.catch(res => {
					uni.hideLoading();
				});
		},
		//小程序授权api替换 getUserInfo
		getUserProfile () {
			uni.showLoading({
				title: this.$t(`正在登录中`)
			});
			let self = this;
			Routine.getUserProfile()
				.then(res => {
					let userInfo = res.userInfo;
					console.log(this.code);
					console.log(userInfo);
					userInfo.code = this.code;
					uni.showToast({
						title: "手机号暂未注册,即将跳转注册界面",
						icon: 'none',
						duration: 2000
					});
					setTimeout(() => {
						// 自动登录失败时，跳转用户注册
						uni.navigateTo({
							url: '/pages/users/register/index'
						})
					}, 2000);

					// userInfo.spread_spid = app.globalData.spid || this.$Cache.get('spread'); //获取推广人ID
					// userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID
					// 模拟授权登录成功
					// self.$store.commit('LOGIN', {
					// 	token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ2NC5jcm1lYi5uZXQiLCJhdWQiOiJ2NC5jcm1lYi5uZXQiLCJpYXQiOjE2NjY1Nzk2NzgsIm5iZiI6MTY2NjU3OTY3OCwiZXhwIjoxNjY5MTcxNjc4LCJqdGkiOnsiaWQiOjM0MzkxLCJ0eXBlIjoiYXBpIn19.GA3Lyr3HueKXwz9GWS6KrO4rYKmJzn3l7ko1nsl7E7Q',
					// 	time: 9999999999999
					// });
					// this.getUserInfo()
					// Routine.authUserInfo(userInfo)
					// 	.then(res => {
					// 		if (res.data.key !== undefined && res.data.key) {
					// 			uni.hideLoading();
					// 			self.authKey = res.data.key;
					// 			self.isPhoneBox = true;
					// 		} else {
					// 			uni.hideLoading();
					// 			let time = res.data.expires_time - self.$Cache.time();
					// 			self.$store.commit('LOGIN', {
					// 				token: res.data.token,
					// 				time: time
					// 			});
					// 			this.getUserInfo()
					// 		}
					// 	})
					// 	.catch(res => {
					// 		uni.hideLoading();
					// 		uni.showToast({
					// 			title: res.msg,
					// 			icon: 'none',
					// 			duration: 2000
					// 		});
					// 	});
				})
				.catch(res => {
					uni.hideLoading();
				});
		},
		getWxUser (code) {
			let self = this;
			Routine.getUserInfo()
				.then(res => {
					let userInfo = res.userInfo;
					userInfo.code = code;
					userInfo.spread_spid = app.globalData.spid; //获取推广人ID
					userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID
					Routine.authUserInfo(userInfo)
						.then(res => {
							if (res.data.key !== undefined && res.data.key) {
								uni.hideLoading();
								self.authKey = res.data.key;
								self.isPhoneBox = true;
							} else {
								uni.hideLoading();
								let time = res.data.expires_time - self.$Cache.time();
								self.$store.commit('LOGIN', {
									token: res.data.token,
									time: time
								});
								self.$util.Tips({
									title: res.msg,
									icon: 'success'
								}, {
									tab: 3
								});
							}
						})
						.catch(res => {
							uni.hideLoading();
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							});
						});
				})
				.catch(res => {
					uni.hideLoading();
				});
		},

		// #endif
		// #ifdef H5
		// 获取url后面的参数
		getQueryString (name) {
			var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
			var reg_rewrite = new RegExp('(^|/)' + name + '/([^/]*)(/|$)', 'i');
			var r = window.location.search.substr(1).match(reg);
			var q = window.location.pathname.substr(1).match(reg_rewrite);
			if (r != null) {
				return unescape(r[2]);
			} else if (q != null) {
				return unescape(q[2]);
			} else {
				return null;
			}
		},
		// 公众号登录
		wechatLogin () {
			if (!this.code || this.options.scope !== 'snsapi_base') {
				this.$wechat.oAuth('snsapi_userinfo', '/pages/users/wechat_login/index');
			} else {
				if (this.authKey) {
					this.isUp = true;
				}
			}
		},
		// 输入手机号后的回调
		wechatPhone () {
			console.log(2222)
			this.$Cache.clear('snsapiKey');
			if (this.options.back_url) {
				let url = uni.getStorageSync('snRouter');
				url = url.indexOf('/pages/index/index') != -1 ? '/' : url;
				if (url.indexOf('/pages/users/wechat_login/index') !== -1) {
					url = '/';
				}
				if (!url) {
					url = '/pages/index/index';
				}
				this.isUp = false;
				uni.showToast({
					title: this.$t(`登录成功`),
					icon: 'none'
				});
				setTimeout(res => {
					location.href = url;
				}, 800);
			} else {
				this.isUp = false;
				uni.showToast({
					title: this.$t(`登录成功`),
					icon: 'none'
				});
				setTimeout(res => {
					location.href = '/pages/index/index';
				}, 800);
			}
		}
		// #endif
	}
};
</script>

<style lang="scss">
page {
	background: #fff;
}

.wechat_login {
	padding: 72rpx 34rpx;

	.img image {
		width: 100%;
	}

	.btn-wrapper {
		margin-top: 86rpx;
		padding: 0 66rpx;

		button {
			width: 100%;
			height: 86rpx;
			line-height: 86rpx;
			margin-bottom: 40rpx;
			border-radius: 120rpx;
			font-size: 30rpx;

			&.btn1 {
				color: #fff;
			}

			&.btn2 {
				color: #666666;
				border: 1px solid #666666;
			}
		}
	}
}

.title-bar {
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 36rpx;
}

.icon {
	position: absolute;
	left: 30rpx;
	top: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 86rpx;
	height: 86rpx;

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

.w_login {
	padding: 30rpx;

	.circle {
		border-radius: 50%;
		width: 106rpx;
		height: 106rpx;
		background: rgb(238, 238, 238);
		margin: auto;
	}

	.info1 {
		text-align: center;
		font-size: 48rpx;
		font-weight: 600;
		color: #333333;
		line-height: 66rpx;
		margin-bottom: 30rpx;
	}

	.info2 {
		text-align: center;
		font-size: 28rpx;
		font-weight: 400;
		color: #999999;
		line-height: 44rpx;
		margin-bottom: 200rpx;
	}

	.now {
		width: 100%;
		height: 96rpx;
		background: #B42A3E;
		border-radius: 8rpx;
		font-size: 32rpx;
		font-weight: 400;
		color: #FFFFFF;
		line-height: 96rpx;
		margin-bottom: 20rpx;
	}

	.not_now {
		width: 100%;
		height: 96rpx;
		background: #F5F5F5;
		border-radius: 8rpx;






		font-size: 32rpx;


		font-weight: 400;
		color: #999999;
		line-height: 96rpx;
	}
}
</style>
