<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" v-if="isVip==1 || isbecomevip==1" @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.png'" 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,checkUserInfo,editUser} from './api/courseLook'
	export default {
		data() {
			return {
				isVip: 0,
				isWechat: false,
				isLogin: false,
				companyid:'',
				companyUserId:'',
				userInfo:{},
				tagIds:[],
				isbecomevip:0,
				viptext:'申请成为会员',
				userInfos:null,
				userlogo:false,
				userinfos:{
					nickname:'',
					avatar:""
				},
				headImg:'',
				authType:0,//0微信登录 1手机号登录
				userdisabled:false,
				projectId:''
			}
		},
		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) {
			console.log(option)
			// let path = 'https://userapp.fbylive.com'//福本源
			let path = 'https://userapp.klbycp.com'//中康
			// let path = 'https://user.test.ylrztop.com/api'//云融融智
			// let path = 'https://userapp.ashyisheng.com'//蜂巢快药
			// let path = 'https://userapp.whhm.ylrzcloud.com/prod-api'//惠名大药房
			// let path = 'https://userapp.xdtongshuntang.top'//同顺堂
			// let path = 'https://userapp.liangmiaoedu.com'//良苗
			// let path = 'https://usercourse.beliyostore.com'//倍力优
			// let path = 'https://userapp.bainian1000y.cn/prod-api'//百年康城
			// let path = 'https://userapp.drkzyy.cn/prod-api'//青岛市德瑞康
			// let path = 'https://companyapp.gjh2024.com/apis'//金康键
			uni.setStorageSync('requestPath',path)
			if(uni.getStorageSync('userInfo')&&JSON.stringify(uni.getStorageSync('userInfo'))!='{}') {
				this.userInfo = JSON.parse(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');
			this.isLogin = !!obj;
			this.companyid = option.companyId || ''
			this.companyUserId=option.companyUserId || 0
			this.projectId=option.projectId
			//#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
			}
			// if(this.$store.state.logoname=='乐氏本源'){
			// 	this.userInfos=uni.getStorageSync('userInfos')
			// 	if(!uni.getStorageSync('userInfos')){
			// 		uni.navigateTo({
			// 			url:'/pages_course/webview'
			// 		})
			// 	}
			// }
			//#endif
			if(option.tagids=="null"){
				this.tagIds=[]
			}else{
				this.tagIds=option.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() {
			if(uni.getStorageSync('userInfo')&&JSON.stringify(uni.getStorageSync('userInfo'))!='{}') {
				this.userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			} else {
				this.userInfo = {}
			}
			//#ifdef MP-WEIXIN
			this.userInfos=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.checkUserInfoA()
			}
			
		},
		methods: {
			//检查用户昵称以及头像
			checkUserInfoA(){
				checkUserInfo().then(res=>{
					if(res.code==200){
						this.isLogin = true
						this.userInfo= res.user
						uni.setStorageSync('userInfo', JSON.stringify(res.user));
						this.nameuser
						if(this.nameuser==''){
							this.userinfos.nickname=this.userInfo.nickname
						}
						this.registerCourse()
					}else if(res.code==500){
						if(res.authType==2){
							uni.setStorageSync('authUrl',res.domain)
							if(!uni.getStorageSync('userInfos')||uni.getStorageSync('userInfos')=={}){
								uni.navigateTo({
									url:'/pages_course/webview'
								})
								return
							}
							this.editUserA()
						}else{
							this.userlogo=true
						}
					}else{
						uni.showToast({
							icon:'none',
							title:res.msg,
						});
					}
				})
			},
			//修改用户昵称以及头像
			editUserA(){
				this.userinfos=uni.getStorageSync('userInfos')?uni.getStorageSync('userInfos'):this.userinfos
				const data={
					nickname:this.userinfos.nickname,
					avatar:this.userinfos.avatar,
				}
				editUser(data).then(res=>{
					if(res.code==200){
						uni.showToast({
							icon:'none',
							title:'修改成功！',
						});
						setTimeout(()=>{
							this.registerCourse()
						},100)
					}else{
						uni.removeStorageSync('userInfos')
						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('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{
					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>