<template>
	<view class="cont-bind">
		<image src="/static/course_expiration_img.png" mode="aspectFill"></image>
		<!-- <button class="msgbox" :disabled="bindShow" @click="getAddCompany">{{msgText}}</button> -->
		<view class="mt50">
			<u-button type="primary" :text="msgText" :disabled="bindShow"></u-button>
		</view>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex';
	import {handleFsUserWx} from '@/api/courseLook.js'
	import {TOKEN_KEYAuto} from '@/utils/courseTool.js'
	import {
		addUserAndSaleFriend,
		loginByMp,
	} from "@/api/courseAuto.js"
	import {
		getConfigByKey
	} from "@/api/user.js"
	export default {
		data() {
			return {
				compayUserId:'',
				externalUserId:'',
				user:{},
				isLogin:false,
				code:'',
				companyId:'',
				msgText:'点击绑定 !',
				bindShow:false
			}
		},
		computed:{
			isSpare() {
				return this.$store.state.isSpare
			},
			...mapGetters(['coureLogin']),
		},
		onLoad(option) {
			uni.$on('usercode',(data)=>{
				if(this.isSpare == 1&&data) {
					this.code=data.code
					this.goLogin(data)
				}
			})
			this.externalUserId=option.externalUserId
			this.compayUserId=option.compayUserId
			this.companyId=option.companyId
			this.getWebviewUrl().then(()=>{
				this.getAddCompany()
			}).catch(()=>{
				this.getAddCompany()
			})
		},
		onShow() {
		},
		methods: {
			getWebviewUrl() {
				return new Promise((resolve,reject)=>{
					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)
							resolve()
						}else{
							uni.showToast({
								icon:'none',
								title: res.msg,
							});
							resolve()
						}
					}).catch(()=>{
						resolve()
					})
				})
			},
			getAddCompany() {
				this.$isLoginCourseAuto().then(
					isLogin => {
						this.isLogin = isLogin
						if(isLogin){
							this.addUserAndSaleFriends() 
						} else {
							this.goLogin()
						}
					},
					rej => {}
				);
			},
			addUserAndSaleFriends(){
				// this.getAddCompany()
				const data={
					compayUserId:this.compayUserId,
					externalUserId:this.externalUserId
				}
				addUserAndSaleFriend(data).then(res=>{
					console.log(res)
					if(res.code==200){
						this.msgText='绑定成功 !'
						this.bindShow=true
					}else{
						this.msgText=res.msg
					}
				})
			},
			goLogin(data) {
				if(data || this.isSpare==1) {
					this.loginFsUserWx(data)
					return
				}
				let provider = 'weixin'
				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:wx.getAccountInfoSync().miniProgram.appId,
								}).then(res=>{
									 uni.hideLoading();
									 if (res.code == 200) {
										 this.$store.commit('setCoureLogin', 1);
										uni.setStorageSync(TOKEN_KEYAuto, res.token);
										uni.setStorageSync('auto_userInfo', JSON.stringify(res.user));
										this.user = res.user
										this.isLogin = true
										console.log("TOKEN_KEYAuto",TOKEN_KEYAuto)
										this.addUserAndSaleFriends() 
									 } else {
										uni.showToast({
											title: res.msg,
											icon: 'none'
										});
									 }
								 }).catch(err=>{
									uni.hideLoading();
									uni.showToast({
										icon:'none',
										title: "登录失败,请重新登录",
									});
								});
						   }
						});
					}
				})
			},
			//备用登录
			async loginFsUserWx(data){
				if(data){
					uni.showLoading({
						title: '登录中'
					})
					uni.login({
						provider: "weixin",
						success: async loginRes => {
							console.log(loginRes)
							let code = loginRes.code // 获取开发code
							handleFsUserWx({
							   code: code,
							   appId:wx.getAccountInfoSync().miniProgram.appId,
							   userId:data.userId
							})
							.then( res => {
								uni.hideLoading();
								if(res.code==200){
									this.$store.commit('setCoureLogin', 1);
									console.log("loginFsUserWx:",res)
									let token = uni.getStorageSync('TOKEN_WEXIN');
									let user = uni.getStorageSync('userInfo')
									uni.setStorageSync(TOKEN_KEYAuto, token);
									uni.setStorageSync('auto_userInfo', JSON.stringify(user));
									this.user = user
									this.isLogin = true
									this.addUserAndSaleFriends()
								}else if(res.code==406){
									uni.showToast({
										icon:'none',
										title: '该用户已成为其他销售会员',
									});
								}else{
									uni.showToast({
										icon:'none',
										title: res.msg,
									});
								}
							   
							 })
						},
					})
				}else{
					uni.setStorageSync('H5course',{
						companyId: this.companyId,
						companyUserId:this.compayUserId,
						type: 1, //1自动，其他手动
					})
					// await this.$store.dispatch('getWebviewUrl');
					uni.navigateTo({
						url:'/pages_course/webview?H5course='+uni.getStorageSync('H5course')
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
.cont-bind{
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 100vh;
}
.msgbox{
	background-color: #f87132;
	color: #fff;
	padding: 0rpx 40rpx;
	text-align: center;
	border-radius: 30rpx;
}
</style>
