<template>
	<view class="content_box flex_col" :style="{backgroundImage: `url(${loginBg})`}">
		<view class="primary-description">
			<view class="container-title flex_cen">TMS运输管理系统</view>
			<view class="container-subTitle flex_cen">上海运匠信息科技有限公司</view>
		</view>
		<!-- 登录按钮 -->
		<view class="user-login flex_center">
			<!-- #ifdef MP -->

			<view
				style="position: absolute; bottom: 244rpx; height: 250rpx; width:100%;display: flex; flex-direction: column; justify-content: space-between;"
				v-if="!isVerifLogin">
				<button class="wx-loginBtn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
					v-if="userAuth">一键登录</button>
				<button class="wx-loginBtn" @click="onClick" v-else>一键登录</button>
				<button class="wx-loginBtn" @click="isVerifLogin = true">手机验证码登录</button>
			</view>


			<!-- #endif -->

			<view class="loginH5" v-if="isVerifLogin">
				<u--form :model="formData" :rules="rules" ref="myForm" errorType='tost'>
					<u-form-item prop="phone">
						<u-input type="number" v-model="formData.phone" placeholder="请输入手机号" />
					</u-form-item>
					<u-form-item prop="authCode">
						<u-input type="number" v-model="formData.authCode" maxlength="6" border="none" placeholder="验证码" />
						<u-button slot="right" @click="getAuthCode" :text="tips" type="success" size="mini"
							:disabled="disabled" />
					</u-form-item>
					<u-code ref="uCode" @change="onTipsChange" seconds="60" @start="disabled" @end="disabled" />
				</u--form>
				<button class="h5-loginBtn" @click="verifyCodeLogin">手机验证码登录</button>
				<!-- #ifdef MP -->
				<view class="h5-back" @click="isVerifLogin = false">
					返回上一级
				</view>
				<!-- #endif -->
			</view>

		</view>
		<!-- 用户隐私协议 -->
		<bs-userPrivacy ref="userPrivacy" @onAuthChange="onAuthChange" />
	</view>
</template>

<script>
	import {
		userLogin,
		SendMessage
	} from '../../api/apiList.js'
	const loginBehavior = require('../../mixins/loginBehavior.js')
	import {
		MINI,
		LOGIN_ACTION,
		ENV_MODEL,
		TokenPrefix
	} from '../../publicConfig/config.js'

	export default {
		mixins: [loginBehavior],
		data() {
			return {
				loginBg: '', //登录页面背景图
				tips: '获取验证码',
				disabled: false, //是否禁用获取验证码
				formData: {
					phone: '', //电话号码
					authCode: '' //验证码
				},
				rules: { // 校验规则
					'phone': {
						required: true
					},
					'authCode': {
						required: true
					}
				},
				userAuth: false,
				isVerifLogin: false,
				// #ifdef H5
				isVerifLogin: true
				// #endif
			};
		},
		onLoad() {
			// #ifdef H5
			this.loginBg = 'static/img/bg/loginBg.png'
			// #endif
			// #ifdef MP
			let base64Png = uni.getFileSystemManager().readFileSync("static/img/bg/loginBg.png", 'base64');
			this.loginBg = 'data:image/jpg;base64,' + base64Png
			// #endif
		},
		methods: {
			sendMessage() {
				const {
					projectMini
				} = getApp().globalData
				SendMessage({
					phone: this.formData.phone,
					entryName: projectMini
				}).then(() => {
					setTimeout(() => {
						uni.hideLoading();
						uni.$u.toast('验证码已发送'); // 该提示会被this.start()方法中的提示覆盖						
						this.$refs.uCode.start(); // 开启倒计时
					}, 1000);
				})
			},
			onClick(e) {
				uni.showToast({
					title: '请先详细阅读用户协议并同意授权',
					icon: 'none',
					duration: 2000
				})
			},
			onAuthChange(value) {
				this.userAuth = value
			},
			//微信授权,获取登录手机号
			getPhoneNumber(e) {
				const _this = this
				const errMsg = e.detail.errMsg
				const {
					loginAction,
					projectMini
				} = getApp().globalData
				if (errMsg == "getPhoneNumber:ok") { //允许授权
					const data = {
						code: e.detail.code,
						entryName: projectMini
					}
					uni.login({
						success: (res) => {
							try {
								let pagePath = getApp().globalData.backPagePath //获取回退页面
								if(uni.getStorageSync('backUrl')){
									pagePath = uni.getStorageSync('backUrl');
									uni.removeStorageSync('backUrl')
								}
								uni.setStorageSync(`${TokenPrefix}_XSRFToken`, '') //清除 XSRFToken	
								userLogin(loginAction, res.code, data).then(res => {
									let token = res.data.renewedToken
									if (res.header['Set-Cookie']) {
										const XSRFToken = res.header['Set-Cookie'].split(';')[0].split('=')[1]
										uni.setStorageSync(`${TokenPrefix}_XSRFToken`, XSRFToken);
									}
									uni.setStorageSync(`${TokenPrefix}_token`, token);
									uni.setStorageSync('cookies', res.cookies)
									if (pagePath) {
										uni.reLaunch({
											url: pagePath
										}) //可跳转至任意页面 							
									} else {
										uni.showToast({
											title: '登录成功！',
											duration: 1000
										})
										setTimeout(() => {
											uni.switchTab({
												url: "/pages/index/index",
											})
										}, 1500)
									}
									// _this.onUpdateLocation()
								}).catch(err => {
									uni.showToast({
										title: err.message || err,
										icon: 'none',
										duration: 3000
									})
								})
							} catch (e) {
								console.log(e)
							}
						}
					})
				} else { //用户拒绝授权
					// #ifdef H5
					uni.showToast({
						title: '您取消了授权',
						icon: 'none',
						duration: 1000
					})
					// #endif
					
					// #ifdef MP
					uni.switchTab({
						url: "/pages/index/index",
					})
					// #endif
				}
			},

			//提示文本
			onTipsChange(text) {
				this.tips = text;
			},
			//获取手机验证码
			getAuthCode() {
				if (!this.userAuth) return this.onClick()
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					this.sendMessage()

				} else {
					uni.$u.toast('请稍候重试 !');
				}
			},

            verifyCodeLogin2() {
				uni.switchTab({
				url: "/pages/index/index"
					})
			},
			//手机验证码登录
			verifyCodeLogin() {
				const _this = this
				if (!_this.userAuth) {
					uni.showToast({
						title: '请先详细阅读用户协议并同意授权',
						icon: 'none',
						duration: 2000
					})
					return
				}
				_this.$refs.myForm.validate().then(result => {
					const {
						phone,
						authCode
					} = _this.formData
					const {
						loginAction,
						projectMini
					} = getApp().globalData
					const data = {
						phone,
						authCode,
						entryName: projectMini
					}
					const isWxBrowser = getApp().isWxBrowser()
					let pagePath = getApp().globalData.backPagePath //获取回退页面
					if(uni.getStorageSync('backUrl')){
						pagePath = uni.getStorageSync('backUrl');
						uni.removeStorageSync('backUrl')
					}
					let newCode = ''
					if (isWxBrowser) {
						const {
							code
						} = _this.getH5Code()
						newCode = code
					}
					// 	uni.login({
					// 		success: (res) => {

					// 			newCode = res.code


					// 		}
					// 	})
					// }
					//#ifdef H5

					userLogin(loginAction, newCode, data).then(res => {
						let token = res.data.renewedToken
						let XSRFToken = _this.getCookies('XSRF-TOKEN')
						uni.setStorageSync(`${TokenPrefix}_token`, token);
						uni.setStorageSync(`${TokenPrefix}_XSRFToken`, XSRFToken);
						if (pagePath) {
							uni.reLaunch({
								url: pagePath
							}) //可跳转至任意页面 							
						} else {
							uni.showToast({
								title: '登录成功！',
								duration: 1000
							})
							setTimeout(() => {
								uni.switchTab({
									url: "/pages/index/index",
								})
							}, 1500)
						}
					}).catch(err => {
						uni.showToast({
							title: err.message || err,
							icon: 'none',
							duration: 3000
						})
					})
					//#endif

					//#ifdef MP
					uni.login({
						success: (res) => {
							userLogin(LOGIN_ACTION.h5, res.code, data).then(res => {
								let token = res.data.renewedToken
								uni.setStorageSync(`${TokenPrefix}_XSRFToken`, '') //清除 XSRFToken
								uni.setStorageSync(`${TokenPrefix}_token`, token);
								if (res.header['Set-Cookie']) {
									const XSRFToken = res.header['Set-Cookie'].split(';')[0].split('=')[1]
									uni.setStorageSync(`${TokenPrefix}_XSRFToken`, XSRFToken);
								}
								uni.setStorageSync('cookies', res.cookies)
								if (pagePath) {
									uni.reLaunch({
										url: pagePath
									}) //可跳转至任意页面 							
								} else {
									uni.showToast({
										title: '登录成功！',
										duration: 1000
									})
									setTimeout(() => {
										uni.switchTab({
											url: "/pages/index/index",
										})
									}, 1500)
								}
							}).catch(err => {
								uni.showToast({
									title: err.message || err,
									icon: 'none',
									duration: 3000
								})
							})
						}
					})

					//#endif

				}).catch(errors => {
					console.log(errors)
					uni.showToast({
						title: '手机号或验证码不可为空',
						icon: 'none',
						duration: 1000
					})
				})
			},
		}
	}
</script>

<style lang="scss">
	.content_box {
		color: #FFFFFF;
		letter-spacing: 6rpx;
		background-size: 100%;
		background-repeat: no-repeat;
		padding: 0 32rpx;

		.primary-description {
			font-size: 28rpx;
			line-height: 40rpx;
			margin-top: 158rpx;

			.container-title {
				font-size: 60rpx;
				line-height: 84rpx;
				// margin-bottom: 38rpx;
				margin-top: 79rpx;
			}
		}


		.user-login {
			width: 90%;
			margin: 0 auto;
			letter-spacing: 4rpx;
			flex-grow: 1;
			min-height: 692rpx;
			position: relative;

			.wx-loginBtn,
			.h5-loginBtn {
				width: 690rpx;
				height: 96rpx;
				line-height: 96rpx;
				color: #FFFFFF;
				font-size: 32rpx;
				font-weight: bolder;
				border-radius: 48rpx;
				background-color: #2E75E6;
				border: none !important;
				left: 50%;
				transform: translateX(-50%);
				&:after{
					border: none;
				}
			}

			.h5-loginBtn {
				position: absolute;
				bottom: 0rpx;
			}
			.h5-back{
				position: absolute;
				bottom: 200rpx;
				color: #2E2EE6;
				left: 50%;
				transform: translateX(-50%);
				text-decoration: underline;
			}

			.loginH5 {
				margin: auto;

				/deep/.u-form-item__body {
					padding: 6rpx 40rpx;
					border-radius: 48rpx;
					margin-bottom: 40rpx;
					background: rgba(225, 225, 225, .2);

					.u-input {
						padding: 16rpx !important;
						border: none;
					}

					.input-placeholder {
						font-size: 32rpx;
					}
				}

				.h5-loginBtn {
					color: #FFFFFF;
					margin-top: 100rpx;
					background: linear-gradient(136deg, #2E75E6 0%, #2E2EE6 100%);
				}
			}
		}
	}
</style>
