<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/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.sign_time }}</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 { getSign, agentSign, getActivityPlaceIp } from '../../api/sign_in.js';
function Rad(d){
   return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
}
function GetDistance(lat1, lng1, lat2, lng2){
	var radLat1 = Rad(lat1);
	var radLat2 = Rad(lat2);
	var a = radLat1 - radLat2;
	var  b = Rad(lng1) - Rad(lng2);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
	Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	return s;
}
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('agentId', options.scene);
		}
	},
	onShow() {
		// if (!uni.getStorageSync('token')) {
		// 	uni.showModal({
		// 		content: '您还未登录小程序，请先登录',
		// 		showCancel: false,
		// 		success: res => {
		// 			if (res.confirm) {
		// 				uni.switchTab({
		// 					url: '../index/index'
		// 				});
		// 			}
		// 		}
		// 	});
		// } else {
		// 	this.getSign();
		// }
		let that = this;
		that.getSetting();
		if (!uni.getStorageSync('token')) {
			that.isAuthLogin = true;
		} else {
			that.getUserInfo();
			that.getSign();
		}
	},
	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: {
		//获取代理报名信息
		getSign() {
			getSign({ id: this.id || uni.getStorageSync('agentId') }).then(res => {
				if (res.code == 200) {
					this.signInfo = res.data;
				} else {
					uni.showModal({
						content: res.message || '请求失败',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.switchTab({
									url: '../index/index'
								});
							}
						}
					});
				}
			});
		},
		//代理确认签到
		async signIn() {
			const _ip = await getActivityPlaceIp()
			if(!_ip  || _ip.code !== 200) {
				uni.showModal({
					title: '签到失败',
					content: '获取活动举办地地址ip失败',
					showCancel: false
				})
				return false
			}
			let { data: { lng, lat, location_status, distance: maxDis } } = _ip
			let { longitude: lng1, latitude: lat1 } = this.wechatInfo
			const _dis = GetDistance(lat1, lng1, lat, lng)
			if(location_status && _dis > maxDis) {
				uni.showModal({
					title: '签到失败',
					content: '您的签到地址超出签到范围',
					showCancel: false
				})
				return false
			}
			agentSign({ id: this.signInfo.id }).then(res => {
				if (res.code == 200) {
					let { nickname, sign_time, phone, season, type } = this.signInfo;
					uni.showModal({
						title: '提示',
						content: '签到成功！',
						showCancel: false,
						success: res => {
							if (res.confirm) {
								uni.reLaunch({
									url:
										'../written_off/written_off?nickname=' +
										nickname +
										'&created_at=' +
										sign_time +
										'&phone=' +
										phone +
										'&path=' +
										0 +
										'&season=' +
										season +
										'&type=' +
										type
								});
							}
						}
					});
				} else {
					uni.showModal({
						content: res.message || '请求失败',
						showCancel: false,
						success: res => {
							if (res.confirm) {
								uni.switchTab({
									url: '../index/index'
								});
							}
						}
					});
				}
			});
		},
		//判断用户是否打开定位权限
		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 => {
					console.log(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;
						that.getLocation();
						// 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.getSign();
									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.getSign();
								that.getUserInfo();
							} else {
								uni.showModal({
									content: res.message || '请求失败',
									showCancel: false
								});
							}
						})
						.catch(e => {})
						.finally(() => {
							that.loginStatus = true;
						});
				}
			});
		},
		// 获取用户信息
		getUserInfo() {
			var that = this;
			that.getSetting();
			let { latitude, longitude } = that.wechatInfo;
			getUserInfo({ latitude, longitude })
				.then(res => {
					if (res.code === 200) {
						this.userInfo = res.data;
						uni.setStorageSync('userInfo', res.data);
					} else {
						uni.showModal({
							content: res.message || '请求失败',
							showCancel: false
						});
					}
				})
				.catch(e => {});
		}
	}
};
</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>
