<template>
	<view class="content hb column justify-center align-center bgf">
		<image :src="imgPath+'/app/image/becomevip.png'" mode="widthFix"></image>
		<view class="justify-start align-center fs24 base-color-9" v-if="userInfo.userId">
			<view>{{nameuser}}#</view>
			<view>{{userInfo.userId}}</view>
		</view>
		<view class="bolds">成为会员，享受更多权益</view>
		<!--#ifdef H5-->
		<view class="sure" @click="registerCourse">{{isVip==1?'您已成为会员':viptext}}</view>
		<!--#endif-->
		<!--#ifdef MP-WEIXIN-->
		
		<view class="base-bg-orange colorf ptb20 plr40 radius60" 
		v-if="(userInfos==null||userInfos=='')&&imgname=='乐氏本源'" @click="nato()">授权用户信息</view>
		<view class="btns" v-else>
			<!-- <button
				class="author-btn"
				open-type="getUserInfo"
				:disabled="userdisabled"
				@getuserinfo="userInfologin"  v-if="authType==0">{{isVip==1?'您已成为会员':'申请成为会员'}}</button>
			<button
				v-else
				class="author-btn"
				open-type="getPhoneNumber"
				@getphonenumber="phoneLogin"  >{{isVip==1?'您已成为会员':'申请成为会员'}}</button> -->
			<button class="author-btn"  @click="handleAgree()">{{viptext}}</button>
		</view>
		
		<!--#endif-->
		<!--#ifdef MP-WEIXIN-->
		<u-popup :show="userlogo" mode="bottom" round='12'>
			<view class="userlogo column">
				<view class="mtb30 justify-start align-center ml20">
					<u-avatar :src="imgPath+'/app/image/logo.jpg'" size="50"></u-avatar>
					<view class="bold mlr20">{{imgname}}</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">√</view>
						</view>
						<view class="ml20">
							<view class="base-color-3 bold">第一步</view>
							<view class="fs24 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="fs24 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>
		<!--#endif-->
		<!-- <view class="footer-tips">重庆云联融智提供技术支持</view> -->
	</view>
</template>

<script>
	import { loginByMp,registerCourses,loginByMiniApp,handleFsUserWx} from '@/api/courseLook'
	import {
		getConfigByKey
	} from "@/api/user.js"
	export default {
		data() {
			return {
				isVip: 0,
				isWechat: false,
				isLogin: false,
				companyid:'',
				companyUserId:'',
				userInfo:{},
				tagIds:[],
				isbecomevip:0,
				viptext:'申请成为会员',
				userlogo:false,
				userinfos:{
					nickname:'',
					avatar:""
				},
				headImg:'',
				authType:0,//0微信登录 1手机号登录
				userdisabled:false,
				projectId:'',
				H5course:{}
			}
		},
		computed: {
		    imgPath() {
		      return this.$store.state.imgpath
		    },
			imgname() {
			  return this.$store.state.logoname
			},
			appid() {
				return this.$store.state.appid
			},
			nameuser() {
				return this.userinfos.nickname
			},
			avataruser() {
				return this.userinfos.avatar
			},
		},
		onLoad(option) {
			uni.$on('usercode',(data)=>{
				console.log('huoqu ',data)
				this.goLogin(data)
			})
			uni.$on('vipMsg',(data)=>{
				console.log('vipMsg ',data)
				this.viptext=data
			})
			console.log(option)
			let path = 'https://userapp.moonxiang.com/prod-api'//存在文化
			uni.setStorageSync('requestPath',path)
			if(uni.getStorageSync('userInfo')&&uni.getStorageSync('userInfo')!='{}') {
				this.userInfo = uni.getStorageSync('userInfo')
			} else {
				this.userInfo = {}
			}
			// this.userInfo=JSON.parse(uni.getStorageSync('userInfo')) || {};
			//#ifdef MP-WEIXIN
			let obj=uni.getStorageSync('TOKEN_WEXIN');
			//#endif
			// #ifdef H5
			let obj=uni.getStorageSync('TOKEN_KEY');
			// #endif
			// let obj=uni.getStorageSync('AppToken');
			let becomeVip={}
			if(!option.becomeVip){
				const keys = decodeURIComponent(Object.keys(option)[0]);
				becomeVip=JSON.parse(keys.split('becomeVip=')[1])
				console.log(becomeVip)
			}else{
				becomeVip = option.becomeVip ? JSON.parse(decodeURIComponent(option.becomeVip)) : {}
			}
			this.isLogin = !!obj;
			this.companyid = becomeVip.companyId || ''
			this.companyUserId=becomeVip.companyUserId || 0
			this.projectId=becomeVip.projectId
			this.H5course.companyId=becomeVip.companyId
			this.H5course.companyUserId=becomeVip.companyUserId
			this.H5course.projectId=becomeVip.projectId
			uni.setStorageSync('H5course',this.H5course)
			console.log(this.H5course)
			//#ifdef MP-WEIXIN
			// if(this.$store.state.logoname!=='乐氏本源'&&!uni.getStorageSync('userInfos')){
			// 	this.userlogo=true
			// }
			if(!uni.getStorageSync('userInfos')&&this.$store.state.logoname=='乐氏本源'){
				uni.navigateTo({
					url:'/pages_course/webview'
				})
				return
			}
			//#endif
			if(becomeVip.tagids==null||becomeVip.tagids==''){
				this.tagIds=[]
			}else{
				this.tagIds=becomeVip.tagids 
				const arr =this.tagIds.split("，")
				  .map(item => parseInt(item.trim(), 10))
				  .filter(num => !isNaN(num)); // 过滤无效转换
				  this.tagIds =arr
				// console.log(this.tagIds); 
			}
			// this.isWechat = String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger"
			// this.code = option.code
				// #ifdef H5
				if(this.code&&!this.isLogin) {
					this.loginByMp()
				}
				// #endif
				
		},
		onShow() {
			this.getWebviewUrl()
			if(uni.getStorageSync('userInfo')&&uni.getStorageSync('userInfo')!='{}') {
				this.userInfo = uni.getStorageSync('userInfo')
			} else {
				this.userInfo = {}
			}
			//#ifdef MP-WEIXIN
			this.userinfos=uni.getStorageSync('userInfo')
			console.log(uni.getStorageSync('userinfos'))
			let obj=uni.getStorageSync('TOKEN_WEXIN');
			//#endif
			// #ifdef H5
			let obj=uni.getStorageSync('TOKEN_KEY');
			// #endif
			this.isLogin = !!obj;
			if(this.isLogin&&this.isVip!=1) {
				this.registerCourse()
			}
			
		},
		methods: {
			getWebviewUrl() {
				var data = {
					key: 'course.config'
				}
					getConfigByKey(data).then(res => {
						if (res.code == 200) {
							console.log("getConfigByKey====", JSON.parse(res.data))
							let data = JSON.parse(res.data,)
							uni.setStorageSync('setWebviewUrl',data.userCourseAuthDomain)
						}else{
							uni.showToast({
								icon:'none',
								title: res.msg,
							});
						}
					})
			},
			goLogin(data) {
				console.log('huoqu111',data)
				if(data){
					console.log('huoqu1222',data)
					uni.showLoading({
						title: '加载中'
					})
					uni.login({
						provider: "weixin",
						success: async loginRes => {
							console.log(loginRes)
							let code = loginRes.code // 获取开发code
							handleFsUserWx({
							   code: code,
							   appId:this.appid,
							   userId:data.userId
							})
							.then( res => {
								if(res.code==200){
									console.log(res)
									uni.hideLoading();
									uni.showToast({
										icon:'none',
										title: "登录成功",
									});
									this.userinfos=uni.getStorageSync('userinfos')
									uni.getStorageSync('TOKEN_WEXIN');
									this.userInfo=uni.getStorageSync('userInfo');
									this.isLogin = true
									setTimeout(()=>{
										this.registerCourse()
									},200)
								}else if(res.code==406){
									uni.hideLoading();
									uni.showToast({
										icon:'none',
										title: '该用户已成为其他销售会员',
									});
								}else{
									uni.hideLoading();
									uni.showToast({
										icon:'none',
										title: res.msg,
									});
								}
							   
							 })
						},
					})
				}else{
					uni.navigateTo({
						url:'/pages_course/webview?H5course='+uni.getStorageSync('H5course')
					})
				}
				
			},
			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('userInfos',this.userinfos)
				this.editUserA()
				this.userlogo=false
			},
			onChooseAvatar(e){
				this.userinfos.avatar=e.detail.avatarUrl
				console.log(e.detail.avatarUrl)
				uni.uploadFile({
					url: uni.getStorageSync('requestPath')+'/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
					}
				});
			},
			onNickNameInput(e){
				console.log(e)
				this.userinfos.nickname=e.detail.value
			},
			nato(){
				uni.navigateTo({
					url:'/pages_course/webview'
				})
			},
			handleAgree(){
				console.log(144443)
				if(this.isVip==1){
					uni.showToast({
						title: '您已成为会员!',
						icon: 'none',
						duration: 2000,
					})
				}else{
					this.goLogin()
					uni.showToast({
						title: this.viptext,
						icon: 'none',
						duration: 2000,
					})
				}
				
			},
			userInfologin(e) {
				console.log(123333)
				this.userdisabled=true
				var that=this;
				uni.showLoading({
					title: "加载中..."
				});
				if (e.mp.detail.errMsg == 'getUserInfo:ok') {
					this.utils.getProvider()
					.then(provider => {
						if (!provider) {
							this.userdisabled=false
						  reject()
						}
						// uni登录
						uni.login({
							provider: provider,
							success: async loginRes => {
								let code = loginRes.code // 获取开发code
								this.userinfos=uni.getStorageSync('userInfos')?uni.getStorageSync('userInfos'):this.userinfos
								loginByMiniApp({
								   encryptedData: e.mp.detail.encryptedData,
								   iv: e.mp.detail.iv,
								   code: code,
								   nickname:this.userinfos.nickname?this.userinfos.nickname:'',
								   avatar:this.userinfos.avatar?this.userinfos.avatar:'',
								   companyId : this.companyid || '',
								   companyUserId:this.companyUserId || 0,
								   authType:this.authType,
								   appId:this.appid,
								   projectId:this.projectId
								})
								.then( res => {
									if(res.code==200){
										// console.log(res)
										uni.hideLoading();
										uni.showToast({
											icon:'none',
											title: "登录成功",
										});
										uni.setStorageSync('TOKEN_WEXIN', res.token);
										uni.setStorageSync('userInfo', JSON.stringify(res.user));
										this.userInfo=res.user;
										uni.hideLoading()
										this.userdisabled=false
										// this.isLogin = true
										setTimeout(()=>{
											this.checkUserInfoA()
											// this.registerCourse()
										},200)
									}else if(res.code==406){
										uni.hideLoading();
										uni.showToast({
											icon:'none',
											title: '该用户已成为其他销售会员',
										});
									}
									else{
										uni.hideLoading();
										uni.showToast({
											icon:'none',
											title: res.msg,
										});
									}
								   
								 })
								 .catch(res=>{
								 	 this.userdisabled=false
								 })
							},
							fail() {
								this.userdisabled=false
							}
						})
					})
					.catch(err => {
						this.userdisabled=false
						uni.showToast({
							icon:'none',
							title: err,
						});
					})
					 
				} else {
					this.userdisabled=false
					uni.showToast({
						title: '已拒绝授权',
						icon: 'none',
						duration: 2000,
					})
				}
			},
			// 微信用户手机号登录
			phoneLogin(e) {
				var that=this;
				uni.showLoading({
					title: "加载中..."
				});
				if (e.mp.detail.errMsg == 'getPhoneNumber:ok') {
					this.utils.getProvider()
					.then(provider => {
						if (!provider) {
						  reject()
						}
						// uni登录
						uni.login({
							provider: provider,
							success: async loginRes => {
								let code = loginRes.code // 获取开发code
								this.userinfos=uni.getStorageSync('userInfos')?uni.getStorageSync('userInfos'):this.userinfos
								loginByMiniApp({
								   encryptedData: e.mp.detail.encryptedData,
								   iv: e.mp.detail.iv,
								   code: code,
								   nickname:this.userinfos.nickname?this.userinfos.nickname:'',
								   avatar:this.userinfos.avatar?this.userinfos.avatar:'',
								   companyId : this.companyid || '',
								   companyUserId:this.companyUserId || 0,
								    authType:this.authType,
									appId:this.appid,
									projectId:this.projectId
								})
								.then( res => {
									if(res.code==200){
										// console.log(res)
										uni.hideLoading();
										uni.showToast({
											icon:'none',
											title: "登录成功",
										});
										uni.setStorageSync('TOKEN_WEXIN', res.token);
										uni.setStorageSync('userInfo', JSON.stringify(res.user));
										this.userInfo=res.user;
										uni.hideLoading()
										// this.isLogin = true
										// setTimeout(()=>{
										// 	this.registerCourse()
										// },200)
										setTimeout(()=>{
											this.checkUserInfoA()
											// this.registerCourse()
										},200)
									}else if(res.code==406){
										uni.hideLoading();
										uni.showToast({
											icon:'none',
											title: '该用户已成为其他销售会员',
										});
									}
									else{
										uni.hideLoading();
										uni.showToast({
											icon:'none',
											title: res.msg,
										});
									}
								   
								 })
							}
						})
					})
					.catch(err => {
						uni.showToast({
							icon:'none',
							title: err,
						});
					})
					 
				} else {
					uni.showToast({
						title: '已拒绝授权',
						icon: 'none',
						duration: 2000,
					})
				}
			},
			getWechatCode() {
				if (this.isWechat) {
					// let appid = "wx961fadab9bcb792b"; //微信APPid（福本源）
					// let appid = "wx93ce67750e3cfba3"; //微信APPid（云联融智）
					// let appid = "wxea1da2b708ab3c2f"; //微信APPid（蜂巢快药）
					// let appid = "wx3de90a39feb8107a"; //微信APPid（岚财良品看课）
					// let appid = "wxec49f9d783abf233"; //微信APPid（惠名大药房）
					// let appid = "wx5a0f7e1932e2689e"; //微信APPid（同顺堂）
					// let appid = "wxe0b82a0018449a62"; //微信APPid（良苗）
					// let appid = "wx568ea6b70350c585"; //微信APPid（倍力优）
					let appid = "wx0d021524695f1943"; //微信APPid（百年康城）
					// let appid = "wx090c5f399d65456e"; //微信APPid（青岛市德瑞康）
					// let appid = "wx52298c1781d5cc99"; //微信APPid（金慷建）
					let code = this.getUrlCode().code; //是否存在code
					let local = window.location.href;
					if (code == null || code === "") {

						let urlPaths = local.split("/registerCourse");
						uni.setStorageSync('beforLoginPage', urlPaths[1]);

						//不存在就打开上面的地址进行授权
						window.location.href =
							"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
							appid +
							"&redirect_uri=" +
							encodeURIComponent(local) +
							"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
					} else {
						this.code = code;
						this.loginByMp()
					}
				}else{
					uni.showToast({
						title: '请在微信浏览器中打开',
						icon:'error'
					})
				}
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
					}
				}
				return theRequest;
			},
			loginByMp() {
				if (this.code == null) {
					return;
				}
				uni.showLoading({
					title: "处理中..."
				});
				loginByMp({code:this.code}).then(res => {
						uni.hideLoading();
						if (res.code == 200) {
							uni.setStorageSync('TOKEN_KEY', res.token);
							uni.setStorageSync('userInfo', JSON.stringify(res.user));
							this.userInfo= res.user
							let beforLoginUrl = uni.getStorageSync('beforLoginPage');
							this.isLogin = true
							this.registerCourse()
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					},
					err => {}
				);
			},
			// 成为会员
			registerCourse() {
				console.log(123333)
				this.isVip = 0
				// 确保从本地存储重新获取最新数据
				  // if(uni.getStorageSync('userInfo')){
				  // 	this.userInfo=JSON.parse(uni.getStorageSync('userInfo'));
				  // }
				  // if (!this.userInfo.userId) {
				  // 	// 空值检查
				  //   uni.showToast({ title: '用户未登录或信息不完整', icon: 'none' });
				  //   return;
				  // }
				  if(this.tagIds==null){
					  this.tagIds=""
				  }
				  // console.log(this.tagIds)
				const data={
					userId:this.userInfo.userId,
					companyUserId:this.companyUserId,
					companyId:this.companyid,
					tagIds:this.tagIds,
					projectId:this.projectId
					}
				if(this.isLogin) {
					registerCourses(data).then(res=>{
						if(res.code == 200) {
							this.isVip = 1
							this.isbecomevip=1
							this.viptext='您已成为会员'
							uni.showToast({
								title: '注册成功',
								icon:'none'
							})
						} else {
							this.isbecomevip=1
							// console.log(this.isbecomevip)
							this.viptext=res.msg
							uni.showToast({
								icon:'none',
								title: res.msg
							})
						}
					})
				} else {
					// #ifdef H5
					this.getWechatCode()
					// #endif
					
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.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;
	}
	.getlogo{
		width:240rpx;
		background-color: #fff;
		// padding: 10rpx 20rpx;
	}
	::v-deep .u-popup {
	 flex: 0 !important;
	}
	// .submitname{
	// 	width: 60%;
	// 	background-color: #05a8ee;
	// 	color: #fff;
	// 	margin: 0 auto;
	// 	border-radius: 80rpx;
	// 	text-align: center;
	// 	padding: 20rpx;
	// 	margin-top: 40rpx;
	// }
	.userlogo{
		height: 760rpx;
	}
	.getlogo{
		width:calc(60% - 40rpx);
		margin: 0 auto;
		background-color: #fff;
		padding: 10rpx 20rpx;
		image{
			width: 80rpx !important;
			height: 80rpx !important;
		}
	}
	.footer-tips {
			// margin-top: 14rpx;
			position: fixed;
			width: 100%;
			bottom: 44rpx;
			text-align: center;
			font-family: PingFang SC,PingFang SC;
			font-weight: 500;
			font-size: 12px;
			color: #bbb;
			transform: scale(0.8); 
		}
	.content {
		image {
			width: 300rpx;
			height: 300rpx;
		}
	}
	.bolds {
		color: #999;
		font-size: 16px;
		height: auto;
		line-height: inherit;
		margin-bottom: 0;
		width: 304px;
		word-break: break-all;
		text-align: center;
		margin: 50rpx 0 100rpx 0;
	}
	.sure {
		width: 500rpx;
		background-color: #1777ff;
		line-height: 88rpx;
		text-align: center;
		border-radius: 8rpx;
		color: #fff;
	}
	.btns{
		position: relative;
		width: 630rpx;
		height: 80rpx;
		.author-btn{				
			z-index:100;
			position: absolute;
			width: 630rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #1777ff;
			border-radius: 40rpx;
			font-size: 30rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: rgba(255, 255, 255, 1);
		}
	}
</style>