<template>
	<view>
		 <view class="content x-c">
			<image class="backImg" @tap="goBack()" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/icon_close.png"></image>
			 <view class="pageTop  x-c">
					<view class="head x-c">
						 登录即可体验完整功能
					 </view>
					<view class="loginBox">
							 <view class="login-item">
								 <view class="input-account">
									 <input  v-model="userName" placeholder="手机号登录" type="number" />
								 </view>
								 <view class="line"></view>
							 </view> 
							<!-- <view class="login-item">
								 <view class="input-pwd">
									 <input v-model="password"  placeholder="请输入密码" type="password" />
								 </view>
								  <view class="line"></view>
							 </view> -->
							 <view class="btns">
								 <view class="login-btn" @click="login">登录</view>
							 </view>
							 <view class="reg-box x-bc">
								  <view class="reg-btn" @click="goToRegister()">注册账号</view>
								  <!-- <view class="reg-btn" @click="goToFindPass()">忘记密码</view>  -->
							 </view>
					</view>
			</view>
			<view class="pageBottom" v-if="isApp && isAgreePrivacy">
					<view class="tips y-f"> — 快捷登录 — </view> 
					<view class="menu x-ac">
						 <view @tap="loginWeixin" ><image src="/static/image/login/weixin.png"></image></view>
						 <view v-if="isIos" @tap="quickAppleLogin" ><image src="/static/image/login/apple.png"></image></view>
				   </view>		
			</view>
		
			<view class="checkbox">
				<view class="checkbox-icon" @tap="handleAgree">
					<image src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/right_org_ling.png" v-show="!agree"></image>
					<image src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/right_org.png" v-show="agree"></image>
				</view>
				<view>我已阅读并同意<text @tap="goToWeb(0)">《用户协议》</text><text @tap="goToWeb(1)">《隐私政策》</text> 并使用本机号码登录</view>
			</view>
			
		 </view>
	</view>
	
</template>

<script>
	import { login } from '@/api/living'
	// login
import { loginByWeChat,getUserInfo,loginByApple } from '@/api/user'
export default {
	data() {
		return {
			userName:"",
			password:"",
		    registrationID:"",
			unionid:"",
			userPhone:"",
			loginType:0,
			isApp:false,
			agree: false,
			isAgreePrivacy:false,
			isIos:false,
			from: '',
			source:'',
			appleKey:""
		}
	},
	onLoad(option) {
		// #ifdef APP-PLUS
		this.isIos = plus.os.name == "iOS"
		// #endif  
		this.from= option.from || ''
			let that=this;
			uni.$on('getRegistrationID', function(data) {
				//console.log("getRegistrationID " + JSON.stringify(data));
				that.registrationID=data;
			}); 
		// #ifdef APP-PLUS
		   this.isApp=true;
		   this.source = plus.runtime.channel || 'app'
		// #endif
		// if(!this.$isLogin()) {
		// 	this.$showLoginPage()
		// } 
	},
	onShow() {
		// if(this.$isLogin()) {
		// 	this.goPage()
		// }
		// #ifdef APP-PLUS
			this.isAgreePrivacy=this.isIos ? true : plus.runtime.isAgreePrivacy();
			if(plus.runtime.isAgreePrivacy()) {
			    this.getRegistrationID();
			}
		// #endif
    },
	onUnload() {
		uni.$off('getRegistrationID');
    },
    mounted() {
       
    },
    methods: {
	   initUniverify(){
		   const callback = (res) => {
		     // 获取一键登录弹框协议勾选状态
		     univerifyManager.getCheckBoxState({
		       success(res) {
		         console.log("getCheckBoxState res: ", res);
		         if (res.state) {
		           // 关闭一键登录弹框
		           univerifyManager.close()
		         }
		       }
		     })
		   }
		   // 订阅自定义按钮点击事件
		   univerifyManager.onButtonsClick(callback);
		   // 取消订阅自定义按钮点击事件
		   univerifyManager.offButtonsClick(callback);  
	   },
       login(){
			
			// if (this.$isEmpty(this.password)) {
			// 	uni.showToast({
			// 		title: "请输入密码",
			// 		icon: 'none',
			// 	});
			// 	return
			// }
			if (!this.agree) {
				uni.showToast({
					title: "请同意相关协议",
					icon: 'none'
				});
				return
			}
			var data = {
				phone:this.userName,
				password: this.password,
				jpushId:this.registrationID,
				loginType:3,
				source: this.source
			};
			var that=this;
			uni.showLoading({
				title:"处理中..."
			});
			login(data).then(res => {
					uni.hideLoading();
					console.log("qxj res:"+JSON.stringify(res));
					if(res.code==200){
						console.log("登录了>>>>",res)
						uni.setStorageSync('AppToken',res.token);
						uni.setStorageSync('userInfo',JSON.stringify(res.user));
						uni.$emit('refreshIM');
						uni.$emit('showHealthButler');
						that.goPage();
						
						// // #ifdef H5
						//     this.$navBack();
						// // #endif
						
						// // #ifdef APP-PLUS
						//      this.$navBack();
						//     // uni.reLaunch({
						//     // 	url: '../index/index',
						//     // 	animationType: 'pop-in',
						//     // 	animationDuration: 100
						//     // })
						// // #endif
					}
					else{
						uni.showToast({title: res.msg,icon: 'none'});
					}
				},
				rej => {
					console.log("qxj rej:"+JSON.stringify(rej));
				}
			);
	   },
	  quickAppleLogin() {
	   	let that=this;
		if (!this.agree) {
			uni.showToast({
				title: "请同意相关协议",
				icon: 'none'
			});
			return
		}
		uni.getProvider({
			service: 'oauth',
			success: function (res) {
				// console.log(res.provider)
				if (res.provider.indexOf('apple')) {
					uni.login({
						provider: 'apple',
						success: function (loginRes) {
							that.appleKey = loginRes.authResult.openid
							that.loginByAppleAct(loginRes.authResult)
							
						},
						fail: function (err) {
							console.log(err);
							// 登录授权失败
							// err.code错误码参考`授权失败错误码(code)说明`
						}
					});
				}
			}
		});
	   },
	   async loginByAppleAct(authResult) {
		   let loginDevice = ''
			if(plus.runtime.isAgreePrivacy()) {
				const info = await uni.getPushClientId();
				uni.setStorageSync("registrationID", info.cid);
				this.registrationID = info.cid;
				let devinfo= await uni.getDeviceInfo();
				if(devinfo!=null){
					loginDevice += devinfo.deviceBrand ? devinfo.deviceBrand : "";
					loginDevice += devinfo.deviceModel ? " " + devinfo.deviceModel : "";
					loginDevice += devinfo.system ? " " + devinfo.system : "";
				}
			}	
		    const params={
				loginDevice:loginDevice,
			   jpushId:this.registrationID,
			   source:this.source,
			   appleKey: authResult.openid
			};
			uni.showLoading({
				title: '登陆中'
			})
		    loginByApple(params).then(res=>{
				uni.hideLoading()
				if(res.user!=null){
					   uni.hideLoading();
					   uni.setStorageSync('AppToken',res.token);
					   uni.setStorageSync('userInfo',JSON.stringify(res.user));
					   uni.closeAuthView();
					   uni.$emit('refreshIM');
					   uni.$emit('showHealthButler');
					   uni.$emit('refreshUserInfo',{});
					   // this.$navBack();
					   this.goPage()
				}else{
					if(res.isNew){
						this.bindMobile('apple');
					}
				}
			}).catch(()=>{
				uni.hideLoading()
			})
	   },
	   loginWeixin(){
		   if (!this.agree) {
		   	uni.showToast({
		   		title: "请同意相关协议",
		   		icon: 'none'
		   	});
		   	return
		   }
		   uni.login({
		   	provider: "weixin",
		   	onlyAuthorize:true,
		   	success: async (res) => {
		   		let that=this;
		   		uni.showLoading({
		   			title:"处理中..."
		   		});
		   		const params={code:res.code,jpushId:this.registrationID,source:this.source};
		   		this.loginByWeChatAct(params);
		   	},
		   	fail: (err) => {
		   		console.log('qxj loginWeixin fail:', JSON.stringify(err));
		   		// 未开通
		   		if (err.code == 1000) {
		   			uni.showModal({
		   				title: '登录失败',
		   				content: `${err.errMsg}\n，错误码：${err.code}`,
		   				confirmText: '开通指南',
		   				cancelText: '确定',
		   				success: (res) => {
		   					if (res.confirm) {
		   						setTimeout(() => {
		   							plus.runtime.openWeb('https://ask.dcloud.net.cn/article/37965')
		   						}, 500)
		   					}
		   				}
		   			});
		   			return;
		   		}
		   		// 一键登录预登陆失败
		   		if (err.code == '30005') {
		   			uni.showModal({
		   				showCancel: false,
		   				title: '预登录失败',
		   				content: err.errMsg
		   			});
		   			return;
		   		}
		   		// 一键登录用户关闭验证界面
		   		if (err.code != '30003') {
		   			uni.showModal({
		   				showCancel: false,
		   				title: '登录失败',
		   				content: JSON.stringify(err)
		   			});
		   		}
		   	},
		   	complete: () => {
		   		
		   	}
		   });			
		   								
	   },
	   goToRegister(){
		   this.$navTo('./register');
	   },
	   goToFindPass(){
	   	   this.$navTo('./findpass');
	   },
	   doUniverify(authResult){
		   uniCloud.callFunction({
				 name: 'loginByMobile', // 你的云函数名称
				 data: {
				   access_token: authResult.access_token, // 客户端一键登录接口返回的access_token
				   openid:authResult.openid // 客户端一键登录接口返回的openid
				 }
		   }).then(res => {
			    uni.closeAuthView();
			   if(res.result.errCode==0){
				   this.userName=res.result.phoneNumber;
			   }else{
				   uni.showToast({title:res.result.message,icon: 'none' });
			   }
		      
		   }).catch(err=>{
		       // 处理错误
			    console.error('调用云函数失败:',err);
			    // 详细记录错误信息
			    console.error('错误信息:', err.errMsg);
		   })
	   },
	   loginByWeChatAct(params){
	   	 loginByWeChat(params).then(res => {
	   	 		if(res.code==200){
	   	 			if(res.user!=null){
	   	 				   uni.hideLoading();
	   	 				   uni.setStorageSync('AppToken',res.token);
	   	 				   uni.setStorageSync('userInfo',JSON.stringify(res.user));
	   	 				   uni.closeAuthView();
						   uni.$emit('refreshIM');
						   uni.$emit('showHealthButler');
	   					   uni.$emit('refreshUserInfo',{});
						   // this.$navBack();
						   this.goPage()
	   	 			}else{
	   	 				this.unionid=res.unionid;
	   	 				if(res.isNew){
	   	 					this.bindMobile();
	   	 				}
	   	 			}
	   	 		    
				}
	   	 		else{
	   	 			uni.hideLoading();
	   	 			uni.showToast({title: res.msg,icon: 'none'});
	   	 		}
	   	 	},
	   	 	rej => {}
	   	 );								
	   },
	   bindMobile(type){
	   	 // #ifdef APP-PLUS
	
	   	    uni.login({
	   	    		        provider: 'univerify',
	   	    				univerifyStyle: { // 自定义登录框样式
	   	    				   fullScreen: false,
	   	    				   authButton: {
	   	    				    	"title": "绑定手机号", 
	   	    						"normalColor": "#FF5C03", 
	   	    						"highlightColor": "#FF5C03",
	   	    				   },
	   	    				   privacyTerms: {
	   	    					        "defaultCheckBoxState":true, // 条款勾选框初始状态 默认值： true
	   	    					        "isCenterHint":false, //未勾选服务条款时点击登录按钮的提示是否居中显示 默认值: false (3.7.13+ 版本支持)
	   	    					        "uncheckedImage":"", // 可选 条款勾选框未选中状态图片（仅支持本地图片 建议尺寸 24x24px）(3.2.0+ 版本支持)
	   	    					        "checkedImage":"", // 可选 条款勾选框选中状态图片（仅支持本地图片 建议尺寸24x24px）(3.2.0+ 版本支持)
	   	    					        "checkBoxSize":18, // 可选 条款勾选框大小
	   	    					        "textColor": "#BBBBBB", // 文字颜色 默认值：#BBBBBB
	   	    					        "termsColor": "#FF5C03", //  协议文字颜色 默认值： #5496E3
	   	    					        "prefix": "我已阅读并同意", // 条款前的文案 默认值：“我已阅读并同意”
	   	    					        "suffix": "并使用本机号码登录", // 条款后的文案 默认值：“并使用本机号码登录”
	   	    					        "privacyItems": [  // 自定义协议条款，最大支持2个，需要同时设置url和title. 否则不生效
	   	    					           
	   	    					        ]
	   	    					    },
	   	    				   },
	   						   success(res){ //
	   								console.log("qxj univerify login:"+JSON.stringify(res.authResult));  // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
	   								if(type == 'apple') {
										this.loginByUniverify(res.authResult,3);
									} else {
										this.loginByUniverify(res.authResult,1);
									}
	   						   },
	   	    				   fail(res){  
	   								uni.hideLoading();
	   								uni.showToast({title: "一键登录失败请检查网络和SIM卡是否可用",icon: 'none',position:'bottom'});
	   								//setTimeout(function() {
	   									uni.navigateTo({url: "/pages/auth/login"});
	   								//}, 1800);
	   								//}
	   								//登录失败
	   								console.log("qxj failRes:"+JSON.stringify(res));
	   	    				
	   					}
	   	    });
	   	    	
	   	 // #endif
	   	 
	   	 // #ifdef H5
			   uni.navigateTo({
				    url: "/pages/auth/login"
			   });
	   	 // #endif
	   },
	   loginByUniverify(authResult,type){
	   		   uniCloud.callFunction({
	   				 name: 'loginByMobile', // 你的云函数名称
	   				 data: {
	   				   access_token: authResult.access_token, // 客户端一键登录接口返回的access_token
	   				   openid:authResult.openid // 客户端一键登录接口返回的openid
	   				 }
	   		   }).then(res => {
	   			    console.log("qxj doUniverify:",JSON.stringify(res));
	   			   if(res.result.errCode==0){
	   				   userPhone=res.result.phoneNumber;
					   if(type==3) {
						   // 苹果登录
						   this.setPhoneAct(3,userPhone,this.unionid);
					   } else {
						   this.setPhoneAct(1,userPhone,this.unionid);
					   }
	   			   }else{
	   				   uni.showToast({title:res.result.message,icon: 'none' });
	   			   }
	   		   }).catch(err=>{
	   		       // 处理错误
	   			    console.error('调用云函数失败:',err);
	   			    // 详细记录错误信息
	   			    console.error('错误信息:', err.errMsg);
	   		   })
	   },
	   setPhoneAct(type,phone,unionId){
	   	  let params={
			  phone:phone,
			  unionId:unionId,
			};
			if(type==3) {
				params={
				  phone:phone,
				  unionId:unionId,
				  appleKey: this.appleKey
				};
			}
	   	  setPhone(params).then(res => {
	   	  		uni.hideLoading();
	   	  		if(res.code==200){
	   	  			   uni.setStorageSync('AppToken',res.token);
	   	  			   uni.setStorageSync('userInfo',JSON.stringify(res.user));
	   	  			   uni.closeAuthView();
					   uni.$emit('refreshIM');
	   	  			   // #ifdef APP-PLUS
	   	  			 
	   	  			   // #endif 
					   this.goPage()
	   	  		}
	   	  		else{
	   	  			uni.showToast({title: res.msg,icon: 'none'});
					uni.closeAuthView();
	   	  		}
	   	  	},
	   	  	rej => {}
	   	  );
	    },
	   getRegistrationID(){
		   this.registrationID=uni.getStorageSync("registrationID");
		    if(this.registrationID==null || this.registrationID==""){
		    	uni.getPushClientId({success: res => {
		    			uni.setStorageSync("registrationID",res.cid);
						this.registrationID = res.cid
		    		}
		    	});
		    }
	   },
	   goBack(){
		  console.log("qxj goBack");
		  uni.$emit('showHealthButler');
		  // this.$navBack();
			uni.redirectTo({
				url: "/pages/auth/loginIndex"
			})
	   },
	   handleAgree() { // 同意
	      this.agree = !this.agree
		  if(this.isIos) {
			  if(this.agree) {
				plus.runtime.agreePrivacy()
				this.getRegistrationID();
			  } else {
				plus.runtime.disagreePrivacy();
			  }
		  }
	   },
	   goToWeb(index){
			uni.setStorageSync('url',index==0?"https://userapp.his.cdwjyyh.com/web/userAgreement":"https://userapp.his.cdwjyyh.com/web/privacyPolicy");
			uni.navigateTo({
				url:"/pages/index/h5"
			})
	   },
	   goPage() {
		    let pages = getCurrentPages();
		    let url = pages[ pages.length - 1];
			let openUrl = uni.getStorageSync("openUrl");
			if(openUrl) {
				uni.navigateTo({
					url: openUrl,
					success: function(res) {
					    uni.removeStorageSync("openUrl")
					}
				})
			} else {
				uni.reLaunch({
					url: '/pages/home/index',
					animationType: 'none',
					animationDuration: 2000
				});
				return;
				if(pages.length == 1) {
					uni.reLaunch({
						url: '/pages/home/index',
						//url: '../course/video/living-app',
						animationType: 'none',
						animationDuration: 2000
					});
				} else {
					//this.$navBack();
				}
			}
			this.$updateMsgDot()
			this.$setSource()
	   }
    },
}
</script>

<style scoped lang="scss">
	
 page{
 	background-color: #ffffff;
 }
 .other-login-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 80rpx;
	background: rgba(229, 138, 0, 0.08);
	border-radius: 40rpx;
	font-size: 30rpx;
	font-family: PingFang SC;
	font-weight: 500;
	color: #FF5C03;
 	border: 2rpx solid #FF5C03;
	margin-top: 30rpx;
	&::after {
		border: none;
	}
 }
 .content{
 	 display: flex;
 	 flex-direction: column;
 	 align-items: center;
 	 height: calc(100vh);
 	 width: 100%;
	 position: relative;
	 // justify-content: space-between;
	 //padding-top: calc(100% - 32vh);
 }
 .backImg{
	 position: absolute;
	 left:30rpx;
	 top:40px;
	 height: 30rpx;
	 width: 30rpx;
 }
 
 .pageTop{
	 display: flex;
	 flex-direction: column;
	 width: 100%;
 }
 
 .content .head{
 	text-align: center;
 	width: 100%;
	height: 100rpx;
	// background:url(/static/image/login/top_bg.png) no-repeat 0 center;
	background-size: cover;
    box-sizing: border-box;
	font-size: 36rpx;
	font-weight: bold;
	color: #666;
 }

 .content .head image{
 	width: 150rpx;
	height: 150rpx;
 	border-radius: 10rpx;
 	box-shadow:0px 0px 20rpx rgba(0,0,0,0.2);
 }
.title{
 	color: #141414;
 	margin:50upx 0upx 30upx 0rpx;
 	font-size: 38rpx;
	font-weight: 500;
 }
 .desc{
 	color: #686866;
 	padding:0 0 30rpx 0rpx;
 	font-size: 28rpx;
 }
 .loginBox{
 	padding:0 10px 30rpx;
	width: calc(100%) ;
	background: #FDFDFD;
	z-index: 10;
	position: relative;
	.login-item p{
		text-align: left;
	}
	.line{
		 height: 0.5rpx;
		 background-color: #efefef;
		 margin-top: 10rpx;
	}
	.input-account{
		margin-top: 20rpx;
		margin-bottom: 0rpx;
		border-radius:40rpx;
		border:solid 0rpx #efefef;
		height: 80rpx;	
		width: 100%;
		// background:url(/static/account.png) no-repeat 0 center;
		background-size: 30rpx 30rpx;
		background-position: 30rpx;
	}
	.input-pwd{
		margin-top: 40rpx;
		margin-bottom: 20rpx;
		border-radius:40rpx;
		border:solid 0rpx #efefef;
		height: 80rpx;	
		width: 100%;
		// background:url(/static/password.png) no-repeat 0 center;
		background-size: 30rpx 30rpx;
		background-position: 30rpx;
	}
	input{
		margin-left: 80rpx;
		height: 80rpx;
		line-height: 80rpx
	}
	.reg-box {
		 padding-bottom:20rpx;
		 margin:0 10px;
		 .reg-btn{
		 	 font-size:16px ;
		 	 color: #FF5C03;
		 }
	}
 }

 .btns{
 	margin: 60rpx 0rpx;
 }
 
 .login-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 80rpx;
	background: linear-gradient(to right, #FF5C03 0%, #FF5C03 100%);
	background: -moz-linear-gradient(to right, #FF5C03 0%, #FF5C03 100%);
	box-shadow: 0px 7rpx 6rpx 0px rgba(229, 138, 0, 0.22);
	border-radius: 40rpx;
	font-size: 30rpx;
	font-family: PingFang SC;
	font-weight: 500;
	color: rgba(255, 255, 255, 1);
 }
 
 .pageBottom{
	height: 220rpx;
	width: 75%;
	display: flex;
	flex-direction: column;
	position: absolute;
	bottom: 100rpx;
 }  
 
 .tips{
 	color: #999;	 
	font-size: 32rpx;
 }  
 .menu{
	 margin-top: 30rpx;
	 image{
	 	width: 96rpx;
	    height: 96rpx;
	 }
 }
  
  
 .checkbox {
	margin: 20rpx;
 	margin-top: 36rpx;
	display: flex;
	flex-direction:row;
	align-items: flex-start;
	justify-content: flex-start;
 	font-family: PingFang SC, PingFang SC;
 	font-weight: 400;
 	font-size: 26rpx;
 	color: #999999;
 	line-height: 38rpx;
 	text-align: left;
 	text {
 		color:#FF5C03;
 	}
 	&-icon {
 		flex-shrink: 0;
 		margin-right: 12rpx;
 		image {
 			height: 24rpx;
 			width: 24rpx;
 		}
 	}
 }
</style>
