<template>
	<!-- #ifdef MP-WEIXIN -->
	<button data-remark='快速登录' open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber" class="no_style">
		<span class="biggerSize"  >
			<slot></slot>
		</span>
	</button>
	<!-- #endif -->
	<!-- #ifdef APP-PLUS -->
	<button class="no_style" @click="applogin">
		<span class="biggerSize"  >
			<slot></slot>
		</span>
	</button>
	<!-- #endif -->
</template>

<script>
export default {
	data() {
		return {};
	},
	created() {
		this.getCode((res) => {
			uni.setStorageSync("apply-code", res);
		});
	},
	props: {
		cloudName:{
			type:String,
			default(){
				return '';
			}
		},
		mobileToLogin:{
			type:String,
			default(){
				return '';
			}
		},
		codeToMobile:{
			type:String,
			default(){
				return '';
			}
		},
	},
	methods: {
		// #ifdef APP-PLUS
		applogin(){
			let that = this;
			uni.getProvider({
				service: 'oauth',
				success: function (serveRes) {
					if(serveRes.provider && serveRes.provider.indexOf('univerify') > -1){
						uni.preLogin({
							provider: 'univerify',
							success(){  
								uni.login({
									provider: 'univerify',
									univerifyStyle: {},
									success(loginRes){ 
										uniCloud.callFunction({
										  name: cloudName, 
										  data: {
										    'access_token': loginRes.authResult.access_token, 
										    'openid': loginRes.authResult.openid
										  }
										}).then(mobileRes => {
										  uni.closeAuthView();
											let params = {
												tel: mobileRes.result.data.phoneNumber,
											}
		                  that.path = '/pages/index/index';
		                  that.G.Get(
		                  	that.mobileToLogin,
		                  	params,
		                  	(baseRes) => {
		                  		that.setToken(baseRes);
		                  	}
		                  );
										}).catch(err=>{
											console.log('云函数返回失败：',err)
											uni.closeAuthView();
										})
									},
									fail(res){  
										that.handleErrMsg(res)
									}
								})
							},
							fail(res){ 
								that.handleErrMsg(res)
								console.log('预登陆失败：',res)
							}
						})
					}else{
						uni.showModal({
							content:'当前设备不支持一键登录',
							showCancel:false,
						})
					}
				}
			});
		},
		// #endif
		handleErrMsg(res){
			if(res.errMsg){
				if(res.errMsg.indexOf('-20201') > -1){
					uni.showModal({
						content:'未插手机电话卡',
						showCancel:false
					})
				}else if(res.errMsg.indexOf('-20202') > -1){
					uni.showModal({
						content:'未开启蜂窝网络',
						showCancel:false
					})
				}else if(res.errMsg.indexOf('-20203') > -1){
					uni.showModal({
						content:'不支持的运营商，请检查手机是否成功连接运营商',
						showCancel:false
					})
				}else if(res.errMsg.indexOf('-20102') > -1){
					uni.showModal({
						content:'服务已到期，请联系客服',
						showCancel:false
					})
				}else if(res.errMsg.indexOf('-10003') > -1){
					uni.showModal({
						content:'网络问题，关闭然后打开飞行模式，或者使用手机流量网络重新试下',
						showCancel:false
					})
				}else{
					if(res && res.metadata && res.metadata.msg){
						uni.showModal({
							content:res && res.metadata && res.metadata.msg ? res.metadata.msg : '请联系客服',
							showCancel:false
						})
					}else if(res.code == 30005){
						uni.showModal({
							content:'运营商返回失败',
							showCancel:false
						})
					}
				}
			}
		},
		onGetPhoneNumber(e) {
			let that = this;
			// that.$emit("successLogin");
			// return;
			console.log("e", e);
			// 进行临时变量的判断, 如果在注册页面获取过手机号授权, 则不再重新获取手机号, 直接登录
			if (uni.getStorageSync("TEMPORARY_CODE")) {
				let wxRes = uni.getStorageSync("TEMPORARY_CODE");
				that.G.Get(
					that.mobileToLogin,
					{
						openId: wxRes.openId,
						tel: wxRes.phoneNumber,
						unionid: wxRes.unionid,
					},
					(res) => {
						console.log("res", res);
						that.setToken(res);
					}
				);
				return;
			}
			if (e.detail.code) {
				// 允许授权。拿button返回信息换取token
				uni.checkSession({
					success(e1) {
						console.log("success", e1);
						//session_key 未过期，并且在本生命周期一直有效
						that.loginWX(e);
					},
					fail() {
						// session_key 已经失效，需要重新执行登录流程
						that.getCode((res) => {
							console.log("res", res);

							uni.setStorageSync("apply-code", res);
							setTimeout(() => {
								that.loginWX(e);
							}, 300);
						});
					},
				});
			} else {
				// 拒绝授权。
			}
		},
		loginWX(e) {
			let that = this;
			console.log("loginWX", e);
			that.G.Get(
				that.codeToMobile,
				{
					code: uni.getStorageSync("apply-code"),
					btnCode: e.detail.code,
					iv: e.detail.iv,
					encryptedData: e.detail.encryptedData,
				},
				(wxRes) => {
					that.G.Get(
						that.mobileToLogin,
						{
							openId: wxRes.openId,
							tel: wxRes.phoneNumber,
							unionid: wxRes.unionid,
						},
						(res) => {
							that.setToken(res);
						}
					);
				}
			);
		},
		setToken($data) {
			let that = this;
			uni.setStorageSync("apply-token", $data.token); 
			that.$emit('exportSetToken',$data)
		},
		getCode(callback = () => {}) {
			uni.login({
				success(wxRes) {
					console.log("wxRes", wxRes);
					callback(wxRes.code);
				},
				fail(res) {
					console.log(res);
				},
			});
		},
	},
};
</script>

<style>
.no_style {
  width: 100%;
  height: 100%;
  background-color: transparent;
  border: none;
  padding: 0;
  margin: 0;
  color: inherit;
  font-size: inherit;
  /* line-height: 0; */
}
.biggerSize {
	position: relative;
}
.biggerSize::after {
	content: "";
	/* display: inline-block; */
	width: 150%;
	height: 140%;
	position: absolute;
	left: 50%;
	top: 50%;
	z-index: 99;
	transform: translate(-50%, -50%);
}
</style>
