<template>
	<view style="height: 100%">
		<image mode="widthFix" src="/pages4/static/login_bg.jpg" class="full_img"></image>
		<!-- #ifdef MP-WEIXIN -->
		<u-navbar title="登录" :border-bottom="false" background="{ background: '#ffffff',opacity:0.4; }"
			title-color="#ffffff" back-icon-color="#ffffff"></u-navbar>
		<!-- #endif -->
		<view style="padding: 30rpx">
			<view style="width: 400rpx">
				<u-subsection @change="sectionChange" :list="list" :current="current" active-color="#007AFF"
					inactive-color="#ffffff" bg-color="rgba(255,255,255,0.52)"></u-subsection>
			</view>
			<view class="login_box">
				<u-form :model="form" ref="uForm1" v-show="current == 0">
					<u-form-item prop="account" v-if="!isDualAuth"><u-input type="idcard" v-model="form.account"
							placeholder-style="color:#999999" placeholder="手机号/学员身份证" /></u-form-item>
					<u-form-item prop="account" ref="account" v-else><u-input type="number" maxlength="11"
							placeholder-style="color:#999999" v-model="form.account" placeholder="手机号" /></u-form-item>
					<u-form-item prop="pwd"><u-input class="password" v-model="form.pwd"
							placeholder-style="color:#999999" type="password" placeholder="登录密码" /></u-form-item>
					<u-form-item prop="code" v-if="isDualAuth">
						<u-input v-model="form.code" type="number" placeholder-style="color:#999999"
							placeholder="验证码" />
						<u-button slot="right" size="mini" @click="getCode('account')">{{
              codeTips
            }}</u-button>
					</u-form-item>
				</u-form>
				<u-form :model="form" ref="uForm2" v-show="current == 1">
					<u-form-item prop="tel" ref="tel"><u-input type="number" maxlength="11"
							placeholder-style="color:#999999" v-model="form.tel" placeholder="手机号" /></u-form-item>
					<u-form-item prop="code">
						<u-input v-model="form.code" type="number" placeholder-style="color:#999999"
							placeholder="验证码" />
						<u-button slot="right" size="mini" @click="getCode('tel')">{{
              codeTips
            }}</u-button>
					</u-form-item>
				</u-form>
			</view>
			<button class="loginBtn" :class="{ able: canLogin() }" @click="pwlogin" v-if="current == 0">
				登录
			</button>
			<button :disabled="isUse" :class="{ able: canLogin() }" class="loginBtn" @click="sms_login"
				v-if="current == 1">
				登录
			</button>
			<view style="width: 100%; margin: 40rpx auto">
				<view style="
            display: flex;
            align-items: center;
            color: #007aff;
            font-size: 24rpx;
            justify-content: center;
          ">
					<!-- <navigator  hover-class="none" :url="'/pages2/register/register?scanCode=' + scanCode" style="margin: 0 40rpx;">立即注册</navigator> -->
					<view style="margin: 0 40rpx" @click="toRegister">立即注册</view>
					<view style="width: 3rpx; height: 20rpx; background-color: #007aff"></view>
					<navigator hover-class="none" url="/pages2/register/forget" style="margin: 0 40rpx">忘记密码</navigator>
				</view>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="wxBtn" v-if="false">
				<view class="wxBtn_title">
					<view class="line"></view>
					<view class="text">快捷登录</view>
					<view class="line"></view>
				</view>
				<button type="default" @click="quickLogin" class="wxloginBtn fl_c">
					<image mode="widthFix" src="/static/icon_phone.png"></image>
				</button>
				<!-- <button
          type="default"
          open-type="getPhoneNumber"
          @getphonenumber="wxLogin"
          class="wxloginBtn fl_c"
        >
          <image mode="widthFix" src="/static/icon_phone.png"></image>
        </button> -->
			</view>
			<!-- #endif -->
		</view>
		<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
	</view>
</template>

<script>
	const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4qkbwIKErstK1sFESPEhOShpR
pj4+sOVpJHxl5r/2xLBfA/MrXcAEra5Ro9cXNQSqmLLt8wecoLk/glfa5IdhXV0h
RVQplIVs5z3MxcUa9ptKPHUTgh8xMCBvl8sUJKwkmn4vYWeDfHT22EL7Hr1pTMwU
hF6WiNlWfQTVoF1rhwIDAQAB
-----END PUBLIC KEY-----`;
	import JSEncrypt from "@/pages4/static/jsencrypt.min.js";
	import {
		getOpenid
	} from "../../utils/authority";
	export default {
		data() {
			return {
				code: "",
				form: {
					tel: "",
					code: "",
					account: "",
					pwd: "",
				},
				list: [{
						name: "密码登录",
					},
					{
						name: "短信登录",
					},
				],
				rules: {
					tel: [{
							required: true,
							message: "请输入手机号",
							// 可以单个或者同时写两个触发验证方式
							trigger: ["change"],
						},
						{
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							},
							message: "手机号码格式不正确",
							// 触发器可以同时用blur和change
							trigger: ["change"],
						},
					],
					account: [{
						required: true,
						message: "请输入手机号/学员身份证",
						trigger: ["change"],
					}, ],
					pwd: [{
						required: true,
						message: "请输入密码",
						// 可以单个或者同时写两个触发验证方式
						trigger: ["change"],
					}, ],
					code: [{
						required: true,
						message: "请输入验证码",
						// 可以单个或者同时写两个触发验证方式
						trigger: ["change"],
					}, ],
				},
				current: 1,
				codeTips: "",
				isUse: false,
				scanCode: "", // pc端扫码登录获取的标志码
				newUser_sc: "", // 用户扫码进来详情页获取的sc
				shareActivityCode: "", // 用户扫码进来详情页获取的
				isBack: false,
				isDualAuth: false,
				isAct: "",
				bindForm: {},
			};
		},
		onLoad(option) {
			if (option.isBack) {
				this.isBack = option.isBack;
			}
			if (option.isAct) {
				this.isAct = option.isAct;
			}

			if (uni.getStorageSync("newUser_sc")) {
				this.newUser_sc = uni.getStorageSync("newUser_sc");
			}
			if (uni.getStorageSync("shareActivityCode")) {
				this.shareActivityCode = uni.getStorageSync("shareActivityCode");
			}
			this.getDualAuth();
		},
		onShow() {
			// 获取code
			// #ifdef MP-WEIXIN
			// this.getwxCode();
			// #endif
		},
		onReady() {
			this.$refs.uForm1.setRules(this.rules);
			this.$refs.uForm2.setRules(this.rules);
		},
		methods: {
			getwxCode() {
				uni.login({
					provider: "weixin",
					success: (loginRes) => {
						this.code = loginRes.code;
						console.log("获取的code:", this.code);
					},
				});
			},
			toRegister() {
				if (this.isBack) {
					uni.redirectTo({
						url: "/pages2/register/register?isBack=" +
							this.isBack +
							"&isAct=" +
							this.isAct,
					});
				} else {
					uni.navigateTo({
						url: "/pages2/register/register?isAct=" + this.isAct,
					});
				}
			},
			getDualAuth() {
				this.$api.getDualAuth().then((res) => {
					if (res.data.code == 200) {
						this.isDualAuth = res.data.data * 1;
						if (this.isDualAuth === 1) {
							this.rules.account = [{
									required: true,
									message: "请输入手机号",
									trigger: ["change"],
								},
								{
									validator: (rule, value, callback) => {
										return this.$u.test.mobile(value);
									},
									message: "手机号码格式不正确",
									trigger: ["change"],
								},
							];
						}
					}
				});
			},
			wxLogin(e) {
				this.$api
					.wxLogin({
						code: this.code,
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv,
						shareCode: this.newUser_sc,
						shareActivityCode: this.shareActivityCode,
					})
					.then((res) => {
						if (res.data.code == 200) {
							this.loginCallback(res, "wxlogin");
						} else {
							if (res.data.code == 666) {
								this.$u.toast(res.data.msg);
								setTimeout(() => {
									this.toRegister();
								}, 500);
								return;
							}
							this.getwxCode(); // code用完一次就会过期，防止用户点击取消后再点微信登录后code过期
							// this.$u.toast(res.data.msg);
						}
					});
			},
			canLogin() {
				if (this.current == 0) {
					if (this.form.account && this.form.pwd) {
						return true;
					}
					return false;
				} else if (this.current == 1) {
					if (this.form.tel && this.form.code) {
						return true;
					}
					return false;
				}
			},
			sms_login() {
				this.$refs.uForm2.validate((valid) => {
					if (valid) {
						let that = this;
						if (!this.form.tel) {
							this.$u.toast("请输入手机号码");
							return;
						}
						if (!this.form.code) {
							this.$u.toast("请输入验证码");
							return;
						}
						that.isUse = true;
						let datas = {
							shareActivityCode: this.shareActivityCode,
							tel: this.form.tel,
							code: this.form.code,
						};
						that.$api.smsLogin(datas).then(
							(res) => {
								that.isUse = false;
								if (res.data.code == 200) {
									this.loginCallback(res, "smslogin");
								} else if (res.data.code == 699) {
									uni.showModal({
										title: '温馨提示',
										content: "系统升级中，您的账号需进入浏览器粘贴才能登录",
										success: (result) => {
											if (result.confirm) {
												uni.setClipboardData({
													data: res.data.msg,
													success: function() {
														console.log('复制成功');
													}
												})
											} else if (result.cancel) {
												console.log('用户点击取消');
											}
										}
									});
								} else {
									that.$u.toast(res.data.msg);
								}
							},
							(err) => {
								that.isUse = false;
							}
						);
					}
				});
			},
			fakeLogin() {
				uni.setStorageSync("user_account", "123");
				uni.setStorageSync("token", "123");
				uni.switchTab({
					url: "/pages/index/index",
				});
			},
			/**
			 *
			 * @param {*} data
			 * @returns
			 * 加密
			 */
			encryptor(data) {
				const encrypt = new JSEncrypt();
				encrypt.setPublicKey(PUBLIC_KEY);

				return encrypt.encrypt(data);
			},
			pwlogin() {
				let that = this;
				if (!this.form.account) {
					this.$u.toast("请输入手机号码/身份证号");
					return;
				}
				if (!this.form.pwd) {
					this.$u.toast("请输入密码");
					return;
				}

				if (this.isDualAuth) {
					if (!this.form.code) {
						this.$u.toast("请输入验证码");
						return;
					}
					this.form.tel = this.form.account;
				}

				//虚拟登录
				/* that.fakeLogin()
			return */
				that.isUse = true;
				let form = JSON.parse(JSON.stringify(this.form));
				form.pwd = this.encryptor(form.pwd);
				form["shareActivityCode"] = this.shareActivityCode;
				// 账号登录用户 /app/common/account_login
				that.$api.accountLogin(form).then(
					(res) => {
						that.isUse = false;
						if (res.data.code == 200) {
							// 记住账号
							uni.setStorageSync("rememberPwLoginMsg", {
								account: this.form.account,
								pwd: this.form.pwd,
							});
							this.loginCallback(res, "pwlogin");
						} else if (res.data.code == 699) {
							uni.showModal({
								title: '温馨提示',
								content: "系统升级中，您的账号需进入浏览器粘贴才能登录",
								success: (result) => {
									if (result.confirm) {
										uni.setClipboardData({
											data: res.data.msg,
											success: function() {
												console.log('复制成功');
											}
										})
									} else if (result.cancel) {
										console.log('用户点击取消');
									}
								}
							});
						} else {
							that.$u.toast(res.data.msg);
						}
					},
					(err) => {
						that.isUse = false;
					}
				);
			},
			codeChange(text) {
				this.codeTips = text;
			},
			// 获取验证码
			getCode(key) {
				let that = this;
				if (that.$refs.uCode.canGetCode) {
					if (that.$refs[key].validateState == "success") {
						let datas = {
							tel: this.form[key]
						};
						that.$api.loginSms(datas).then(
							(res) => {
								if (res.data.code == 200) {
									that.$u.toast("验证码已发送");
									// 通知验证码组件内部开始倒计时
									that.$refs.uCode.start();
								} else {
									that.$u.toast(res.data.msg);
								}
							},
							(err) => {
								console.log(err);
							}
						);
					} else {
						this.$refs[key].onFieldChange();
					}
				}
			},
			sectionChange(index) {
				this.current = index;
				// #ifdef H5
				if (index == 0) {
					const rememberPwLoginMsg = uni.getStorageSync("rememberPwLoginMsg");
					if (rememberPwLoginMsg) {
						let {
							account,
							pwd
						} = rememberPwLoginMsg;
						this.form.account = account;
						this.form.pwd = pwd;
					}
				}
				// #endif
			},
			getPhoneNumber(e) {
				let that = this;
				uni.checkSession({
					success() {
						//session_key 未过期，并且在本生命周期一直有效
						that.putInfo(e);
					},
					fail() {
						// session_key 已经失效，需要重新执行登录流程
						uni.login({
							provider: "weixin",
							success: function(loginRes) {
								that.code = loginRes.code;
								that.putInfo(e);
							},
						});
					},
				});
			},
			putInfo(e) {
				let that = this;
				if (e.detail.encryptedData) {
					let inviteCode = uni.getStorageSync("inviteCode");
					//用户同意授权
					var datas = {
						iv: e.detail.iv,
						encryptedData: e.detail.encryptedData,
						code: that.code,
					};
					if (inviteCode) {
						datas.inviteCode = inviteCode;
					}
					that.$api.login(datas).then(
						(res) => {
							if (res.data.code == 200) {
								uni.setStorageSync("union_id", res.data.data.union_id);
								uni.setStorageSync("token", res.data.data.token);
								that.$api.getInfo({
									fromPlat: 1
								}).then((resdata) => {
									if (resdata.data.code == 200) {
										uni.navigateBack();
										that.$store.state.userInfo = resdata.data.data;
									}
								});
							} else {
								uni.showModal({
									title: "提示",
									content: res.data.msg,
									showCancel: false,
								});
							}
						},
						(err) => {
							console.log(err);
						}
					);
				}
			},
			// 微信、密码、验证码 登录成功的回调
			loginCallback(res, types) {
				// if(res.data.data && res.data.data.full_info){
				uni.removeStorageSync("newUser_sc");
				uni.removeStorageSync("shareActivityCode");
				//信息完善，直接进入页面
				uni.setStorageSync("user_account", res.data.data.user_account);
				uni.setStorageSync("token", res.data.data.token);
				// 修改邀请码
				let sac = this.$store.getters.sac;
				sac &&
					this.$api.shareActivityCode({
						shareActivityCode: sac
					}).then((res) => {
						// if (res.data.code == 200) {
						//   uni.removeStorageSync("sac");
						// }
					});
				// /app/user/getInfo 登录用户信息// fromPlat来源平台 1小程序 2PC网站
				this.$api.getInfo({
					fromPlat: 1
				}).then((resdata) => {
					if (resdata.data.code == 200) {
						this.$store.state.userInfo = resdata.data.data;
						if (this.bindForm.openId) {
							this.$api.openIdLogin({
								...this.bindForm,
								userId: resdata.data.data.userId,
							});
						}
						//
						if (!this.isBack) {
							let goPath = "";
							if (types == "wxlogin" || types == "smslogin") {
								//密码登录不用判断电脑goPath, 直接到首页
								goPath = uni.getStorageSync("goPath");
							}
							if (goPath == "course") {
								uni.redirectTo({
									url: "/pages2/wd/class",
								});
								types == "wxlogin" &&
									this.$method.setUuid(new Date().valueOf() + "");
							} else if (goPath == "bank") {
								uni.redirectTo({
									url: "/pages2/wd/question_bank",
								});
								types == "wxlogin" &&
									this.$method.setUuid(new Date().valueOf() + "");
							} else {
								console.log("登录后跳转");
								uni.removeStorageSync("h5_code");
								uni.reLaunch({
									url: "/pages/index/index?show=1",
								});
								types == "wxlogin" &&
									this.$method.setUuid(new Date().valueOf() + "");
							}
						} else {
							uni.navigateBack();
						}
					}
				});
			},
			async quickLogin() {
				let openId = await getOpenid();
				let res = await this.$api.openIdLogin({
					openId
				});
				if (res.data.code === 200) {
					this.loginCallback(res);
				} else {
					this.bindForm = {
						openId,
						unionId: uni.getStorageSync("unionId")
					};
					uni.showToast({
						icon: "none",
						title: res.data.msg + "请用密码或验证码登录！",
					});
				}
			},
		},
	};
</script>

<style scoped lang="scss">
	.wxBtn {
		position: fixed;
		bottom: 10%;
		width: 100%;
		left: 0;

		.wxBtn_title {
			display: flex; //生成浏览器兼容性代码
			width: 70%;
			margin: 0 auto 48rpx;

			.line {
				flex: 1;
				position: relative;
				top: -16rpx;
				border-bottom: 2rpx solid #d9d9d9;
			}

			.text {
				padding: 0 28rpx;
				font-size: 28rpx;
				color: #666666;
			}
		}

		.wxloginBtn {
			margin: 0 auto;
			width: 100rpx;
			height: 100rpx;
			background: #66c8f9;
			border-radius: 50%;
			border: none;
			padding: 0;

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

	/deep/ .wxBtn button::after {
		border: none;
	}

	.loginBtn {
		width: 526rpx;
		height: 80rpx;
		background: linear-gradient(90deg, #015eea, #00c0fa);
		box-shadow: 0rpx 10rpx 16rpx 4rpx rgba(1, 99, 235, 0.04);
		opacity: 0.6;
		border-radius: 40rpx;
		color: #ffffff;
		text-align: center;
		line-height: 80rpx;
		margin: 40rpx auto;

		&.able {
			opacity: 1;
		}
	}

	/deep/page {
		background-color: #ffffff;
		height: 100%;
		width: 100%;
	}

	.login_box {
		width: 100%;
		height: 360rpx;
		background: #ffffff;
		box-shadow: 0rpx 0rpx 16rpx 4rpx rgba(1, 99, 235, 0.1);
		border-radius: 24rpx;
		margin-top: 30rpx;
		padding: 40rpx 35rpx;

		.password {
			/deep/.uicon-eye-fill {
				&::before {
					color: #007aff;
					content: "\e613";
				}
			}
		}
	}

	/deep/ .u-item-bg {
		border-radius: 32px !important;
	}

	/deep/ .u-subsection {
		border-radius: 32px !important;
	}

	.full_img {
		position: absolute;
		left: 0;
		display: block;
		width: 100%;
		z-index: -999;
		top: 0;
	}

	.head {
		height: 96rpx;
		width: 100%;
		line-height: 96rpx;
		margin-top: 40rpx;
		text-align: center;
		display: flex;
		position: relative;
		justify-content: center;
	}

	.icon {
		position: absolute;
		left: 30rpx;
	}
</style>