<template>
	<view class="login-container">
		<image src="/static/logo.png" mode="" />
		<view class="title">陪护服务</view>
		<button class="auth-btn" type="default" @click="authLogin" >授权登录</button>
		<!-- <view class="form-box" v-else>
      <view class="form-item">
        <view class="label">昵称</view>
        <input type="nickname" v-model="loginForm.nickname" placeholder-class="placeholder-input" placeholder="获取昵称" />
      </view>
      <view class="form-item">
        <view class="label">手机号</view>
        <input v-model="loginForm.mobile" placeholder-class="placeholder-input" placeholder="请点击按钮获取手机号" disabled />
        <button class="phone-btn" type="default" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">获取手机号</button>
      </view>
      <button class="auth-btn" type="default" @click="registerAndLogin">注册并登录</button>
      <button class="auth-btn auth-btn-close" type="default" @click="goBack()">暂不注册</button>
    </view> -->
		<view class="privacy">
			<checkbox-group @change="checkboxChange">
				<checkbox value="agree" :checked="agree" />
			</checkbox-group>
			<text>我已阅读并同意</text>
			<text class="txt" @click="goAgreement('user_protocol')">《用户隐私协议》</text>
		</view>
		<u-popup :show="popupShow" bgColor="transparent" :safeAreaInsetBottom="false" closeOnClickOverlay
			@close="close">
			<view class="popupBox">
				<view class="popupBox_title">
					<!-- <image src="https://guess-shop.oss-cn-beijing.aliyuncs.com/static/online/img4.png" mode="" /> -->
					<!-- <image src="https://guess-shop.oss-cn-beijing.aliyuncs.com/static/online/img53.png" mode="" />
					<image class="img52" src="https://guess-shop.oss-cn-beijing.aliyuncs.com/static/online/img52.png"
						mode="" /> -->
					<view class="popupBox_title_l">
						<image src="/static/logo.png" mode="aspectFill"></image>
						<view class="name">Hi，欢迎登录</view>
					</view>
					<view class="popupBox_title_r" @click="close()">
						<span class="txt">取消</span>
					</view>
				</view>
				<view class="popupBox_content">
					<view>
						<button class="btnRed" type="default" open-type="getPhoneNumber"
							@getphonenumber="getPhoneNumber">绑定手机号</button>
						<view class="btnCancel" type="default" @click="close()">暂不绑定</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		miniappOpenId,
		miniappAuthLogin,
		miniappPhone,
		miniappAuthRegister
	} from "@/api/user.js"
	import {
		storage,
		needLoginList,
		UserInfo
	} from "@/utils/tools.js"
	export default {
		data() {
			return {
				code: undefined,
				openId: undefined,
				loginForm: {
					nickname: undefined,
					// headPhoto: undefined,
					mobile: undefined,
				},
				needLoginList: needLoginList,
				agree: false,
				popupShow: false
			}
		},
		onLoad() {
			uni.setStorageSync('apiToken', '');
		},
		methods: {
			close() {
				this.popupShow = false;
			},
			goBack() {
				uni.switchTab({
					url: '/pages/tabBar/home'
				});
			},
			authLogin() {
				if (!this.agree) return uni.$u.toast("请先仔细阅读并同意隐私政策");
				uni.showLoading({
					title: "授权中,请稍后",
				})
				uni.login({
					provider: 'weixin', //使用微信登录
					success: async (loginRes) => {
						console.log(loginRes);
						if (loginRes.errMsg && loginRes.errMsg == 'login:ok' && loginRes.code) {
							this.code = loginRes.code
							const openId = await this.getOpenId(loginRes.code)
							if (openId) {
								this.toLogin()
							}
						}
					}
				})
			},
			getOpenId(code) {
				return new Promise((resolve, reject) => {
					miniappOpenId({
						code: code
					}).then(res => {
						if (res.code === 200) {
							console.log('res===>', res)
							this.openId = res.data.openId
							resolve(res.data.openId || null)
						} else {
							resolve(null)
						}
					}).finally(() => {
						uni.hideLoading()
					})
				})
			},
			toLogin() {
				miniappAuthLogin({
					code: this.code,
					openId: this.openId,
				}).then(res => {
					console.log('res===>111', res)
					if (res.code === 200 && res.data) {
						this.successLogin(res.data.token)
					} else if (needLoginList.includes(res.code)) {
						// uni.$u.toast("暂无用户信息，请先进行注册");
						this.popupShow = true
					}
				}).catch(e => {
					console.log('e==>', e)
				})
			},
			// getChooseavatar(e) {
			//   let that = this;
			//   uni.showLoading({
			//     title: '上传中',
			//   });
			//   // console.log('获取用户头像:' + JSON.stringify(res.detail.avatarUrl));
			//   let apiUrl = uni.$u.http.config.baseURL + '/common/upload';
			//   let a = uni.uploadFile({
			//     url: apiUrl, // 仅为示例，非真实的接口地址
			//     filePath: e.detail.avatarUrl,
			//     name: 'file',
			//     success: (res) => {
			//       let newdata = JSON.parse(res.data);
			//       if (newdata.code == 200) {
			//         this.loginForm.headPhoto = newdata.data.url;
			//         uni.hideLoading();
			//       }
			//     },
			//     fail() {
			//       uni.hideLoading();
			//     },
			//   });
			// },
			getPhoneNumber(e) {
				console.log('e==>', e)
				uni.showLoading({
					title: "手机号获取中",
				})
				miniappPhone({
					openId: this.openId,
					...e.detail
				}).then(res => {
					this.loginForm.mobile = res.data.phone || null;
					// 获取 this.loginForm.mobile 后四位
					let lastFourDigits = this.loginForm.mobile.slice(-4);
					this.loginForm.nickname = '微信会员' + lastFourDigits;
					this.registerAndLogin()
				}).finally(() => {
					uni.hideLoading()
				})
			},
			registerAndLogin() {
				if (!this.loginForm.nickname) {
					return uni.$u.toast("请先获取昵称");
				}
				if (!this.loginForm.mobile) {
					return uni.$u.toast("请先获取手机号");
				}
				uni.showLoading({
					title: "注册并登录中...",
				})
				miniappAuthRegister({
					...this.loginForm,
					openId: this.openId
				}).then(result => {
					this.successLogin(result.data.token);
					this.close()
				}).finally(() => {
					uni.hideLoading()
				})
			},
			successLogin(token) {
				storage.set('apiToken', token)
				UserInfo()
				setTimeout(() => {
					// uni.switchTab({
					// 	url: '/pages/tabBar/index'
					// })
					//跳转订单页面传递参数
					getApp().globalData.switchTabParams = {
						reload: 'reload'
					};
					uni.navigateBack()
				}, 300)
			},
			checkboxChange(e) {
				this.agree = e.detail.value.includes('agree')
			},
			goAgreement(code) {
				uni.navigateTo({
					url: `/pages/mine/agreement?type=${code}`
				})
			}
		}
	}
</script>

<style>
	page {
		width: 100%;
		height: 100vh;
	}
</style>

<style lang="scss" scoped>
	.login-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		width: 100%;
		height: 100%;
		padding: 30rpx;
		box-sizing: border-box;

		>image {
			width: 210rpx;
			height: 210rpx;
			margin: 10vh auto 0;
		}

		.title {
			margin: 50rpx 0;
			font-size: 30rpx;
			text-align: center;
			font-weight: bold;
		}

		.auth-btn {
			width: 100%;
			margin-bottom: 30rpx;
			color: #fff;
			background-color: #4B91D1;
			border-radius: 40rpx;
		}

		.privacy {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;

			.txt {
				color: #4B91D1;
			}
		}

		.form-box {
			margin-bottom: 40rpx;

			.form-item {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #ccc;

				.label {
					font-size: 28rpx;
					margin-right: auto;
				}
			}

			input {
				flex: 1;
				margin-left: 30rpx;
				font-size: 28rpx;
				text-align: right;
			}

			::v-deep .placeholder-input {
				font-size: 24rpx;
			}

			button {
				margin: 0;
				font-size: 24rpx;
			}

			button::after {
				border: none;
			}

			.headPhoto-btn {
				background-color: rgba(0, 0, 0, 0);
				line-height: inherit;
				border-radius: 0;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.phone-btn {
				margin-left: 30rpx;
			}

			.auth-btn {
				width: 100%;
				margin: 20rpx 0;
				padding: 10rpx 0;
				font-size: 28rpx;
			}

			.auth-btn-close {
				border: 1rpx solid #ff4736;
				background-color: #fff;
				color: #000;

				&::after {
					border: 1rpx solid #ff4736;
				}
			}
		}

		.popupBox {
			position: relative;

			.popupBox_title {
				display: flex;
				align-items: center;
				justify-content: space-between;
				position: absolute;
				top: 0px;
				left: 0px;
				width: 100%;
				padding: 30rpx;
				box-sizing: border-box;

				.popupBox_title_l {
					display: flex;
					align-items: center;

					image {
						width: 60rpx;
						height: 60rpx;
					}

					.name {
						font-size: 36rpx;
						color: #1a1a1a;
						font-family: FZCuYuan-M03;
						margin-left: 20rpx;
					}
				}
				.popupBox_title_r{
					font-size: 28rpx;
					color: #808080;
				}
			}

			.popupBox_content {
				padding: 60rpx 0rpx 0;
				background: #F8F8F8;
				border-radius: 40rpx 40rpx 0rpx 0rpx;
				background-size: 100% 100%;
				background-position-y: -300rpx;
				padding-top: 120rpx;

				>view {
					background: #fff;
					border-radius: 40rpx 40rpx 0 0;
					position: relative;
					z-index: 20;
					padding: 80rpx 0 120rpx;
					text-align: center;

					.btnRed {
						width: 690rpx;
						height: 90rpx;
						background: #4B91D1;
						border-radius: 40rpx;
						margin: auto;
						font-size: 32rpx;
						font-family: FZZhunYuan-M02S;
						text-align: center;
						color: #ffffff;
						line-height: 90rpx;
					}

					.btnCancel {
						width: 690rpx;
						height: 90rpx;
						border-radius: 40rpx;
						background: #fff;
						font-size: 32rpx;
						font-family: FZZhunYuan-M02S;
						text-align: center;
						color: #1a1a1a;
						line-height: 90rpx;
						border: 1rpx solid #CCCCCC;
						display: inline-block;
						margin: 30rpx auto 0;
					}
				}
			}
		}
	}
</style>