<template>
	<view class="register_box">
		<template v-if="isRegister==0">
			<image src="https://cdn.his.cdwjyyh.com/minapp/kc_hb_bg1.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>
		<u-popup :show="userlogo" mode="bottom" round='12'>
			<view class="userlogo column">
				<view class="mtb30 justify-start align-center ml20">
					<u-avatar src="/static/logo.png" size="50"></u-avatar>
					<view class="bold mlr20">丝路佳选</view>
					<view>申请</view>
				</view>
				<view class="bold fs36 ml20">授权你的昵称头像信息</view>
				<view class="mtb20 justify-between align-center  plr20">
					<view class="justify-start align-center">
						<view class="boxweixin" :class="userinfos.nickname==''?'boxnosel':'boxsel'">
							<view v-if="userinfos.nickname">
								<u-icon name="checkbox-mark" color="#00aa00" size="22"></u-icon>
							</view>
						</view>
						<view class="ml20">
							<view class="base-color-3 bold">第一步</view>
							<view class="fs32 base-color-9">请点击授权微信昵称</view>
						</view>
					</view>
					<view class="button-container">
					   <input 
					     type="nickname"
					     class="hidden-input"
						 @blur="onNickNameInput"
						 @input="onNickNameInput"
					   />
					   <button class="custom-button" :class="nameuser==''?'subname':'subavt'">{{nameuser?"已授权":'允许授权'}}</button>
					 </view>
				</view>
				<!-- <view class="mtb20 justify-between align-center  plr20 mt40">
					<view class="justify-start align-center">
						<view class="boxweixin" :class="userinfos.nickname==''?'boxnosel':'boxsel'">
							<view v-if="userinfos.avatar">√</view>
						</view>
						<view class="ml20">
							<view class="base-color-3 bold">第二步</view>
							<view class="fs32 base-color-9">请点击授权微信头像</view>
						</view>
					</view>
					<view class="button-container">
					  <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="hidden-input" 
					  v-if="nameuser">
					    允许授权
					  </button>
					  <button class="custom-button sub" @click="shouquan" v-if="nameuser==''">允许授权</button>
					   <button class="custom-button "  :class="avataruser==''?'subname':'subavt'"
					   v-else>{{avataruser?"已授权":'允许授权'}}</button>
					 </view>
				</view> -->
				<view class="submitname" @click="confimrname" :class="nameuser&&avataruser?'subact':'sub'">确定</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex';
	import {getRealLink,handleFsUserWx,isAddCompanyUser,loginByMp,editUser} from "@/api/course.js"
	export default {
		data() {
			return {
				isLogin: false,
				isRegister: 0,
				isLoading: false,
				urlOption: {},
				sortLink: '',
				isLoginH5:0, // 1服务号授权
				userlogo:false,
				imgname:'',
				userinfos:{
					nickname:"",
					avatar:""
				},
				chatId:''
			}
		},
		computed:{
			...mapGetters(['coureLogin']),
			nameuser() {
				return this.userinfos.nickname
			},
			avataruser() {
				return this.userinfos.avatar
			},
		},
		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
					if(this.isLoginH5==0){
						this.goWXLogin()
					}else{
						this.goLogin()
					}
		        }
		      }
		    }
		},
		onLoad(option) {
			this.urlOption = option.link ? JSON.parse(decodeURIComponent(option.link)) : {},
			this.sortLink = this.urlOption.link || ''
			this.chatId = this.urlOption.chatId
			console.log(this.sortLink)
			uni.$on('usercode',(data)=>{
				if(data) {
					this.goLogin(data)
				}
			})
		},
		beforeDestroy() {
			uni.$off('usercode')
		},
		onUnload() {
			uni.$off('usercode')
		},
		methods: {
			//修改用户昵称以及头像
			editUserA(){
				this.userinfos=uni.getStorageSync('web_userInfo')?uni.getStorageSync('web_userInfo'):this.userinfos
				const data={
					nickName:this.userinfos.nickname,
					// avatar:this.userinfos.avatar,
				}
				editUser(data).then(res=>{
					if(res.code==200){
						this.isLogin = true
						uni.showToast({
							icon:'none',
							title:'修改成功！',
						});
						setTimeout(()=>{
							// this.getIsAddKf()
							this.getAddCompanyUser()
						},100)
					}else{
						uni.removeStorageSync('web_userInfo')
						uni.showToast({
							icon:'none',
							title:res.msg+'请重新点击立即学习',
						});
					}
				})
			},
			shouquan(){
				if(this.userinfos.nickname==''){
					uni.showToast({
						icon:'none',
						title: "请先授权微信昵称",
					});
				}
			},
			confimrname(){
				if(this.userinfos.nickname==''){
					uni.showToast({
						icon:'none',
						title: "请授权微信昵称",
					});
					return
				}
				// if(this.userinfos.avatar==''){
				// 	uni.showToast({
				// 		icon:'none',
				// 		title: "请授权微信头像",
				// 	});
				// 	return
				// }
				uni.setStorageSync('web_userInfo',this.userinfos)
				this.editUserA()
				this.userlogo=false
			},
			onNickNameInput(e){
				console.log(e)
				this.userinfos.nickname=e.detail.value
			},
			onChooseAvatar(e){
				this.userinfos.avatar=e.detail.avatarUrl
				uni.uploadFile({
					url: 'https://h5api.his.cdwjyyh.com'+'/app/common/uploadOSS', //仅为示例，非真实的接口地址
					filePath: e.detail.avatarUrl,
					name: 'file',
					formData: {
						'user': 'test'  // 上传附带参数
					},
					success: (uploadFileRes) => {
						console.log(uploadFileRes)
						// 根据接口具体返回格式   赋值具体对应url
						var data=JSON.parse(uploadFileRes.data)
						this.headImg=uni.getStorageSync('requestPath')+data.fileName
						this.userinfos.avatar=data.url
					}
				});
			},
			getLink() {
				if(!this.sortLink){
					uni.showToast({
						title: '链接错误',
						icon: 'none'
					});
					return
				}
				let that = this;
				if(this.isLoginH5==0) {
					this.utils.isLoginCourse().then(
						isLogin => {
							this.isLogin = isLogin
							if(this.isLogin) {
								// this.editUserA()
								if(this.chatId!=''||this.chatId){
									this.userlogo=true
								}else{
									this.getAddCompanyUser(1)
								}
							} else {
								this.goLogin()
							}
						},
						rej => {}
					);
				}else {
					this.utils.isLoginResCourse().then(
						isLogin => {
							this.isLogin = isLogin
							if(this.isLogin) {
								this.getAddCompanyUser(1)
							} else {
								this.goLogin()
							}
						},
						rej => {}
					);
				}
				// uni.showLoading({
				// 	title: '报名中'
				// })
				// getRealLink({sortLink:this.sortLink}).then(res=>{
				// 	uni.hideLoading()
				// 	if(res.code == 200) {
				// 		let linkurl=JSON.parse(res.realLink.split('?link=')[1]) 
				// 		this.chatId=linkurl.chatId
				// 		console.log(this.chatId)
				// 		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.editUserA()
				// 							if(this.chatId!=''||this.chatId){
				// 								this.userlogo=true
				// 							}else{
				// 								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(type) {
				if(type==1) {
					uni.showLoading({
						title: '报名中'
					})
				}
				isAddCompanyUser(this.urlOption).then(res=>{
					uni.hideLoading()
					if(res.code==200) {
						this.isRegister = 1
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				}).catch(()=>{
					uni.hideLoading()
				})
			},
			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.showLoading({
										title: '报名中...'
								    });
									loginByMp({code: loginRes.code,encryptedData:infoRes.encryptedData,iv:infoRes.iv,appId:getApp().globalData.appId}).then(res=>{
										 uni.hideLoading();
										 if (res.code == 200) {
											 // this.checkUserInfoA()
											this.$store.commit('setCoureLogin', 1);
											uni.setStorageSync('AppTokenmini_RTCourse', res.token);
											uni.setStorageSync('auto_userInfo', JSON.stringify(res.user));
											this.isLogin = true
											if(this.chatId!=''||this.chatId){
												this.userlogo=true
											}else{
												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">
	.subname{
		background-color: #00aa00;
		color: #fff;
	}
	.subavt{
		background-color: #fff;
		border: 2rpx #0a0 solid;
		color: #00aa00;
	}
	.boxweixin{
		width: 44rpx;
		height: 44rpx;
		border-radius: 50%;
		text-align: center;
		line-height: 34rpx;
		color: #0a0;
	}
	.boxnosel{
		border: #757575 4rpx solid;
	}
	.boxsel{
		border: #0a0 4rpx solid;
	}
	.button-container {
	  position: relative;
	  width: 240rpx;
	}
	.hidden-input {
	  position: absolute;
	  top: 0;
	  left: 0;
	  width: 100%;
	  height: 100%;
	  opacity: 0;
	  z-index: 2;
	}
	.custom-button {
	  position: relative;
	  z-index: 1;
	  /* 其他样式 */
	  width:100%;
	  margin: 0 auto;
	  height: 80rpx;
	  line-height: 60rpx;
	  font-size: 28rpx;
	  padding: 10rpx 20rpx;
	}
	.submitname{
		width: 90%;
		
		margin: 0 auto;
		text-align: center;
		padding: 30rpx;
		margin-top: 40rpx;
	}
	.sub{
		background-color: #f0f0f0;
		color: #0a0;
	}
	.subact{
		background-color: #0a0;
		color: #fff;
	}
	.userlogo{
		height: 760rpx;
	}
	.timepopbox{
		width: 560rpx;
		padding: 32rpx;
		box-sizing: border-box;
	}
	.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>