<template>
	<view style="padding: 16px;font-size: 14px;">
		<tn-nav-bar fixed alpha customBack>
			<view slot="back" class='tn-custom-nav-bar__back' @click="goBack">
				<text class='icon tn-icon-left'></text>

			</view>
		</tn-nav-bar>
		<view style="text-align: center;padding: 80px 0">
			<image src="../../static/logo.png" style="width: 110px; height: 100px;"></image>
			<view style="margin: 8px 0;"><text style="font-size: 22px;font-weight: bold;" :style="{fontSize:(wxFontSize+5)+'px'}">速立保</text></view>
		</view>

		<view :class="!agreeValue?'':'isHidden'" style="background: #00000088;
    display: inline;
    padding: 4px 10px;
    border-radius: 12px;
    border-bottom-left-radius: 0;
    color: #fff;font-size: 12px;margin-left: 12px;" :style="{fontSize:(wxFontSize-5)+'px'}">
			请先阅读并同意协议
		</view>

		<view style="margin-top:4px">
			<tn-checkbox v-model="agreeValue" activeColor="#1d60b1" :size="wxFontSize+17" name="选项1"  >
				<text :style="{fontSize:(wxFontSize-2)+'px'}">阅读并同意</text>
			</tn-checkbox>
			<view style="display: inline;font-size: 15px; margin-left: -12px;vertical-align: middle;" @click="showInfo()" :style="{fontSize:(wxFontSize-2)+'px'}">
				<view style="color: #1d60b1;display: inline;">《用户服务协议》</view>
				和
				<view style="display: inline;color: #1d60b1;" @click="showInfo2()">《隐私政策》</view>
			</view>

		</view>

		<view class="" hover-class="button-hover" style="margin-top: 24px;" v-if="agreeValue">
			<button :disabled="!canSave" style="border-radius: 50rpx;width: 100%;background-color: #1d60b1;" type="primary" open-type="getPhoneNumber"
				@getphonenumber="getPhoneNumber" :style="{fontSize:(wxFontSize-2)+'px'}">手机号快捷登录</button>
		</view>
		<view class=""  hover-class="button-hover" style="margin-top: 24px;" v-if="!agreeValue">
			<button :disabled="!canSave" style="border-radius: 50rpx;width: 100%;background-color: #1d60b1;" type="primary" @click="showToast" :style="{fontSize:(wxFontSize-2)+'px'}">手机号快捷登录</button>
		</view>
		
		<view @click="showLogin" style="text-align: center;margin-top: 24px;" :style="{fontSize:(wxFontSize-4)+'px'}">验证码登录</view>


	</view>
</template>

<script>
	import request from '../../utils/request';
	export default {

		data() {
			return {
				agreeValue: false,
				value: [],
				range: [{
					"value": 0,
					"text": ""
				}],
				lxSessionKey: '',
				openId: '',
				unionid: '',
				canSave:true,
				phoneNum:'',
				wxFontSize: 17,
				phoneData: null
			}
		},
		onLoad() {
			const appBaseInfo = wx.getAppBaseInfo();
			this.wxFontSize = uni.getStorageSync('fontSize')||appBaseInfo.fontSizeSetting||17;
		},
		onShow(){
			if(uni.getStorageSync('agreeInfo')){
				this.agreeValue = true;
			}
		},
		beforeDestroy(){
			uni.removeStorageSync('agreeInfo')
		},
		methods: {
			goBack() {
				const pages = getCurrentPages()
				// 有可返回的页面则直接返回，uni.navigateBack 默认返回失败之后会自动刷新页面 ，无法继续返回
				if (pages.length > 1) {
					uni.navigateBack()
					return;
				}else{
					uni.navigateTo({
						url: '/pages/index/index'
					})
				}
			},
			showToast() {
				uni.showToast({
					title: '请先阅读并同意协议',
					icon: 'none'
				})
				wx.vibrateShort();
			},
			showInfo() {
				if(uni.getStorageSync('agreeInfo')){
					uni.navigateTo({
					  url: '/pages/login/info?counted=1'
					})
					return false;
				}else{
					uni.navigateTo({
					  url: '/pages/login/info'
					})
				}
			},
			showInfo2() {
				uni.navigateTo({
				    url:'/pages/webview/web-view?url='+encodeURIComponent('https://slb-m.lx-device.com/webview?title=隐私协议&url='+'https://oss.lx-device.com/userFeedback/1735201139460G1J.docx'),
			    })
			},
			showLogin(){
				uni.redirectTo({
					url:'/pages/login/loginByCode'
				})
			},
			change(e) {
				this.value = e.detail.data.length == 0 ? [] : [0];
				console.warn(this.value);
				console.log('e:', e);
			},
			
			getLxSessionKey(e) {
				const that = this;
				uni.login({
					success(res) {
						console.error(res);
						//如果已经注册，自动登录一次
						 
						that.getOpenId(res.code,e);
					},
					fail(res) {
						console.error(res);
						uni.hideLoading();
					}
				});
			},
			getOpenId(code,data) {
				const that = this;
				request.post('/wxma/code2Session', {
					code: code,
					platType: "slb",
					mpType: "engineer",
				}).then(res => {
					console.error(res);
					if (res.success) {
						that.lxSessionKey = res.resultMap.lxSessionKey;
						that.openId = res.resultMap.openId;
						that.unionid = res.resultMap.unionid;
						that._getPhoneNumber(data);
					}

				})

			},
			getPhoneNumber(e) {
				if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
					// wx.showModal({
					// 	title: '提示',
					// 	content: e.detail.errMsg,
					// 	showCancel: false
					// })
					console.error(e)
					return;
				}
				//
				this.phoneData = e;
				//获取手机号之前，先登录一次，判断是否注册过。
				this.loginFirst();

			},




			_getPhoneNumber(e) {
				console.warn(e);
				let that = this;


				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					wx.getUserInfo({
						success: function(res) {
							console.error(res);
							res.encryptedData = encodeURIComponent(encodeURIComponent(e.detail.encryptedData));
							res.iv = encodeURIComponent(encodeURIComponent(e.detail.iv));
							res.lxSessionKey = that.lxSessionKey;
							that.getPhone(res)
						}
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: e.detail.code ? '获取成功' : '拒绝了使用微信手机号'
					});
				}
			},

			getPhone(prarms) {
				let newParams = {};
				newParams.signature = prarms.signature;
				newParams.rawData = prarms.rawData;
				newParams.encryptedData = prarms.encryptedData;
				newParams.iv = prarms.iv;
				newParams.lxSessionKey = prarms.lxSessionKey;

				let that = this;

				request.post('/wxma/getWaUserPhone',
					newParams

				).then(res => {
					console.error(res);
					if (res&&res.success) {
						 
						that.phoneNum = res.resultMap.waUserPhoneInfo.phoneNumber;
						that.ZhuceByPhone(res.resultMap.waUserPhoneInfo.phoneNumber);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				});
			},
			async ZhuceByPhone(phone) {
				const that = this;
				let params = {
					phone: phone,
					openid: that.openId,
					unionid: that.unionid,

				};
				that.canSave = false;
				const res = await request.post('/wxma/register',
					params, {
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							platType: "slb",
							mpType: "engineer",
						}
					}
				);

				if (res.success) {
					//当前页直接登录
					// uni.navigateTo({
					//     url:'/pages/index/auth'
					// })
					uni.showToast({
						title: '请稍后',
						icon: 'none'
					})
					this.loginAgain();
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}

				console.warn(res);
			},
			//退出登录时,先自动登录一次,看用户绑定过没有,没有才去注册.
			loginFirst(){
				let that = this;
				uni.showToast({
					title: '请稍后',
					icon: 'none'
				})
				that.canSave = false;
				uni.login({
					success(res) {
						that.loginByCodeOnce(res.code);
					},
					fail(res) {
				
						uni.hideLoading();
					}
				});
			},
			loginAgain() {
				let that = this;
				uni.login({
					success(res) {
						that.loginByCode(res.code);
					},
					fail(res) {

						uni.hideLoading();
					}
				});
			},
			loginByCodeOnce(frontId) {
				const that = this;
				uni.setStorageSync('loginStatus', 'false');
				wx.getUserInfo({
					success: function(res) {
						console.error(res);
						request.post("/slbMpAutoLogin", {
							code: frontId,
							appType: 'ma',
							encryptedData: res.encryptedData,
							iv: res.iv
						}, {
							login: false,
							warn: false,
							loading: false
						}).then(res2 => {
							console.error(res2);
							if (res2.success) {
								//登录成功
								uni.setStorageSync('loginStatus', 'true');
								uni.setStorageSync('userMap', JSON.stringify(res2.resultMap));
								uni.setStorageSync('userNo', res2.resultMap.accountName);
								uni.removeStorageSync('loginOut');
								that.getUserInfo();
								
							} else {
								//
								that.getLxSessionKey(that.phoneData);
								// that.ZhuceByPhone(that.phoneNum)
								// that.canSave = true;
								
								//登录失败,
			
			
							}
							console.error(res2);
						});
			
			
					}
				})
			},
			loginByCode(frontId) {
				const that = this;
				uni.setStorageSync('loginStatus', 'false');
				wx.getUserInfo({
					success: function(res) {
						console.error(res);
						request.post("/slbMpAutoLogin", {
							code: frontId,
							appType: 'ma',
							encryptedData: res.encryptedData,
							iv: res.iv
						}, {
							login: false,
							warn: false,
							loading: false
						}).then(res2 => {
							if (res2.success) {
								//登录成功
								uni.setStorageSync('loginStatus', 'true');
								uni.setStorageSync('userMap', JSON.stringify(res2.resultMap));
								uni.setStorageSync('userNo', res2.resultMap.accountName);
								uni.removeStorageSync('loginOut');
								that.getUserInfo();
								
							} else {
								//
								uni.showToast({
									title: res2.msg,
									icon: 'none'
								})
								that.canSave = true;
								
								//登录失败,


							}
							console.error(res2);
						});


					}
				})
			},
			getUserInfo() {
				let that = this;
				request.post('/slbWxma/getPersonlInfo', {

				}).then(res => {
					that.canSave = true;
					if (res&&res.success) {
						
						that.personInfo = res.resultMap.userInfo || {};
						uni.setStorageSync('userInfo', JSON.stringify(res.resultMap.userInfo));
						that.goBack();
					}else{
						uni.showToast({
							title: '登录超时,请再试一次',
							icon: 'none'
						})
					}
					// uni.navigateBack();
					console.warn(res);
				})

			},
			}
		}
</script>

<style lang="scss" scoped>
	.isHidden {
		visibility: hidden;
	}

	.template-edit {}

	/* 胶囊*/
	.tn-custom-nav-bar__back {
		width: 60%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		box-sizing: border-box;
		// background-color: rgba(0, 0, 0, 0.15);
		border-radius: 1000rpx;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		// color: #FFFFFF;
		font-size: 18px;

		.icon {
			display: block;
			flex: 1;
			margin: auto;
			text-align: center;
		}

		&:before {
			content: " ";
			width: 1rpx;
			height: 110%;
			position: absolute;
			top: 22.5%;
			left: 0;
			right: 0;
			margin: auto;
			transform: scale(0.5);
			transform-origin: 0 0;
			pointer-events: none;
			box-sizing: border-box;
			opacity: 0.7;
			background-color: #FFFFFF;
		}
	}

	/* 底部悬浮按钮 start*/
	.tn-tabbar-height {
		min-height: 100rpx;
		height: calc(120rpx + env(safe-area-inset-bottom) / 2);
	}

	.tn-footerfixed {
		position: fixed;
		width: 100%;
		bottom: calc(30rpx + env(safe-area-inset-bottom));
		z-index: 1024;
		box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0);

	}

	/* 底部悬浮按钮 end*/
</style>