<template>
	<view class="container">
		<view style="height: 140rpx;"></view>
		<view class="title">
			<text class="title--text">欢迎使用源享住</text>
		</view>
		<view v-if="quickLogin" class="quick-login">
			<!-- #ifdef MP-WEIXIN -->
			<u-button text="本机号码一键登录" :openType="openType" @getphonenumber="getPhoneNumber" @click="checkAgree"
				shape="circle" color="#de9db7"></u-button>
			<!-- #endif -->

			<!-- #ifdef MP-ALIPAY -->
			<button class="quick-login--alipay" :openType="openTypeAlipay" :scope="scopeAlipay" @click="checkAgree"
				@getAuthorize="getPhoneNumberAlipay" @error="handleAuthError">本机号码一键登录</button>
			<!-- #endif -->
		</view>
		<view v-else class="phone-login">
			<view class="phone-login--tel">
				<u-input prefixIcon="account" placeholder="请输入手机号" shape="circle" v-model="phone" clearable
					type="number" maxlength="11" placeholderStyle="color: #FFFFFF" color="#FFFFFF"
					prefixIconStyle="color: #FFFFFF"></u-input>
			</view>
			<view class="phone-login--code">
				<u-input prefixIcon="lock" placeholder="请输入验证码" shape="circle" v-model="verificationCode" type="number"
					maxlength="4" placeholderStyle="color: #FFFFFF" color="#FFFFFF" prefixIconStyle="color: #FFFFFF">
					<template slot="suffix">
						<u-code ref="uCode" @change="codeChange" seconds="60" startText="点击发送"></u-code>
						<u-button class="verification-btn" @click="getVerificationCode" color="#de9db7" shape="circle"
							size="mini" :text="tips"></u-button>
					</template>
				</u-input>
			</view>
			<view class="phone-login--btn">
				<u-button @click="phoneLogin" text="登录" shape="circle" color="#de9db7"></u-button>
			</view>
		</view>
		<view class="other-phone">
			<u-text :text="changeLoginTypeText" size="24rpx" color="#FFFFFF;" align="center"
				@click="quickLogin=!quickLogin"></u-text>
		</view>
		<view class="agree">
			<checkbox-group @change="checkboxChange">
				<label>
					<!-- #ifdef MP-WEIXIN -->
					<checkbox style="transform:scale(0.75)" color="#9e97c3" />
					<!-- #endif -->

					<!-- #ifdef MP-ALIPAY -->
					<checkbox style="transform:scale(0.75)" color="#FFFFFF" />
					<!-- #endif -->

					<text>请阅读并同意源享住</text>
					<text @click.stop="gotoProtocol">《用户协议》</text>
					<text>和</text>
					<text @click.stop="gotoProtocol">《隐私条款》</text>
				</label>
			</checkbox-group>
		</view>
		<view class="version">
			<u-text :text="version" align="right"></u-text>
		</view>
	</view>
</template>

<script>
	import {
		numberNotZero,
		stringHasText,
		jsonParamIsTrue,
	} from '../../utils/commonUtils.js'
	import {
		IMG_BASE_URL
	} from '../../config.js'
	import {
		mapMutations,
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				iconSrc: IMG_BASE_URL + '/icon.png',
				phone: '',
				tips: '',
				verificationCode: '',
				agree: false,
				hotelId: null,
				version: '',
				quickLogin: true,
			}
		},
		computed: {
			...mapState('m_user', ['token', 'userInfo', 'lastLoginPhone']),
			...mapState('m_business', ['currentHotel']),
			openType() {
				return this.agree ? 'getPhoneNumber' : ''
			},
			// #ifdef MP-ALIPAY
			openTypeAlipay() {
				return this.agree ? 'getAuthorize' : ''
			},
			scopeAlipay() {
				return this.agree ? 'phoneNumber' : ''
			},
			// #endif
			changeLoginTypeText() {
				return this.quickLogin ? '使用其他手机号登录' : '手机号快速登录'
			}
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateLastLoginPhone']),
			...mapMutations('m_business', ['updateCurrentHotel']),
			checkboxChange() {
				this.agree = !this.agree
			},
			gotoLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},
			gotoProtocol() {
				uni.navigateTo({
					url: '/subpkg/protocol/protocol'
				})
			},
			checkAgree() {
				if (!this.agree) {
					uni.showModal({
						content: "请同意相关条款，勾选后代表您同意《用户协议》、《隐私条款》",
						confirmText: "我知道了",
						showCancel: false
					})
				}
			},
			async getPhoneNumber(e) {
				// console.log("获取手机号", e);
				if (e.detail.errMsg === 'getPhoneNumber:ok') {

					let res = await uni.$http.post('/userInfo/login', {
						code: e.detail.code,
						platform: "WECHAT"
					})
					if (res.data.code === 200 && res.data.success === true) {
						await this.afterLoginSuccess(res)
					}
					//登录失败
					else {
						uni.$showMsg(res.data.msg)
					}
				} else if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {

				}
				console.log(e)
			},
			// #ifdef MP-ALIPAY
			async getPhoneNumberAlipay(e) {
				// console.log("getPhoneNumberAlipay", e);

				let cipherText = await my.getPhoneNumber({
					protocols: {
						isvAppId: "2021004141650063"
					}
				})
				// console.log("cipherText", cipherText);

				let res = await uni.$http.post('/userInfo/login', {
					code: cipherText.response,
					platform: "ALIPAY"
				})

				if (res.data.code === 200 && res.data.success === true) {
					await this.afterLoginSuccess(res)
				}
				//登录失败
				else {
					uni.$showMsg(res.data.msg)
				}

			},
			handleAuthError(e) {
				// console.log("handleAuthError", e.detail.errorMessage);
				if (e.detail.errorMessage === "用户取消授权") {
					uni.showModal({
						title: "提示",
						content: "本机号码一键登录功能需要授权，取消授权将无法使用一键登录功能",
						confirmText: "我知道了",
						showCancel: false
					})
				}
			},
			// #endif
			async phoneLogin() {
				if (!this.agree) {
					uni.showModal({
						content: "请同意相关条款，勾选后代表您同意《用户协议》、《隐私条款》",
						confirmText: "我知道了",
						showCancel: false
					})
					return
				}
				//没有输入验证码
				let codeLength = this.verificationCode.length
				if (!numberNotZero(codeLength)) {
					uni.$showMsg('请输入验证码')
					return;
				}
				if (codeLength < 4) {
					uni.$showMsg('验证码格式错误')
					return;
				}
				//输入4位数字验证码
				const res = await uni.$http.post(`/login`, {
					phone: this.phone,
					verificationCode: this.verificationCode,
				})
				console.log(res)
				if (res.data.code === 200 && res.data.success === true) {
					await this.afterLoginSuccess(res)
				}
			},
			async afterLoginSuccess(res) {
				let userInfo = res.data.data.userInfo
				//是否跳过人证比对
				let params = JSON.parse(res.data.data.params)
				console.log(params)
				if (params && jsonParamIsTrue(params.skipIdMatching)) {
					userInfo.skipIdMatching = true
				} else {
					userInfo.skipIdMatching = false
				}
				//是否调用人脸动态检测
				if (params && jsonParamIsTrue(params.staticFaceCheck)) {
					userInfo.staticFaceCheck = true
				} else {
					userInfo.staticFaceCheck = false
				}
				//是否可以选择酒店
				if (params && jsonParamIsTrue(params.selectHotel)) {
					userInfo.selectHotel = true
				} else {
					userInfo.selectHotel = false
				}
				//是否为测试账号
				if (params && jsonParamIsTrue(params.isDebug)) {
					userInfo.isDebug = true
				} else {
					userInfo.isDebug = false
				}
				//保存用户信息至local storage
				this.updateUserInfo(res.data.data.userInfo)
				//保存token
				this.updateToken(res.data.data.tokenValue)
				//上次登录的手机号
				this.updateLastLoginPhone(this.phone)
				//设置酒店信息
				if (this.hotelId) {
					await this.setHotelInfoById(this.hotelId)
				}
				//当前用户没设置身份证号则跳转
				if (this.currentHotel && this.currentHotel != {}) {
					uni.switchTab({
						url: '/pages/home/home'
					})
				} else {
					uni.reLaunch({
						url: '/subpkg/chooseHotel/chooseHotel?source=home'
					})
				}
			},
			async getVerificationCode() {
				var pattern = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
				if (!pattern.test(this.phone)) {
					uni.$showMsg("手机号格式错误! ")
					return;
				}
				if (this.$refs.uCode.canGetCode) {
					this.$refs.uCode.start()
					const res = await uni.$http.get(`/verificationCode/${this.phone}`)
					if (res.statusCode == 200 && res.data.data === true) {
						// uni.$showMsg("验证码发送成功！")
					} else {
						uni.$showMsg('验证码发送失败！')
					}
				} else {
					uni.$showMsg('请倒计时结束后再发送！')
				}
			},
			codeChange(e) {
				if (e.length > 4 && e != '获取验证码')
					e = e.substring(0, e.length - 5) + 's'
				this.tips = e;
			},
			async setHotelInfoById(hotelId) {
				let res = await uni.$http.post('/hotel', {
					hotelId: hotelId,
					pageNo: 1,
					pageSize: 2
				})
				let hotelList = res.data.data.records
				if (hotelList.length === 1) {
					this.updateCurrentHotel(hotelList[0])
				} else {
					this.updateCurrentHotel({})
				}
			},
		},
		async onLoad(query) {
			// #ifdef MP-WEIXIN
			//二维码扫描时传入hotelId
			if (query.q !== null && query.q !== undefined) {
				let url = decodeURIComponent(query.q)
				let hotelId = url.split('=')[1]
				if (stringHasText(hotelId)) {
					try {
						this.hotelId = Number(hotelId)
					} catch (err) {
						this.hotelId = null
					}
				}
				//未登录则在登录后查询hotelId是否存在对应酒店
				//已登录则直接查询
				if (this.token) {
					await this.setHotelInfoById(this.hotelId)
				}
			} else {
				this.hotelId = null
			}

			//设置版本号,只有正式版本可以获取到
			const accountInfo = wx.getAccountInfoSync();
			this.version = accountInfo.miniProgram.version

			// #endif

			// #ifdef MP-ALIPAY
			this.hotelId = uni.getStorageSync('hotelIdTemp')
			if (stringHasText(this.hotelId)) {
				if (stringHasText(this.token)) {
					this.hotelId = Number(this.hotelId)
					await this.setHotelInfoById(this.hotelId)
				}
			}
			// #endif

			this.phone = this.lastLoginPhone
			if (stringHasText(this.token)) {
				uni.switchTab({
					url: '/pages/home/home'
				})
			}
		},
		// #ifdef MP-WEIXIN
		onShareAppMessage(info) {
			return {
				title: '源享住',
				path: 'pages/quickLogin/quickLogin',
				imageUrl: "/static/logo.png"
			}
		},
		onShareTimeline(info) {}
		// #endif
	}
</script>

<style>
	.u-input__content__field-wrapper__field {
		background-color: transparent;
	}
</style>

<style lang="scss" scoped>
	page {
		.container {
			width: 100vw;
			height: 100vh;
			background-image: url("../../static/login.jpg");
			background-size: cover;
			background-repeat: no-repeat;

			.title {
				height: 160rpx;
				display: flex;
				justify-content: center;
				padding-top: 300rpx;

				.title--text {
					font-size: 40rpx;
					color: #FFFFFF;
					letter-spacing: 6rpx;
				}
			}

			.quick-login {
				margin: 0 100rpx;
				padding-top: 40rpx;
				padding-bottom: 20rpx;

				.quick-login--alipay {
					border-top-left-radius: 200rpx;
					border-bottom-left-radius: 200rpx;
					border-top-right-radius: 200rpx;
					border-bottom-right-radius: 200rpx;
					background-color: #de9db7;
					color: #FFFFFF;
					border: 0;
					padding: 0;
				}
			}

			.phone-login {
				.phone-login--tel {
					margin: 0 100rpx 50rpx 100rpx;
				}

				.phone-login--code {
					margin: 0 100rpx 50rpx 100rpx;
				}

				.phone-login--btn {
					margin: 0 100rpx 50rpx 100rpx;
				}


			}

			.other-phone {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.agree {
				margin: 20rpx 60rpx;
				color: #FFFFFF;
				display: flex;
				flex-direction: row;
				align-items: center;
				position: fixed;
				bottom: 100rpx;

				checkbox-group {
					label {
						font-size: 26rpx;
						display: flex;
						flex-direction: row;
						align-items: center;
					}
				}
			}

			.version {
				position: fixed;
				bottom: 0;
				right: 20rpx;
			}
		}
	}
</style>