<template>
	<view class="container login">
		<swiper class="banner">
			<swiper-item
				v-for="(v, k, i) in bannerData"
				:key="k"
			>
				<view
					class="item"
					:style="{ backgroundImage: `url(${v})` }"
				/>
			</swiper-item>
		</swiper>
		<view class="activity">
			<view class="activityInfo">
				<view
					class="activityInfo_status"
					:class="open ? '' : 'no'"
				>
					{{ open ? '火爆开启' : '暂未开启' }}
				</view>
				<view class="activityInfo_title">
					<view class="icon" />
					<view class="title">
						第{{ activityInfo.season | numToZh }}届大卫博士创业{{ activityInfo.season_type | seasonType }}
					</view>
				</view>
				<view class="activityInfo_content">
					<view class="item">
						<view class="circle" />
						<view class="content">
							举办地址：{{ address }}
						</view>
					</view>
					<view class="item">
						<view class="circle" />
						<view class="content">
							举办时间：{{ time }}
						</view>
					</view>
					<view class="item">
						<view class="circle" />
						<view class="content">
							<text>{{ activityStatus.k }}</text>
							<text class="spec">{{ activityStatus.t }}</text>
						</view>
					</view>
				</view>
			</view>
			<template v-if="!loginStatus">
				<button
					open-type="getUserInfo"
					class="activityBtn"
					@getuserinfo="toGetUserInfo"
				>
					登录查看详情
				</button>
			</template>
			<template v-else>
				<view class="activityBtn" @click="toLoginProgress">登录查看详情</view>
			</template>
		</view>
		<!-- 手机号登陆 -->
		<g-toast :is-show="phoneLogin" :is-close="false">
			<view class="bindTel">
				<view class="bindTelC">
					<view class="bindTelC_avatar">
						<open-data type="userAvatarUrl" />
					</view>
					<view class="bindTelC_form">
						<input
							v-model="telInfo.tel"
							type="number"
							class="bindTelC_form_input"
							placeholder="请输入您的手机号"
						/>
						<view class="bindTelC_form_code">
							<input
								v-model="telInfo.code"
								type="number"
								class="code"
								placeholder="验证码"
							/>
							<view
								class="send"
								@click="toSendTelCode"
							>
								{{ telInfo.status ? `${telInfo.time}s` : '发送验证码' }}
							</view>
						</view>
						<view class="bindTelC_form_tip">若验证失败请联系你的政委</view>
					</view>
				</view>
				<view class="bindTel_submit" @click="toServerPhoneLogin">提交</view>
			</view>
		</g-toast>
	</view>
</template>

<script>
	import { activityData, bannerData, serverLogin, sendTelCode, phoneLogin } from "../../api/login.js"
	import { dateFormatter, countDown } from "../../utiils/filters.js"
	import GToast from "../../components/global/toast.vue"
	export default {
		components: {
			GToast
		},
		data(){
			return {
				activityInfo: {},
				bannerData: {},
				activityStatus: {},
				intervalTimer: null,
				loginStatus: 0,
				phoneLogin: false,
				telInfo: {
					tel: '',
					code: '',
					key: '',
					status: false,
					time: 60,
					timer: null
				}
			}
		},
		computed: {
			// 活动开始
			open() {
				let { time_start:s, time_end:e } = this.activityInfo;
				if(!s || !e) return false
				const n = Date.now()
				return n < e && n >= s
			},
			// 活动地址
			address(){
				let { province: p, city: c, area: a } = this.activityInfo
				if(!p || !c || !a) return ''
				return `${p}${c}${a}`
			},
			// 活动时间
			time() {
				let { time_start:s, time_end:e } = this.activityInfo
				if(!s || !e) return ''
				const _c = t => dateFormatter(t * 1000, 'yyyy.MM.dd')
				return `${_c(s)}-${_c(e)}`
			}
		},
		watch: {
			// 登陆进度状态
			loginStatus(s) {
				this.toLoginProgress(s)
			},
			// 手机号验证码状态
			"telInfo.status"(flag) {
				if(flag) {
					const _this = this
					this.telInfo.timer = setInterval(() => {
						--_this.telInfo.time
					}, 1000)
				} else {
					if(this.telInfo.timer) {
						clearInterval(this.telInfo.timer) 
					}
					this.telInfo.timer = null
					this.telInfo.time = 60
				}
			},
			// 手机号验证码时间
			"telInfo.time"(a) {
				if(a <= 0) {
					this.telInfo.status = false
				}
			}
 		},
		onLoad() {
			this.loginInit()
			this.pageInit()
		},
		onUnload() {
			this.clearIntervalTime()
		},
		methods: {
			// 登录初始化
			async loginInit() {
				let token = await uni.getStorageSync("token")
				if(token) {
					// 登录成功直接跳转
					console.log('登陆成功: token')
					uni.switchTab({
						url: "../index/index"
					})
				} else {
					let wxUserInfo = await uni.getStorageSync("wxUserInfo")
					let wxUserLocation = await uni.getStorageSync("wxUserLocation")
					this.loginStatus = wxUserInfo ? wxUserLocation ? 2 : 1 : 0
				}
			},
			// 页面初始化
			pageInit() {
				this.intervalTime()
				this.getBannerData()
				this.getActivityData()
			},
			// 清除定时器
			clearIntervalTime() {
				const _this = this
				this.intervalTimer ? clearInterval(_this.intervalTimer) : null
				this.intervalTimer = null
				this.telInfo.telInfo ? clearInterval(_this.telInfo.timer) : null
				this.telInfo.timer = null
			},
			// 开始定时器
			intervalTime() {
				const _this = this
				this.intervalTimer = setInterval(_this.computedStatus, 1000)
			},
			// 活动状态
			computedStatus() {
				let { sign_start: s1, sign_end:e1, time_start: s2, time_end: e2 } = this.activityInfo
				const _c = n => n * 1000
				const n = Date.now()
				if(n < _c(s1)) {
					this.activityStatus = { k: '距报名开始仅剩:', t: countDown(_c(s1), n) }
				} else if (n < _c(e1) && n > _c(s1)) {
					this.activityStatus = { k: '距离报名截止仅剩:', t: countDown(_c(e1), n) }
				} else if (n < _c(s2)) {
					this.activityStatus = { k: '距离活动开始仅剩:', t: countDown(_c(s2), n) }
				} else if (n < _c(e2) && n > _c(s2)) {
					this.activityStatus = { k: '距离活动结束仅剩:', t: countDown(_c(e2), n) }
				} else {
					this.activityStatus = { k: '活动已结束:', t: '' }
				}
			},
			// 轮播信息
			getBannerData() {
				bannerData().then(res => {
					if(res.code === 200) {
						this.bannerData = res.data
					} else {
						uni.showModal({
							title: '失败',
							content: res.msg || '获取轮播图失败',
							showCancel: false
						})
					}
				}).catch(e => {
					uni.showModal({
						title: '失败',
						content: '获取轮播图失败',
						showCancel: false
					})
				})
			},
			// 活动信息
			getActivityData() {
				activityData().then(res => {
					if(res.code === 200) {
						this.activityInfo = res.data
					} else {
						uni.showModal({
							title: '失败',
							content: res.msg || '获取活动详情失败',
							showCancel: false
						})
					}
				}).catch(e => {
					uni.showModal({
						title: '失败',
						content: '获取活动详情失败',
						showCancel: false
					})
				})
			},
			// 登录过程
			toLoginProgress() {
				let m = new Map([
					[1, this.toGetUserLocation],
					[2, this.toServerWxLogin],
					[3, () => this.phoneLogin = true]
				])
				let s = this.loginStatus
				return m.get(s)()
			},
			// 微信授权
			toGetUserInfo(res) {
				let { detail: { errMsg } } = res;
				if(errMsg === 'getUserInfo:ok') {
					let { detail: { userInfo } } = res;
					uni.setStorageSync("wxUserInfo", userInfo)
					this.loginStatus += 1
				} else {
					uni.showModal({
						title: '失败',
						content: '获取微信信息授权失败',
						showCancel: false
					})
				}
				
			},
			// 获取微信位置
			toGetUserLocation() {
				const _this = this
				uni.getLocation({
					success(res) {
						let { longitude: lng, latitude: lat } = res;
						uni.setStorageSync("wxUserLocation", { lng, lat })
						_this.loginStatus += 1
					},
					fail() {
						uni.showModal({
							title: '失败',
							content: '获取定位失败,将不能进行签到',
							showCancel: false
						})
					}
				})
			},
			// 微信服务器登录
			async toServerWxLogin() {
				const _this = this
				const [, { code }] = await uni.login()
				const wxUserInfo = await uni.getStorageSync("wxUserInfo")
				const wxUserLocation = await uni.getStorageSync("wxUserLocation")
				serverLogin({
					openid: '',
					avatar: wxUserInfo.avatarUrl,
					nickname: wxUserInfo.nickName,
					code,
					longitude: wxUserLocation.lng,
					latitude: wxUserLocation.lat
				}).then(res => {
					if(res.code === 200) {
						let { data: { token } } = res
						uni.setStorage({
							key: 'token',
							data: token,
							success() {
								console.log('登陆成功: wx')
								uni.switchTab({
									url: "../index/index"
								})
							}
						})
					} else if (res.code === 300) {
						uni.showModal({
							title: '失败',
							content: '您的账号未进行手机绑定, 请先绑定手机号',
							showCancel: false,
							success(c_res) {
								if(c_res.confirm) {
									_this.loginStatus = 3
								}
							}
						})
					} else {
						uni.showModal({
							title: '失败',
							content: res.message || '服务器登录失败',
							showCancel: false
						})
					}
				}).catch(() => {
					uni.showModal({
						title: '失败',
						content: '服务器登录失败',
						showCancel: false
					})
				})
			},
			// 发送验证码
			toSendTelCode() {
				let { status, tel } = this.telInfo
				if(status) return false
				this.telInfo.status = true
				const errorMap = new Map([
					[400, '手机号不存在'],
					[600, '该手机号已被注册']
				])
				const teg = /^1\d{10}$/
				if(!teg.test(tel)) {
					uni.showModal({
						title: '失败',
						content: '请输入正确的手机号',
						showCancel: false
					})
					return false
				}
				sendTelCode({
					phone: tel
				}).then(res => {
					if(res.code === 200) {
						this.telInfo.status = true
						let { data: { verify_key } } = res
						this.telInfo.key = verify_key
					} else {
						uni.showModal({
							title: '失败',
							content: errorMap.get(res.code) || res.message || res.msg || '出现错误,验证码发送失败',
							showCancel: false
						})
					}
				}).catch(e => {
					uni.showModal({
						title: '失败',
						content: '出现错误,验证码发送失败',
						showCancel: false
					})
				})
			},
			// 手机号服务器登录
			async toServerPhoneLogin() {
				let { tel, code, key } = this.telInfo
				const teg = /^1\d{10}$/
				if(!teg.test(tel)) {
					uni.showModal({
						title: '失败',
						content: '请输入正确的手机号',
						showCancel: false
					})
					return false
				}
				if(!code) {
					uni.showModal({
						title: '失败',
						content: '请输入验证码',
						showCancel: false
					})
					return false
				}
				const [ , { code:wxCode }] = await uni.login()
				const errorMap = new Map([
					[300, '验证码错误'],
					[400, '验证码超时']
				])
				let { avatarUrl, nickName } = await uni.getStorageSync("wxUserInfo")
				let { lng, lat } = await uni.getStorageSync("wxUserLocation")
				phoneLogin({
					phone: tel,
					phone_code: code,
					avatar: avatarUrl,
					nickname: nickName,
					longitude: lng,
					latitude: lat,
					code: wxCode
				}).then(res => {
					if(res.code === 200) {
						let { data: { token } } = res
						uni.setStorage({
							key: 'token',
							data: token,
							success() {
								console.log('登陆成功: phone')
								uni.switchTab({
									url: "../index/index"
								})
							}
						})
					} else {
						uni.showModal({
							title: '失败',
							content: errorMap.get(res.code) || res.message || res.msg || '发生错误,手机号绑定登陆失败',
							showCancel: false
						})
					}
				}).catch(() => {
					uni.showModal({
						title: '失败',
						content: '手机号登陆失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.login {
		padding: 30rpx;
		box-sizing: border-box;
		.banner {
			width: 100%;
			height: 370rpx;
			margin-bottom: 30rpx;
			border-radius: 10rpx;
			overflow: hidden;
			.item {
				width: 100%;
				height: 100%;
				background-color: $imgBgColor;
				background-position: center;
				background-repeat: no-repeat;
				background-size: 100% 100%;
			}
		}
		.activity {
			width: 100%;
			border-radius: 8rpx;
			overflow: hidden;
			&Info {
				width: 100%;
				padding: 40rpx 46rpx 30rpx 46rpx;
				background-color: $white;
				box-sizing: border-box;
				position: relative;
				&_status {
					position: absolute;
					top: 0;
					right: 0;
					padding: 0 14rpx 0 24rpx;
					height: 55rpx;
					color: $white;
					font-size: 26rpx;
					border-bottom-left-radius: 55rpx;
					background-color: $color1;
					line-height: 55rpx;
					&.no {
						background-color: $imgBgColor !important;
					}
				}
				&_title {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin: 30rpx 0 44rpx 0;
					.icon {
						width: 44rpx;
						height: 44rpx;
						border-radius: 4rpx;
						background:$color1 url(../../static/imgs/icon/1.png) no-repeat center;
						background-size: 32rpx 30rpx;
						margin-right: 20rpx;
					}
					.title {
						flex: 1;
						color: #333333;
						font-size: 36rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}
				&_content {
					.item {
						display: flex;
						justify-content: space-between;
						align-items: flex-start;
						margin-bottom: 20rpx;
						&:nth-last-of-type(1) {
							margin-bottom: 0;
						}
						.circle {
							width: 12rpx;
							height: 12rpx;
							background-color: $color1;
							border-radius: 50%;
							margin: 10rpx;
						}
						.content {
							color: #333333;
							font-size: 26rpx;
							flex: 1;
							overflow: hidden;
							margin-left: 20rpx;
							line-height: 32rpx;
							font-weight: 500;
							.spec {
								color: $color1;
								font-size: 32rpx;
							}
						}
					}
				}
			}
			&Btn {
				width: 100%;
				height: 80rpx;
				background-color: $color1;
				color: $white;
				font-size: 36rpx;
				line-height: 80rpx;
				text-align: center;
				border-radius: 0 !important;
				&::after {
					display: none !important;
				}
			}
		}
		.bindTel {
			width: 600rpx;
			margin: 0 auto;
			border-radius: 10rpx;
			background-color: $white;
			&::before {
				content: "";
				display: block;
				width: 100%;
				height: 350rpx;
				background: url(https://api.jiuweiyun.cn/public/uploads/weapp/icon/tel_logon_bg.png) no-repeat center;
				background-size: 100%;
			}
			&C {
				width: 500rpx;
				margin: -156rpx auto 35rpx auto;
				background-color: $white;
				box-shadow: 0 0 10rpx 3rpx rgba(0,0,0,.2);
				padding: 25rpx 30rpx;
				box-sizing: border-box;
				border-radius: 10rpx;
				position: relative;
				&_avatar {
					width: 128rpx;
					height: 128rpx;
					border-radius: 50%;
					background-position: center;
					background-repeat: no-repeat;
					background-size: 100%;
					background-color: $imgBgColor;
					position: absolute;
					top: 0;
					left: 50%;
					transform: translate(-50%, -50%);
					box-shadow: 0 0 32rpx 9rpx rgba(250, 99, 66, 0.2);
					overflow: hidden;
				}
				&_form {
					margin: 117rpx 0 0 0;
					&_code, &_input {
						height: 70rpx;
						border-radius: 10rpx;
						background-color: #F2F4F5;
						padding: 0 24rpx;
						box-sizing: border-box;
					}
					&_input {
						margin-bottom: 40rpx;
						font-size: 28rpx;
					}
					&_code {
						display: flex;
						align-items: center;
						justify-content: space-between;
						margin-bottom: 45rpx;
						.send {
							width: 160rpx;
							height: 60rpx;
							border-radius: 60rpx;
							line-height: 60rpx;
							text-align: center;
							background-color: $color1;
							color: $white;
							font-size: 24rpx;
						}
						.code {
							flex: 1;
							font-size: 28rpx;
							margin-right: 24rpx;
						}
					}
					&_tip {
						color: #666666;
						font-size: 24rpx;
						text-align: center;
					}
				}
			}
			&_submit {
				height: 72rpx;
				line-height: 72rpx;
				text-align: center;
				border-radius: 72rpx;
				background-color: $color1;
				color: $white;
				font-size: 28rpx;
				margin: 0 30rpx 39rpx 30rpx;
			}
		}
	}
</style>
