<template>
	<view class="container">
		<view class="authModal">
			<view class='header'>
				<image src='../../static/image/paokong/login-icon.png'></image>
				<view class="title">露天炮孔测孔仪</view>
			</view>
			<view class='content' v-if="!hasToken">
				<view class="title">手机号</view>
				<input class="uni-input" focus placeholder="请输入手机号" maxlength="11" v-model="phone" />
 
				<button class="tel-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
					<uni-icons type="phone" size="18"></uni-icons>
				</button>
			</view>

			<button class='loginBtn' type='primary' @click="wxLogin">
				授权登录
			</button>
		</view>
	</view>
</template>


<script>
	import {
		showCustomToast,
		popuper,
		storager,
		pager
	} from '../../common/util.js'
	import {
		login,
		getPhoneNumber,
		getExistedUser
	} from '../../api/login.js'
	export default {
		onLoad() {
			/**
			 * 
			 * {"errMsg":"login:ok","code":"0f1q6Tll2gxgEe4Apiml2fxzdl4q6Tlh"}
			 * {
					"encryptedData": "z47dFJgWWcFlRiN38qzwykrxraYUj/caxt8nNJb/YonFtuGtMHCirL5G/GKWs/T7UDfmREUgyJ3z9nBiuCDE9XIbDslKTO3hpdM0Lw98gVZKOMtSjbmtAYTLbkUdDn4J6RdPYLIdCF8pUaqSZxkD+41tXW1JXKYrEuLWAZ5fmxn4rV0vCsnS+ciRdUWToq8s/KkMNHb0/1nlIyho5dz5GO1ac+BNvfk0YPrgkQdvMSCzB5NAQxUfFQERyErMW9dfQeQLXpelu0F00q778V1xAgmFWFh9IFIwVUyzSsCsMQHZpDPZT8nM3l/kNPRpK50L2msSxJ9H7lp2M8oUcQDPRttPakj1TyYb3iGDs6dx4lMBA38qbw5IYvWmrXw+A7avz/o+0u0RRrUR99u+ert6V1cg8ubDbMJGDqzAPlsTt6OdzIsGNZfddVZ/HR/9vJQc5OCgnMFRVDU9S+OTZbFLHQ==", 
					"iv": "kdDnOvCrhjUS5J1vA5fK9A==", 
					"signature": "7b9c21a62909b06fc1ba8291c808b4ec9fddde6d", 
					"userInfo": {
						"nickName": "微信用户", 
						"gender": 0, 
						"language": "", 
						"city": "", 
						"province": "", 
						"country": "", 
						"avatarUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
					}, 
					"rawData": "{\"nickName\":\"微信用户\",\"gender\":0,\"language\":\"\",\"city\":\"\",\"province\":\"\",\"country\":\"\",\"avatarUrl\":\"https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132\"}", 
					"errMsg": "getUserInfo:ok"
				}
			 */
		},
		data() {
			return {
				phone: '',
				hasToken: true
			}
		},
		mounted() {
			// this.hasToken = !!storager.get('token')
			this.getExistedUser() // 判断是否为第一次登陆
		},
		methods: {
			async getPhoneNumber(e) {
				popuper.showLoading()
				console.log(e)
				console.log(JSON.stringify(e))
				const code = e.detail.code // 动态令牌

				let res = await getPhoneNumber({
					data: {
						code
					}
				})
				console.log('res', res)
				if(res){
					this.phone = res.phoneNumber
				}
				popuper.hideLoading()
			},
			async wxLogin() {
				popuper.showLoading({
					title: '登录中...'
				})
				const loginRes = await this.getWxCode()
				if (!loginRes.code) {
					showCustomToast({
						title: 'code未获取'
					})
					return
				}
				const userInfo = await this.getUserInfo()
				if (!userInfo.iv) {
					showCustomToast({
						title: 'iv未获取'
					})
					return
				}
				await this.getToken(loginRes.code, userInfo)

			},
			getWxCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: (loginRes) => {
							console.log('loginRes: ' + JSON.stringify(loginRes));
							resolve(loginRes);
						},
						fail: (err) => reject(err) // 添加失败处理
					});
				});
			},
			getUserInfo() {
				return new Promise((resolve, reject) => {
					uni.getUserInfo({
						provider: 'weixin',
						success: (infoRes) => {
							console.log('infoRes：' + JSON.stringify(infoRes));
							resolve(infoRes);
						},
						fail: (err) => reject(err) // 添加失败处理
					});
				});
			},
			async getToken(code, userInfo) {
				popuper.hideLoading()
				let res = await login({
					data: {
						"code": code,
						"encryptedIv": userInfo.iv,
						"encryptedData": userInfo.encryptedData,
						phone: this.phone
					},
				})
				console.log('res', res)
				if (res) {
					storager.set('token', res.token)
					console.log('获取token', res.token)
					pager.relaunchTo('/pages/home/home')
				}
			},
			async getExistedUser() {
				const loginRes = await this.getWxCode()
				if (!loginRes.code) {
					showCustomToast({
						title: 'code未获取'
					})
					return
				}
				let res = await getExistedUser({
					data: {
						"code": loginRes.code,
					},
				})
				console.log('res', res)
				if (res) {
					this.hasToken = !!res.boolean
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tel-btn {
		background: #fff;
		    border: none;
		    position: absolute;
		    right: 50rpx;
		    top: -25rpx;
		    z-index: 1;

		&::after {
			border: none;
		}
	}

	.container {
		background-color: #fff;
		height: 100vh;
		overflow: hidden;
	}

	.header {
		margin-top: 340rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		gap: 33rpx;

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

		.title {
			font-family: Source Han Sans SC;
			font-weight: bold;
			font-size: 38rpx;
			color: #000000;
		}

	}

	.content {
		position: relative;
		display: flex;
		justify-content: center;
		gap: 50rpx;
		margin-top: 128rpx;

		.title {
			font-weight: bold;
			font-size: 34rpx;
			color: #000000;
		}

		input {
			font-size: 34rpx;
		}
	}

	.loginBtn {
		width: 630rpx;
		height: 88rpx;
		line-height: 88rpx;
		background: #06C15F;
		border-radius: 44rpx;
		margin-top: 172rpx;
		font-size: 34rpx;
	}
</style>