<template>
	<view class="content hb column justify-center align-center bgf">
		<image src="/static/image/becomevip.png" mode="widthFix"></image>
		<view class="bold">成为会员，享受更多权益</view>
		<view class="sure" @click="registerCourse">{{isVip==1?'您已成为会员':'申请成为会员'}}</view>
	</view>
</template>

<script>
	import { loginByMp,registerCourses } from '@/api/user'
	export default {
		data() {
			return {
				isVip: 0,
				isWechat: false,
				isLogin: false,
				companyid:'',
				companyUserId:'',
				userInfo:{},
				tagIds:[]
			}
		},
		onLoad(option) {
			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')) || {};
			let obj=uni.getStorageSync('AppToken');
			this.isLogin = !!obj;
			this.companyid = option.companyId || ''
			this.companyUserId=option.companyUserId || 0
			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); // [66, 78]
			}
			this.isWechat = String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger"
			this.code = option.code
			if(this.code&&!this.isLogin) {
				this.loginByMp()
			}
		},
		onShow() {
			if(uni.getStorageSync('userInfo')&&JSON.stringify(uni.getStorageSync('userInfo'))!='{}') {
				this.userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			} else {
				this.userInfo = {}
			}
			let obj=uni.getStorageSync('AppToken');
			this.isLogin = !!obj;
			if(this.isLogin&&this.isVip!=1) {
				this.registerCourse()
			}
			
		},
		methods: {
			getWechatCode() {
				if (this.isWechat) {
					let appid = "wx961fadab9bcb792b"; //微信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('AppToken', 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() {
				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
					}
				if(this.isLogin) {
					registerCourses(data).then(res=>{
						if(res.code == 200) {
							this.isVip = 1
							uni.showToast({
								title: '恭喜你！成为会员',
								icon:'none'
							})
						} else {
							uni.showToast({
								icon:'none',
								title: res.msg
							})
						}
					})
				} else {
					this.getWechatCode()
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.content {
		image {
			width: 300rpx;
			height: 300rpx;
		}
	}
	.bold {
		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;
	}
</style>