<template>
	<div class="wx-share-wrap">
		<section>
			<div class="invite-info">
				<img :src="avatarImageUrl" />
				<p class="title1">{{ name }}邀请您助力 为他赢大奖</p>
				<p class="title2">领取课程即可助他一臂之力</p>
			</div>

			<div class="page-info">
				<p class="title1">资深医生讲师、精选专业课程</p>
				<p class="title2">已有超过20,000+的医生领取以下课程</p>
				<div class="imgs-wrap">
					<div>
						<img src="../assets/img/ico1.png" />
						<div class="img-txt">高血压课程</div>
					</div>
					<div>
						<img src="../assets/img/ico2.png" />
						<div class="img-txt">糖尿病课程</div>
					</div>
					<div>
						<img src="../assets/img/ico3.png" />
						<div class="img-txt">中医课程</div>
					</div>
					<div>
						<img src="../assets/img/ico4.png" />
						<div class="img-txt">全科课程</div>
					</div>
				</div>
			</div>

			<div class="form-info">
				<div class="field-wrap">
					<label>联系方式</label>
					<input v-model="mobilePhone" type="tel" maxlength="11" placeholder="请输入手机号">
				</div>
				<div class="field-wrap">
					<label>图形验证码</label>
					<input v-model="captchaAnswer" type="text" maxlength="6" placeholder="请输入">
					<div class="cap-box"><img :src="captchaImg" @click="getCaptcha"></div>
				</div>
				<div class="field-wrap">
					<label>短信验证码</label>
					<input v-model="authCode" type="tel" maxlength="6" placeholder="请输入">
					<button v-if="notSend" @click="sendSms">{{btnMsg}}</button>
					<van-count-down v-if="!notSend" :time="time" @finish="finishCount" :format="'ss' + 's'" />
				</div>
				<button class="btn-post" @click="getCourse">领取课程</button>
			</div>
		</section>
	</div>
</template>

<script>
	import { getInviteInfo, getCourseById, getCaptchaGet, getAuthCode } from '@/service';
	const TIMEALL = 60000; // 倒计时常量 60 秒
	export default {
		data(){
			return {
				notSend: true,
				regMobile: /^1[3456789]\d{9}$/,
				mobilePhone: '',
				authCode: '', // 短信验证码
				flag: 0,
				captchaImg: '', // 图形验证码图片字段
				captchaToken: '', // captchaToken
				captchaAnswer: '', // 输入的图形验证码
				time: TIMEALL,
				btnMsg: '点击获取',
				isReq: false
			}
		},
		async asyncData({ query }){
			const { id, taskId, activityId } = query;
			let avatarImageUrl = '', name = '', captchaImg = '', captchaToken = '';
			const res = await getInviteInfo(id);
			if(res.code === '000000'){
				const data = res.data;
				avatarImageUrl = data.avatarImageUrl;
				name = data.name ? data.name : data.mobilePhone;
			}
			const resCapt = await getCaptchaGet();
			if(resCapt.code === '000000'){
        captchaImg = `data:image/png;base64,${resCapt.data.content}`;
        captchaToken = resCapt.data.token;
    	}
    	return { 
    		avatarImageUrl, name, id, taskId, activityId, captchaImg, captchaToken
    	}
		},
		mounted(){
  		document.querySelector('body').setAttribute('style', 'background: #FE9A51;');
  		this.checkCache();
		},
		methods: {
			// 校验用户浏览器是否有登录缓存，此缓存为纯前端缓存，与token之类的无关
			checkCache(){
				const mobilePhoneCache = window.localStorage.getItem('mobilePhone');
	  		const statusCache = window.localStorage.getItem('status');
	  		const status = 'false';
	  		// 如果有缓存则是第二次进入，就要显示已领取，也就是false
	  		if(mobilePhoneCache && statusCache){
	  			window.localStorage.setItem('status', status);
	  			this.$router.push({
	          name: 'shareResult',
	          query: {
	            status
	          }
	        })
	  		}
	  		// 如果没有缓存，则停留当前页面
			},
			// 点击刷新验证码
			getCaptcha(){
				getCaptchaGet().then(res=>{
					if(res.code === '000000'){
	          this.captchaImg = `data:image/png;base64,${res.data.content}`;
	          this.captchaToken = res.data.token;
        	}else{
        		this.$toast(res.message);
        	}
				})
			},
			// 领取课程事件
			getCourse(){
				if(this.isReq){
					this.$toast('您的登录操作过于频繁，请稍后再试');
					return;
				}
				const { regMobile, mobilePhone, authCode, id, taskId, activityId } = this;
				const mobileTrue = regMobile.test(mobilePhone);

				if(!mobileTrue){
	        this.$toast('请输入正确的手机号');
	        return;
	      }
	      // 校验图形验证码
				if(this.captchaAnswer==''){
	        this.$toast('请输入图形验证码');
	        return;
	      }
				if(this.authCode==''){
	        this.$toast('请输入短信验证码');
	        return;
	      }
	      
	      this.isReq = true;
	      // 调用领取课程接口
				getCourseById({
					mobile: mobilePhone, 
					authCode, 
					id, 
					taskId, 
					activityId
				}).then(res=>{
					this.isReq = false;
					// res.data true 登记成功 、 false 登记失败
					if(res.code === '000000'){
						// 将手机号和状态存入浏览器缓存，用户再次进来就能直接进入领取结果页面
						// 注意，如果清除微信或者浏览器缓存，则将停留在当前这个页面并且再次填写手机号以做登录
						window.localStorage.setItem('mobilePhone', mobilePhone);
						window.localStorage.setItem('status', res.data);
						this.$router.push({
		          name: 'shareResult',
		          query: {
		            status: res.data
		          }
		        })
					}else {
						this.$toast(res.message);
					}
				})
			},
			// 发送获取短信验证码
			sendSms(){
				const { regMobile, mobilePhone, flag, captchaToken, captchaAnswer } = this;
				const mobileTrue = regMobile.test(mobilePhone);
				if(!mobileTrue){
	        this.$toast('请输入正确的手机号');
	        return;
	      }
				// 校验图形验证码
				if(this.captchaAnswer==''){
	        this.$toast('请输入图形验证码');
	        return;
	      }

	      getAuthCode({mobilePhone, flag, captchaToken, captchaAnswer}).then(res=>{
	      	// 发送成功
	      	if(res.code === '000000'){
	      		this.notSend = false;
	      	}else{
	      		this.$toast(res.message);
	      		this.getCaptcha();
	      	}
	      })

			},
			// 倒计时结束
			finishCount(){
				this.time = TIMEALL;
				this.notSend = true;
				this.btnMsg = '重新获取';
			}
		}
	}
</script>

<style lang="less" scoped>
@import '../assets/style/index.less';
</style>
<style lang="less">
@import '../assets/style/revant.less';
</style>
