<template>
	<view class="voucher">
		<image src="../../static/imgs/sign_in_before.jpg" class="bgImg"></image>
		<view class="voucher_con">
			<view class="line"></view>
			<view class="title">第{{ signInfo.season ? signInfo.season : '' }}届大卫博士创业密训{{ signInfo.type == 1 ? '密训' : '实训' }}营</view>
			<view class="voucher_icon">
				<image src="../../static/imgs/written_off.png"></image>
				<view>有效凭证</view>
			</view>
			<view class="info">
				<view class="flexS">
					<text>报名人：</text>
					<view>{{ signInfo.nickname }}</view>
				</view>
				<view class="flexS">
					<text>手机号：</text>
					<view>{{ signInfo.phone }}</view>
				</view>
				<view class="flexS">
					<text>报名时间：</text>
					<view>{{ signInfo.created_at }}</view>
				</view>
			</view>
			<view class="btn flexC" @click="signIn">确认签到</view>
		</view>
		<view class="auth_login flexC" v-if="isAuthLogin"><button open-type="getUserInfo" @getuserinfo="userLogin" class="auth_btn">点击登录</button></view>
		<view class="phone_login" v-if="isPhoneLogin">
			<view class="phone_container">
				<view class="close" @click="isPhoneLogin = false"></view>
				<view class="top">
					<text>手机号验证</text>
					<div class="userImg"><open-data type="userAvatarUrl" class="getImgBtn"></open-data></div>
				</view>
				<view class="bottom">
					<input v-model="phone" type="text" placeholder="请输入手机号" class="input" maxlength="11" />
					<view class="bottom_eqcode">
						<input v-model="code" type="text" placeholder="输入验证码" class="input eqcode_input" />
						<view class="eqcode" @click="getCode">{{ countDown ? `重新获取(${countDown}s)` : '获取验证码' }}</view>
					</view>
				</view>
				<view class="submit_btn" @click="phoneLogin">提交</view>
			</view>
		</view>
	</view>
</template>

<script>
import { wecatLogin, getUserInfo, phoneLogin, sendCode } from '../../api/index.js';
import { getUser, sureSign } from '../../api/sign_in.js';
export default {
	data() {
		return {
			userInfo: {}, //用户信息
			id: '', //扫码获取的id
			signInfo: {}, //报名人信息
			isAuthLogin: false, //是否显示登陆授权按钮
			isPhoneLogin: false, //是否显示手机登陆弹窗
			wechatInfo: {
				latitude: '',
				longitude: '',
				avatarUrl: '',
				nickName: ''
			}, //微信信息
			phone: '', //手机号
			code: '', //验证码
			countDown: 0, //验证码倒计时
			loginStatus: true //登陆状态
		};
	},
	onLoad(options) {
		if (options.scene) {
			this.id = options.scene;
			uni.setStorageSync('id', options.scene);
		}
		if (options.id) {
			this.id = options.id;
			uni.setStorageSync('id', options.id);
		}
	},
	onShow() {
		let that = this;
		that.getSetting();
		if (!uni.getStorageSync('token')) {
			that.isAuthLogin = true;
		} else {
			this.getUser();
			this.getUserInfo();
		}
	},
	watch: {
		isAuthLogin(a) {
			if (!a) {
				let that = this;
				wx.login({
					success({ code }) {
						that.wechatInfo.code = code;
					}
				});
			}
		},
		isPhoneLogin(a) {
			if (!a) {
				this.phone = '';
				this.code = '';
			}
		}
	},
	methods: {
		//判断用户是否打开定位权限
		getSetting() {
			let that = this;
			uni.getSetting({
				success: res => {
					// 从未触发过授权的情况
					if (typeof res.authSetting['scope.userLocation'] == 'undefined') {
						this.getLocation();
						return false;
					}
					//位置授权关闭 引导开启
					if (!res.authSetting['scope.userLocation']) {
						uni.showModal({
							title: '是否授权当前位置',
							content: '如需正常使用本程序，请在授权管理中选中“地理位置”，然后点按返回即可正常使用',
							showCancel: false,
							success: res => {
								if (res.confirm) {
									that.openSetting();
								}
							}
						});
						return false;
					}
					//位置授权开启，获取当前位置
					if (res.authSetting['scope.userLocation']) {
						this.getLocation();
					}
				},
				fail: err => {
					console.log(err);
				}
			});
		},
		openSetting() {
			wx.openSetting({
				success: res => {
					let that = this;
					if (res.authSetting['scope.userLocation']) {
						this.getLocation();
					}
				},
				fail: err => {
					uni.showModal({
						content: '开启位置权限失败,请手动开启',
						showCancel: false
					});
				}
			});
		},
		getLocation() {
			let that = this;
			uni.getLocation({
				// 用户同意授权地理位置
				success: ({ latitude, longitude }) => {
					that.wechatInfo.latitude = latitude;
					that.wechatInfo.longitude = longitude;
				},
				fail: function(err) {
					// 授权地理位置调用失败
					// if (err.errMsg == 'getLocation:fail system permission denied') {
					// 	uni.showModal({
					// 		content: '获取位置失败，请检查手机GPS或者微信使用手机定位权限是否开启',
					// 		showCancel: false
					// 	});
					// 	return false;
					// }
					if (err.errMsg == 'getLocation:fail auth deny') {
						uni.showModal({
							title: '是否授权当前位置',
							content: '取消位置授权，将影响您使用小程序，请重新开启授权',
							showCancel: false,
							success: res => {
								if (res.confirm) {
									that.openSetting();
								}
							}
						});
					}
				}
			});
		},
		// 获取验证码
		getCode() {
			let that = this;
			if (that.countDown) {
				uni.showModal({
					content: '验证码已发送，请稍后重试',
					showCancel: false
				});
				return false;
			}
			if (!that.phone) {
				uni.showModal({
					content: '请输入手机号',
					showCancel: false
				});
				return false;
			}
			sendCode({
				phone: that.phone
			}).then(res => {
				if (res.code != 200) {
					uni.showModal({
						content: res.message || '获取验证码失败',
						showCancel: false
					});
					return false;
				}
				if (res.code == 200) {
					uni.showModal({
						content: '验证码发送成功',
						showCancel: false
					});
					this.countDown = 60;
					this.timer = setInterval(() => {
						this.countDown--;
						if (!this.countDown) {
							this.countDown = 0;
							clearInterval(this.timer);
						}
					}, 1000);
				}
			});
		},
		/*微信登录获取 token
		 * @params openid用户openid 传空
		 * @params avatar 用户头像
		 * @params nickname  用户昵称
		 * @params code  微信登录code
		 * @params longitude 用户位置经度
		 * @params latitude  用户位置维度
		 */
		userLogin({ detail }) {
			let that = this;
			if (detail.errMsg === 'getUserInfo:ok') {
				that.wechatInfo.avatarUrl = detail.userInfo.avatarUrl;
				that.wechatInfo.nickName = detail.userInfo.nickName;
				uni.login({
					success: ({ code }) => {
						that.wechatInfo.code = code;
						// if (!that.wechatInfo.longitude && !that.wechatInfo.latitude) {
						// 	uni.showModal({
						// 		content: '获取位置失败，请检查手机GPS或者微信使用手机定位权限是否开启',
						// 		showCancel: false
						// 	});
						// 	return false;
						// }
						let { avatarUrl, nickName, latitude, longitude } = that.wechatInfo;
						wecatLogin({
							openid: '',
							avatar: avatarUrl,
							nickname: nickName,
							code: code,
							longitude: longitude,
							latitude: latitude
						})
							.then(res => {
								if (res.code === 300) {
									that.isAuthLogin = false;
									that.isPhoneLogin = true;
								} else if (res.code === 200) {
									uni.setStorageSync('token', res.data.token);
									that.getUserInfo();
								} else {
									uni.showModal({
										content: res.message,
										showCancel: false
									});
								}
							})
							.catch(e => {})
							.finally(() => {
								that.isAuthLogin = false;
							});
					}
				});
			} else {
				uni.showModal({
					content: '不授权将无法获取到您的信息，请手动开启授权',
					showCancel: false,
					success: res => {
						if (res.confirm) {
							wx.openSetting({
								success: res => {
									let that = this;
									if (res.authSetting['scope.userInfo']) {
										uni.showModal({
											content: '用户权限已开启',
											showCancel: false
										});
									} else {
										uni.showModal({
											content: '您未开启用户信息权限',
											showCancel: false
										});
									}
								},
								fail: err => {
									uni.showModal({
										content: '开启用户信息权限失败',
										showCancel: false
									});
								}
							});
						}
					}
				});
			}
		},
		// 手机验证码登陆
		phoneLogin() {
			let that = this;
			if (!that.phone) {
				uni.showModal({
					content: '手机号不存在',
					showCancel: false
				});
				return false;
			}
			if (!that.code) {
				uni.showModal({
					content: '验证码不存在',
					showCancel: false
				});
				return false;
			}
			if (!that.loginStatus) return false;
			that.loginStatus = false;
			uni.login({
				success: ({ code }) => {
					phoneLogin({
						phone: that.phone,
						phone_code: that.code,
						avatar: that.wechatInfo.avatarUrl,
						nickname: that.wechatInfo.nickName,
						longitude: that.wechatInfo.longitude,
						latitude: that.wechatInfo.latitude,
						code
					})
						.then(res => {
							if (res.code === 200) {
								this.isPhoneLogin = false;
								uni.setStorageSync('token', res.data.token);
								that.getUserInfo();
								that.getUser();
							} else {
								uni.showModal({
									content: res.message || '请求失败',
									showCancel: false
								});
							}
						})
						.catch(e => {})
						.finally(() => {
							that.loginStatus = true;
						});
				}
			});
		},
		// 获取用户信息
		getUserInfo() {
			var that = this;
			if (!that.wechatInfo.latitude && that.wechatInfo.longitude) {
				that.getSetting();
				return false;
			}
			let { latitude, longitude } = that.wechatInfo;
			getUserInfo({ latitude, longitude })
				.then(res => {
					if (res.code === 200) {
						this.userInfo = res.data;
						uni.setStorageSync('userInfo', res.data);
						this.getUser();
					} else {
						uni.showModal({
							content: res.message || '请求失败',
							showCancel: false
						});
					}
				})
				.catch(e => {});
		},
		/*获取用户的报名信息
		 * @params:id  扫码获得的id
		 */
		getUser() {
			getUser({ id: this.id || uni.getStorageSync('id') }).then(res => {
				if (res.code != 200) {
					uni.showModal({
						content: res.message,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.switchTab({
									url: '../index/index'
								});
							}
						}
					});
					return false;
				}
				if (res.code == 200) {
					this.signInfo = res.data;
				}
			});
		},
		/*确认签到
		 * @params:id  扫码获得的id
		 */
		signIn() {
			sureSign({ id: this.signInfo.id }).then(res => {
				if (res.code == 200) {
					let { nickname, created_at, phone, season, type } = this.signInfo;
					uni.showToast({
						title: '签到成功！',
						duration: 2000,
						success: res => {
							uni.reLaunch({
								url:
									'../written_off/written_off?nickname=' +
									nickname +
									'&created_at=' +
									created_at +
									'&phone=' +
									phone +
									'&path=' +
									1 +
									'&season=' +
									season +
									'&type=' +
									type
							});
						}
					});
				} else {
					uni.showModal({
						content: res.message || '请求失败',
						showCancel: false,
						success: res => {
							uni.redirectTo({
								url: '../sign_in/sign_in'
							});
						}
					});
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.phone_login {
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: rgba(0, 0, 0, 0.3);

	.phone_container {
		width: 570rpx;
		background-color: #ffffff;
		border-radius: 10rpx;
		overflow: hidden;
		position: relative;

		.close {
			&::before {
				position: absolute;
				top: 26rpx;
				right: 26rpx;
				content: '\2716';
				display: block;
				width: 30rpx;
				height: 30rpx;
				color: #ffffff;
				z-index: 9999;
			}
		}

		.top {
			width: 100%;
			height: 220rpx;
			background-color: #fa6342;
			color: #ffffff;
			font-size: 40rpx;
			padding-top: 50rpx;
			font-weight: blod;
			box-sizing: border-box;
			display: flex;
			justify-content: flex-start;
			flex-direction: column;
			align-items: center;
			position: relative;

			.userImg {
				position: absolute;
				width: 138rpx;
				height: 138rpx;
				border-radius: 50%;
				bottom: -69rpx;
				overflow: hidden;

				.getImgBtn {
					width: 138rpx;
					height: 138rpx;
				}
			}
		}

		.bottom {
			padding: 100rpx 60rpx 30rpx;
			background-color: #ffffff;

			.input {
				width: 100%;
				height: 70rpx;
				padding: 0 17rpx;
				box-sizing: border-box;
				color: #000000;
				font-size: 30rpx;
				background-color: #eeeeee;
				border-radius: 2rpx;
			}

			.bottom_eqcode {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 60rpx;

				.eqcode_input {
					width: 240rpx;
				}

				.eqcode {
					width: calc(100% - 240rpx);
					color: #fa6342;
					font-size: 32rpx;
					text-align: right;
				}
			}
		}

		.submit_btn {
			width: 100%;
			height: 86rpx;
			line-height: 86rpx;
			text-align: center;
			background-color: rgba(250, 99, 66, 0.2);
			color: #fa6342;
			font-size: 32rpx;
		}
	}
}
.auth_login {
	position: fixed;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background-color: rgba(0, 0, 0, 0.8);
	.auth_btn {
		width: 80%;
		height: 88rpx;
		background: #ea4a41;
		color: #fff;
	}
}
.voucher {
	hieght: 100vh;
	min-height: 100vh;
	width: 100vw;
	position: relative;
	.bgImg {
		height: 100vh;
		width: 100vw;
		position: fixed;
		top: 0;
		left: 0;
	}
	.voucher_con {
		position: fixed;
		height: 80%;
		width: 100%;
		bottom: 0;
		left: 0;
		background: #fff;
		border-top-left-radius: 60rpx;
		border-top-right-radius: 60rpx;
		.line {
			width: 128rpx;
			height: 8rpx;
			background: #f1f3f5;
			margin: 36rpx auto 0;
		}
		.title {
			color: #333;
			font-size: 42rpx;
			margin: 48rpx auto 101rpx;
			text-align: center;
			font-weight: bold;
		}
		.voucher_icon {
			text-align: center;
			image {
				height: 192rpx;
				width: 192rpx;
				margin-bottom: 51rpx;
			}
			view {
				font-size: 48rpx;
				color: #07b159;
			}
		}
		.info {
			margin: 30rpx 0 40rpx 100rpx;
			> view {
				margin-top: 34rpx;
				font-size: 28rpx;
				text {
					color: #656565;
				}
				view {
					color: #333333;
				}
			}
		}
		.btn {
			width: 640rpx;
			margin: 0 auto;
			height: 88rpx;
			color: #fff;
			background-color: #07b159;
			border-radius: 44rpx;
			letter-spacing: 2rpx;
		}
	}
}
</style>
