<template>
	<view class="invite-proxy">
		<custom-nav noback="noback" transparent="transparent" ref="ltm" title=" " />
		<view class="content">
			<view v-if="!logged" class="app-item item">
				<text>邀请人</text>
				<text>{{ recom_nickname }}</text>
			</view>
			<view v-if="!logged" class="app-item item">
				<text>邀请码</text>
				<text>{{ invite_code }}</text>
			</view>
			<view v-if="!logged" class="app-item item">
				<text>联系方式</text>
				<text>{{ recom_mobile }}</text>
			</view>
			
			<view v-if="!logged" class="form">
				<navigator url="../phone-area/phone-area" class="phone-area">
					<text class="text">国家/地区</text>
					<text class="area">{{ areaName }}（{{ areaCode == '86' ? '+' : '' }}{{ areaCode }}）</text>
					<text class="icon cuIcon-right"></text>
				</navigator>
				<view class="item">
					<text class="icon cuIcon-mobilefill"></text>
					<input maxlength="11" type="number" v-model="phone" placeholder="请输入手机号" />
					<text v-if="phone" class="cuIcon-roundclosefill" @tap="clearPhone"></text>
				</view>
				<view class="item">
					<text  class="icon cuIcon-markfill"></text>
					<input maxlength="6" type="number" v-model="verifycode" placeholder="请输入6位验证码" />
					<text v-if="verifycode" class="cuIcon-roundclosefill" @tap="clearVerify"></text>
					<view class="countdown" @tap="getCode">
						发送验证码 <text v-if="countDown">{{ ' ' + countDown }}</text>
					</view>
				</view>
			</view>
			
			<view v-if="!logged" class="app-item item item-space">
				<text>微信昵称</text>
				<input v-model="wx_nickname" placeholder="请填写微信昵称" />
			</view>
			<view v-if="!logged" class="app-item item">
				<text>真实姓名</text>
				<input v-model="real_name" maxlength="32" placeholder="请填写真实姓名" />
			</view>
			<view v-if="!logged" class="app-item item">
				<text>身份证号</text>
				<input type="text" @input="inputChange" v-model="id_card_num" maxlength="18" placeholder="请填写身份证号" />
			</view>
			
			<button v-if="isREG && !logged" class="big-btn bg" @tap="submit">立即加入</button>
			<view id="erweima" style="display: none;"></view>
			<image style="width: 0; height: 0;" src="../../static/avatar.jpg"></image>
			<view id="imgWrapper">
				<image class="showCan" v-if="src" :src="src" ></image>
			</view>
			<view v-if="logged" class="basecolor sharetext">{{ src ? '长按二维码发送给代理即可邀请加入' : '' }}</view>
		</view>
	</view>
</template>

<script>
	import { _API_GetVerifyCode, _API_Reg, _API_Login, _API_LoginWX, _API_GzhWebInit } from '@/apis/verify.js'
	import { _API_SubAuthInfo } from '@/apis/user.js'
	export default {
		data() {
			return {
				title: '欢迎加入大卫博士',
				recom_nickname: '',
				recom_mobile: '',
				invite_code: '',
				wx_nickname: '',
				real_name: '',
				id_card_num: '',
				areaName: '中国大陆', // 手机号地区名称
				areaCode: '86', // 手机号地区代码
				phone: '', // 手机号
				verifycode: '', // 验证码
				countDown: 0, // 倒计时
				isREG: true,
				src: ''
			};
		},
		computed: {
			logged() { return this.$store.state.app.token }
		},
		created() {
			uni.showLoading({ mask: true })
			uni.$on('CHOOSEPHONECODE', (name, code) => { // 监听 chooseArea 事件更新
				this.areaName = name // 修改选择的手机号地区名称
				this.areaCode = code // 修改选择的手机号地区代码
			})
			if (this.$store.state.app.token) {
				const script = document.createElement('script')
				script.type = 'text/javascript'
				script.src = 'http://res.wx.qq.com/open/js/jweixin-1.4.0.js'
				document.getElementsByTagName('head')[0].appendChild(script)
				script.onload = () => {
					_API_GzhWebInit().then(res => {
						window.history.replaceState({}, '', res.url.split('.cn')[1])
						setTimeout(() => {
							const img = document.getElementsByTagName('img')[0]
							$('#erweima').qrcode({ width: 333, height: 333, text: res.url })
							document.getElementsByTagName('canvas')[0].getContext('2d').drawImage(img, 123, 123, 80, 80)
							wx.config(res)
							wx.ready(() => {
								wx.updateAppMessageShareData({
									title: `我是${this.$store.state.userinfo.nickname}, 邀请你加入大卫博士`,
									desc: '传递健康，改变命运。',
									link: res.url,
									imgUrl: 'http://api.app.jiuweiyun.cn/public/uploads/logo.jpg'
								})
							})
							wx.error(res => window.history.replaceState({}, '', `/api/gzh/david`))
							uni.hideLoading()
							const can = document.createElement('canvas')
							const pixelRatio = window.devicePixelRatio || 1;
							const ctx = can.getContext('2d')
							const backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
							    ctx.mozBackingStorePixelRatio ||
							    ctx.msBackingStorePixelRatio ||
							    ctx.oBackingStorePixelRatio ||
							    ctx.backingStorePixelRatio || 1;
							const ratio = pixelRatio / backingStoreRatio;
							can.width = uni.upx2px(680) * ratio
							can.height = uni.upx2px(960) * ratio
							can.style.width = uni.upx2px(680) + 'px'
							can.style.height = uni.upx2px(960) + 'px'
							ctx.scale(ratio, ratio);
							
							ctx.fillStyle="#ffffff";
							ctx.fillRect(0, 0, uni.upx2px(680), uni.upx2px(960));
							ctx.fillStyle="#000000";
							ctx.font=`${uni.upx2px(42)}px Arial`;
							ctx.textAlign="center";
							
							ctx.drawImage(img, uni.upx2px(276), uni.upx2px(16), uni.upx2px(128), uni.upx2px(128))
												
							ctx.fillText(`“${this.recom_nickname.length > 18 ? this.recom_nickname.slice(0, 18) + '...' : this.recom_nickname }”`, uni.upx2px(340), uni.upx2px(206))
							
							ctx.fillStyle="#333333";
							ctx.font=`${uni.upx2px(36)}px Arial`;
							ctx.fillText(`邀请你加入大卫博士`, uni.upx2px(340), uni.upx2px(271))
							
							ctx.drawImage(document.getElementsByTagName('canvas')[0], uni.upx2px(80), uni.upx2px(332), uni.upx2px(517), uni.upx2px(518))
							
							ctx.font=`${uni.upx2px(36)}px Arial`;
							ctx.fillStyle="#F76454";
							ctx.fillText(`长按-识别二维码-填写信息`, uni.upx2px(340), uni.upx2px(910))
							this.src = can.toDataURL("image/png")
						}, 567)
					})
				}
			} else {
				uni.hideLoading()
			}
		},
		onLoad({ nickname, mobile, invite_code }) {
			this.recom_nickname = decodeURIComponent(nickname)
			this.recom_mobile = mobile
			this.invite_code = invite_code
			if (!this.recom_nickname || !this.recom_mobile || !this.invite_code) {
				uni.showToast({ title: '用户信息获取失败，请重新登陆' })
				uni.navigateBack()
			}
		},
		methods: {
			inputChange() {
				this.id_card_num = this.id_card_num.trim()
			},
			getCode() { // 点击获取手机验证码
				if (this.phone.length) { // 手机号是否输入
					if (this.countDown) { // 如果正在倒计时
						uni.toast('验证码已发送,请稍后重试')
					} else {
						uni.showLoading({ mask: true }) // 显示 loading
						_API_GetVerifyCode({ mobile: this.phone, code: this.areaCode, type: 'invite' }).then(res => {
							if (res.code == 200) {
								if (res.data.status == 0) { // 登录 // 0、 1 代表用户是登录 或 注册
									this.isREG = false // 隐藏提交
									uni.toast('该手机号已注册！请直接登陆！') // 提示邀请码发送成功
								} else {
									this.isREG = true // 显示提交
									uni.toast('验证码发送成功') // 提示邀请码发送成功
									this.countDown = 120 // 倒计时时长
									this.timer = setInterval(() => { // 开始倒计时
										this.countDown --
										if (this.countDown <= 0) { // 倒计时结束清除倒计时
											this.countDown = 0
											clearInterval(this.timer)
										}
									}, 1000)
								}
							} else if (res.code == 900) {
								this.isREG = false // 隐藏提交
								uni.toast('该手机号已注册！请直接登陆！') // 提示邀请码发送成功
							} else { // code 300 表示禁止获取验证码，禁止登陆
								uni.toast('获取验证码失败')
							}
						})
					}
				} else {
					uni.toast('手机号格式不正确，请重新输入')
				}
			},
			submit() { // 点击登录/注册
				if (!this.phone.length) { uni.toast('手机号格式不正确，请重新输入'); return }
				if (!(this.verifycode.length == 6)) { uni.toast('验证码格式不正确，请重新输入'); return }
				if (!this.wx_nickname.length) {
					uni.toast('微信昵称不能为空')
					return
				}
				if (!this.real_name.match(/^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/)) {
					uni.toast('真实姓名不符合要求')
					return
				}
				if (!this.id_card_num.match(/^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/)) {
					uni.toast('身份号码不合法')
					return
				}
				uni.showLoading({ mask: true }) // 显示 loading
				if (!this.requesting) {
					this.requesting = true
					setTimeout(() => this.requesting = false, 567)
					_API_Reg({
						mobile: this.phone,
						verify_code: this.verifycode,
						recom_code: this.invite_code,
						code: this.areaCode
					}).then(res => {
						uni.showLoading({ mask: true }) // 显示 loading
						if (res.code == 200) { // 注册成功
							this.$store.commit('app/LOGIN', res.data.token) // 保存 token
							_API_SubAuthInfo({ // 提交信息
								wechatname: this.wx_nickname,
								realname: this.real_name,
								cre_num: this.id_card_num
							}).then(res => {
								if (res.code === 200) { // 提交成功
									this.$store.commit('userinfo/UPDATA_USERINFO', { cert_status: 1 })
									uni.redirectTo({ url:'../auth-progress/auth-progress' }) // redirect 到 审核进度页面
								} else if (res.code === 300) {
									uni.showToast({ title: res.message })
								}
							})
						} else if (res.code == 300) { // 验证码不正确
							uni.toast('验证码错误')
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.invite-proxy {
		@include page();
		.content {
			#imgWrapper {
				flex: 1;
				@include flex();
				.showCan {
					width: 680rpx;
					height: 960rpx;
					border-radius: 14rpx;
					box-shadow:0px 0px 23px 2px rgba(194,133,58,0.5);
				}
			}
			.sharetext {
				font-size: 88rpx;
				text-align: center;
				margin: 8rpx 0;
				box-sizing: border-box;
				padding: 0 24rpx;
			}
			.form {
				padding: 30rpx;
				margin-top: 10rpx;
				box-sizing: border-box;
				background-color: #FFFFFF;
				.phone-area {
					@include flex();
					justify-content: space-between;
					.text {
						font-size: 32rpx;
					}
					.area {
						color: #42b983;
					}
					
				}
				.item {
					@include flex();
					height: 110rpx;
					padding-top: 20rpx;
					box-sizing: border-box;
					color: $app-sec-text-color;
					border-bottom: 1rpx solid #B2B2B2;
					.icon, .cuIcon-roundclosefill {
						margin: 0 20rpx;
						font-size: 36rpx;
					}
					input {
						flex: 1;
						height: 84rpx;
						margin-left: 15rpx;
					}
					.countdown {
						@include flex();
						height: 50rpx;
						font-size: 24rpx;
						padding: 0 20rpx;
						background: #FFEFF0;
						margin-right: 20rpx;
						border-radius: 33rpx;
						color: $app-base-color;
						text {
							margin-left: 8rpx;
						}
					}
				}
			}
		}
	}
</style>
