<template>
	<view class="register_box">
		<template v-if="isRegister==0">
			<image src="https://cdn.his.cdwjyyh.com/minapp/kc_hb_bg.png" class="imgbg" mode="widthFix"></image>
			<view class="kc_footer">
				<image src="https://cdn.his.cdwjyyh.com/minapp/kc_footer_bg.png" class="imgft" mode="widthFix"></image>
				<view class="kc_footer_btn" @click="getLink">{{isRegister==1?'注册成功':'立即注册'}}</view>
			</view>
		</template>
		<view v-else class="success_box">
			<image src="https://cdn.his.cdwjyyh.com/minapp/course_register_img.png" mode="heightFix"></image>
			<view>注册成功</view>
		</view>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex';
	import {getRealLink,handleFsUserWx,isAddCompanyUser,loginByMp} from "@/api/course.js"
	export default {
		data() {
			return {
				isLogin: false,
				isRegister: 0,
				isLoading: false,
				urlOption: {},
				sortLink: '',
				isLoginH5: 0, // 1服务号授权
			}
		},
		computed:{
			...mapGetters(['coureLogin']),
		},
		watch: {
		    coureLogin: {
		      immediate: true,          // 页面一进入就检查一次
		      handler(val) {
		        if (val == 2&&this.isLogin) {
					console.log("注册AppToken失效，请重新登录")
					uni.removeStorageSync('web_userInfo');
					uni.removeStorageSync('TOKEN_WEXIN');
					this.isLogin = false
					this.goLogin()
		        }
		      }
		    }
		},
		onLoad(option) {
			this.urlOption = option.link ? JSON.parse(decodeURIComponent(option.link)) : {}
			this.sortLink = this.urlOption.link || ''
			uni.$on('usercode',(data)=>{
				if(data) {
					this.goLogin(data)
				}
			})
		},
		beforeDestroy() {
			uni.$off('usercode')
		},
		onUnload() {
			uni.$off('usercode')
		},
		methods: {
			getLink() {
				if(!this.sortLink){
					uni.showToast({
						title: '链接错误',
						icon: 'none'
					});
					return
				}
				let that = this;
				uni.showLoading({
					title: '注册中'
				})
				getRealLink({sortLink:this.sortLink}).then(res=>{
					uni.hideLoading()
					if(res.code == 200) {
						if(res.config&&res.config.userCourseAuthDomain) {
							uni.setStorageSync('weixinOauth',res.config.userCourseAuthDomain)
							if(this.isLoginH5==0) {
								this.utils.isLoginCourse().then(
									isLogin => {
										this.isLogin = isLogin
										if(this.isLogin) {
											this.getAddCompanyUser()
										} else {
											this.goLogin()
										}
									},
									rej => {}
								);
							}else {
								this.utils.isLoginResCourse().then(
									isLogin => {
										this.isLogin = isLogin
										if(this.isLogin) {
											this.getAddCompanyUser()
										} else {
											this.goLogin()
										}
									},
									rej => {}
								);
							}
						}else {
							uni.showToast({
								title: '授权地址错误',
								icon: 'none'
							});
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				}).catch(err=>{
					uni.hideLoading()
					uni.showToast({
						title: '发生错误，请稍后再试',
						icon: 'none'
					});
				})
			},
			goLogin(data) {
				if(this.isLoginH5==0) {
					this.goWXLogin()
					return
				}
				if(data) {
					this.utils.getProvider().then(provider=>{
						console.log('当前的环境商',provider)
						if (!provider) {
						  reject()
						}
						uni.login({
							provider: provider,
							success: loginRes => {
								console.log(loginRes)
								uni.getUserInfo({
								   provider: provider,
								   success: (infoRes)=> {
										const param = {
											code: loginRes.code, // 必填参数，不能为空，code参数缺失时会报错
											appId: getApp().globalData.appId, // 应用ID
											userId: data.userId // 用户id
										}
										uni.showLoading({
											title: '注册中'
										})
										handleFsUserWx(param).then(res=>{
											uni.hideLoading()
											if(res.code==200) {
												this.getAddCompanyUser()
											} else {
												uni.removeStorageSync('web_userInfo');
												uni.removeStorageSync('TOKEN_WEXIN');
												uni.showToast({
													title: res.msg,
													icon: 'none'
												});
											}
										}).catch(err=>{
											uni.hideLoading()
										})
								   }
								});
							}
						})
					})
				} else {
					uni.setStorageSync('H5course',{
						companyId: this.urlOption.companyId,
						companyUserId:this.urlOption.companyUserId,
					})
					uni.navigateTo({
						url:'/pages_course/webview'
					})
				}
			},
			getAddCompanyUser() {
				isAddCompanyUser(this.urlOption).then(res=>{
					if(res.code==200) {
						this.isRegister = 1
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				})
			},
			goWXLogin() {
				this.utils.getProvider().then(provider=>{
					console.log('当前的环境商',provider)
					if (!provider) {
					  reject()
					}
					uni.login({
						provider: provider,
						success: async loginRes => {
							console.log(loginRes)
							uni.getUserInfo({
							   provider: provider,
							   success: (infoRes)=> {
								    uni.showToast({
										title: '注册中...',
										icon: 'loading'
								    });
									loginByMp({code: loginRes.code,encryptedData:infoRes.encryptedData,iv:infoRes.iv,appId:getApp().globalData.appId}).then(res=>{
										 uni.hideLoading();
										 if (res.code == 200) {
											this.$store.commit('setCoureLogin', 1);
											uni.setStorageSync('AppTokenmini_RTCourse', res.token);
											uni.setStorageSync('auto_userInfo', JSON.stringify(res.user));
											this.isLogin = true
											this.getAddCompanyUser()
										 } else {
											uni.showToast({
												title: res.msg,
												icon: 'none'
											});
										 }
									 }).catch(err=>{
										uni.hideLoading();
										uni.showToast({
											icon:'none',
											title: "登录失败,请重新登录",
										});
									});
							   }
							});
						}
					})
				}).catch(err => {})
			}
		}
	}
</script>

<style>
	page {
		background-color: #fff;
	}
</style>
<style scoped lang="scss">
	.register_box {
		position: relative;
		min-height: 100vh;
	}
	@keyframes scaleAnimation {
	  0% {
	    transform: translate(-50%, -50%) scale(1);
	  }
	  50% {
	    transform: translate(-50%, -50%) scale(1.05);
	  }
	  100% {
	    transform: translate(-50%, -50%) scale(1);
	  }
	}
	.success_box {
		height: 100vh;
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 64rpx;
		color: #222222;
		image {
			width: 404rpx;
			height: 404rpx;
			margin-bottom: 26rpx;
		}
	}
	.imgbg {
		width: 100%;
	}

	.kc_footer {
		width: 100%;
		position: absolute;
		bottom: 0;
		left: 0;

		&_btn {
			width: 528rpx;
			height: 96rpx;
			background: #FF5C03;
			border-radius: 48rpx 48rpx 48rpx 48rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
			display: flex;
			align-items: center;
			justify-content: center;
			position: absolute;
			bottom: 20%;
			left: 50%;
			transform: translate(-50%, -50%) scale(1);
			// will-change: transform;
			// animation: scaleAnimation 1s ease infinite;
		}
	}

	.imgft {
		width: 100%;
	}
</style>