<template>
	<view class="container">
		<u-navbar placeholder safeAreaInsetTop>
			<view class="" slot="left" v-show="hasForgot" @click="closeForgot">
				<u-icon name="arrow-left"></u-icon>
			</view>
			<view class="text-lg" slot="right" @click="handleModeChange" v-if="!hasForgot">
				{{loginText}}
			</view>
		</u-navbar>
		<view class="auth-header">
			<view class="auth-logo">
				<u-image width="80px" height="80px" src="@/static/lpg-logo.png"></u-image>
			</view>
		</view>

		<view class="loginTitleCss flex flex-direction">
			<view class="text-xxl text-bold">
				<!-- 账号密码登录 -->
				{{accountTile}}
			</view>
			<view class="margin-top-sm text-gray">
				{{accountTip}}
				<!-- 未注册手机号登录后自动生成账号 -->
			</view>
		</view>

		<view class="auth-box">
			<u-gap height="10"></u-gap>
			<!-- 登录表单 -->
			<u--form labelPosition="left" :model="formData" :rules="rules" ref="form">
				<u-form-item prop="mobile" borderBottom ref="item-mobile">
					<u-input type="text" maxlength="11" v-model="formData.mobile" clearable
						:placeholder="accountPlaceholder" border="none"></u-input>
				</u-form-item>
				<u-gap height="20"></u-gap>
				<u-form-item v-if="currentModeIndex === 1" prop="password" labelWidth="60" borderBottom
					ref="item-password">
					<u-input :type="inputType" maxlength="16" v-model="formData.password" placeholder="请输入密码"
						border="none">
						<template slot="suffix">
							<u-icon v-if="inputType === 'password'" size="20" color="#666666" name="eye-fill"
								@click="inputType = 'text';"></u-icon>
							<u-icon v-if="inputType === 'text'" size="20" color="#666666" name="eye-off"
								@click="inputType = 'password';"></u-icon>
						</template>
					</u-input>
				</u-form-item>

				<!-- <u-form-item v-else label="验证码" prop="code" labelWidth="60" borderBottom>
					<u--input type="number" maxlength="4" v-model="formData.code" border="none"
						placeholder="请填写验证码"></u--input>
					<u-button slot="right" @tap="getCode" :text="codeTips" type="success" size="mini"
						:disabled="codeDisabled"></u-button>
					
				</u-form-item> -->
				<view class="flex align-start margin-top" v-if="!hasForgot">
					<view class="radioCss">
						<u-checkbox-group v-model="checkValue" @change="groupChange" activeColor="#EA5504">
							<u-checkbox name="agree" shape="circle"></u-checkbox>
						</u-checkbox-group>
					</view>
					<view class="margin-left-xs">
						<text class="text-gray">阅读并同意</text>
						<text class="text-bold">《同城服务条款》、</text>
						<text class="text-bold">《同城隐私政策》和</text>
						<text class="text-bold">个人信息保护规则</text>
					</view>
				</view>
				<view class="margin-tb">
					<!-- <u-checkbox-group v-model="isAutoLogin" activeColor="#EA5504" v-if="currentModeIndex === 1">
						<u-checkbox  label="自动登录" name="y"></u-checkbox>
					</u-checkbox-group> -->
				</view>
				<view class="flex justify-between align-center">
					<view class="text-gray" @click="goToCodePage">
						忘记密码
					</view>
					<view class="btn-group">
						<view class="w100">
							<u-button class="auth-btn" shape="circle" :disabled="formData.mobile === ''"
								:style="{background:formData.mobile?'#EA5504':'#D5D8DF'}"
								@click="handleSubmit">{{btnText}}</u-button>
						</view>
					</view>
				</view>
				<u-code ref="uCode" @change="codeChange" seconds="60" @start="codeDisabled = true" style="height: 50px;"
					@end="codeDisabled = false"></u-code>
			</u--form>
		</view>
	</view>
</template>

<script>
	import {
		sendSmsCode
	} from '@/api/auth.js'
	import {
		decrypt
	} from '@/utils/encrypt.js'

	export default {
		data() {
			return {
				currentModeIndex: 2, //1账号密码 2验证码 3忘记密码
				inputType: 'password',
				codeDisabled: false,
				codeTips: '',
				formData: {
					mobile: '',
					password: '',
				},
				flag: true,
				rules: {
					mobile: [{
							type: 'string',
							required: true,
							message: '请输入手机号',
							trigger: ['blur', 'change']
						},
						// {
						//   // 自定义验证函数，见上说明
						//   validator: (rule, value, callback) => {
						//     // 上面有说，返回true表示校验通过，返回false表示不通过
						//     // uni.$u.test.mobile()就是返回true或者false的
						//     return uni.$u.test.mobile(value)
						//   },
						//   message: '手机号码不正确',
						//   // 触发器可以同时用blur和change
						//   trigger: ['change', 'blur']
						// }
					],
					password: {
						type: 'string',
						min: 4,
						max: 16,
						required: true,
						message: '密码长度4-16位密码',
						trigger: ['blur', 'change']
					},
					code: {
						type: 'integer',
						len: 4,
						required: true,
						message: '请填写4位验证码',
						trigger: ['blur', 'change']
					}
				},
				isAutoLogin: [], //是否自动登录
				hasForgot: false, //忘记密码
				loginText: "短信登录",
				btnText: "发送验证码",
				checkValue: ['agree'],
				accountTile: "短信验证码登录",
				accountTip: "未注册手机号登录后自动生成账号",
				accountPlaceholder: "请输入手机号",
				appid: this.$config.appid,
				openId: null
			}
		},
		onLoad(data) {
			console.log(data);
			console.log('user', JSON.parse(JSON.stringify(this.$store.state.user)));
			if (data.type) {
				this.currentModeIndex = parseInt(data.type);
			}
			this.defaultInit()
		},
		// 检测是否开启自动登录
		async onShow() {
			// #ifdef APP
			let AppToken = uni.getStorageSync('App-Token');
			let autoInformation = uni.getStorageSync('autoInformation');
			console.log(AppToken);
			if (AppToken && autoInformation) {
				this.$modal.showLoading('自动登录中...');
				console.log("存在账号信息", autoInformation);
				let {
					username,
					password
				} = autoInformation
				let decryptUser = await decrypt(username);
				let decryptPwd = await decrypt(password);
				let data = {
					mobile: decryptUser,
					password: decryptPwd
				}
				console.log("解密账号", data);
				setTimeout(() => {
					this.mobileLogin(data)
				}, 1000)
			}
			// #endif
			console.log("appid", this.appid);
			let isWechatBrowser = this.isWechatBrowser();
			this.openId = uni.getStorageSync("openId");
			console.log("openId", this.openId);
			if (isWechatBrowser) {
				if (!this.openId) {
					uni.reLaunch({
						url: '/pages/jump/weChatOffAcc'
					})
				}
			}
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			//是否有openid
			hasOpenId() {
				this.openId = uni.getStorageSync('openId');
				console.log("有openid", this.openId);
				if (this.openId) {
					this.bindWxOffAcc(this.openId)
					// 默认静默绑定 
					// this.$modal.confirm('是否绑定公众号，以便下次免登录', '温馨提示', )
					// 	.then(() => {
					// 		this.bindWxOffAcc(this.openId)
					// 	})
					// 	.catch(() => {
					// 		console.log("不绑定");
					// 		uni.removeStorageSync('openId');
					// 		uni.switchTab({
					// 			url: '/pages/home/home'
					// 		});
					// 	})
				}
			},
			bindWxOffAcc(openId) {
				this.$api.loginApi.bindOpenId({
					account: this.formData.mobile,
					openId
				}).then((res) => {
					if (res.state) {
						// 绑定成功
						uni.removeStorageSync('openId');
						uni.switchTab({
							url: '/pages/home/home'
						});
					}
				})
			},
			isWechatBrowser() {
				return /MicroMessenger/i.test(navigator.userAgent);
			},
			defaultInit() {
				if (this.currentModeIndex === 0) {
					this.btnText = '发送验证码';
					this.accountTile = "短信验证码登录";
					this.loginText = '账号密码登录';
					this.accountTip = "未注册手机号登录后自动生成账号"
				} else if (this.currentModeIndex === 1) {
					this.btnText = '登录';
					this.accountTile = "账号密码登录";
					this.loginText = '短信登录';
					this.accountTip = "请输入您的注册账号和登录密码"
				} else if (this.currentModeIndex === 2) {
					this.btnText = '发送验证码';
					this.accountTile = "短信验证码登录";
					this.loginText = '账号密码登录';
					this.accountTip = "未注册手机号登录后自动生成账号"
					this.btnText = "发送验证码"
				} else if (this.currentModeIndex === 3) {
					this.btnText = '发送验证码';
					this.accountTile = "找回密码";
					this.accountTip = "请输入需要找回密码的手机号"
					this.btnText = "发送验证码"
				}

			},
			handleModeChange() {
				console.log("当前模式", this.currentModeIndex);
				if (this.currentModeIndex === 0) {
					this.currentModeIndex = 1;
					this.btnText = '登录';
					this.loginText = '短信登录';
					this.accountTile = "账号密码登录";
					this.accountTip = "请输入您的注册账号和登录密码"
				} else if (this.currentModeIndex === 1) {
					this.currentModeIndex = 0;
					this.btnText = '发送验证码';
					this.loginText = '账号密码登录';
					this.accountTile = "短信验证码登录";
					this.accountTip = "未注册手机号登录后自动生成账号"
				} else if (this.currentModeIndex === 2) {
					this.currentModeIndex = 1;
					this.btnText = '登录';
					this.loginText = '短信登录';
					this.accountTile = "账号密码登录";
					this.accountTip = "请输入您的注册账号和登录密码"
				} else if (this.currentModeIndex === 3) {
					this.currentModeIndex = 3;
					this.btnText = '发送验证码';
					this.loginText = '账号密码登录';
					this.accountTile = "短信验证码登录";
					this.accountTip = "未注册手机号登录后自动生成账号"
				}

				// if (index !== this.currentModeIndex) {
				// 	this.currentModeIndex = index
				// 	this.$refs.form.clearValidate()
				// }
			},
			codeChange(text) {
				if (this.currentModeIndex === 0) {
					this.btnText = text
				}
			},
			getCode() {
				const mobile = this.formData.mobile
				// return
				let that = this;
				if (!mobile) {
					uni.$u.toast('请填写手机号')
				} else if (!uni.$u.test.mobile(mobile)) {
					uni.$u.toast('手机号格式不正确')
				} else if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					this.$api.loginApi.getCode({
						phone: mobile
					}).then(res => {
						if (res.code === 200) {
							console.log("已发送验证码");
							uni.hideLoading()
							uni.$u.toast('验证码已发送')
							this.$refs.uCode.start();
							setTimeout(() => {
								uni.navigateTo({
									url: `/pages/code?mobile=${mobile}&mode=${that.currentModeIndex}`
								})
							}, 500)
						}
					}).catch(e => {
						console.log(e);
						uni.hideLoading()
					})
					// sendSmsCode({
					// 	mobile: mobile,
					// 	scene: 1
					// }).then(res => {
					// 	//console.log(res)
					// 	uni.hideLoading()
					// 	uni.$u.toast('验证码已发送')
					// 	// 通知验证码组件内部开始倒计时

					// })
				} else {
					uni.$u.toast('倒计时结束后再发送')
				}
			},
			groupChange(e) {
				console.log(e);
			},
			handleSubmit() {
				if (!this.checkValue.length && !this.hasForgot) {
					uni.$u.toast('请先勾选同意');
					return;
				} else {
					this.$refs.form.validate().then(res => {
						if (this.currentModeIndex === 1) {
							this.mobileLogin(this.formData)
						} else {
							console.log("发送验证码");
							this.getCode();
						}
					})
				}
			},
			goToCodePage() {
				this.hasForgot = true;
				this.currentModeIndex = 3;
				this.defaultInit();
			},
			closeForgot() {
				this.currentModeIndex = 1;
				this.defaultInit();
				this.hasForgot = false;
			},
			// 设置免登录标识,存储免登录账号密码
			setNoLoginInformation(data) {
				// console.log("免登录",data);
				this.$store.dispatch('AutoLogin', data).then(res => {
					setTimeout(() => {
						uni.$u.toast('登录成功');
						uni.setStorageSync('myAvatorImg', '');
						uni.switchTab({
							url: '/pages/home/home'
						});
					}, 300)
				}).catch(err => {
					uni.$u.toast(err)
				})
			},
			// 清除免登录设置和账号密码
			cleanNoLoginInformation() {
				uni.removeStorageSync('autoInformation');
				uni.removeStorageSync('isAutoLogin');
			},
			mobileLogin(data) {
				this.$store.dispatch('Login', data).then(res => {
					this.$modal.closeLoading();
					setTimeout(() => {
						// uni.$u.toast('登录成功');
						uni.setStorageSync('myAvatorImg', '');
						// 只在微信浏览器环境生效并去绑定openid
						if (this.isWechatBrowser()) {
							this.hasOpenId();
						}else{
							// 非微信环境登录直接进入主页
							uni.switchTab({
								url: '/pages/home/home'
							});
						}
					}, 300)
				}).catch(err => {
					console.log("err", err);
					uni.$u.toast(err.msg)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background: #fff;
		height: 100vh;
	}

	.auth-header {
		width: 100%;
		height: 200rpx;

		.auth-logo {
			margin: 40px 0 0 40px;
		}
	}

	.auth-box {
		margin: 0 40px;

		.btn-group {
			width: 140px;
			display: flex;
			justify-content: flex-end;
			align-items: center;

			.auth-btn {
				color: #fff;
				height: 90rpx;
				font-size: 32rpx;
			}
		}
	}

	.radioCss {
		margin-top: 2px;
	}

	.loginTitleCss {
		margin: 0 40px;
	}

	/deep/.u-form-item__body__right__message {
		margin-left: 0px !important;
	}
</style>