<template>
	<view class="p-login-index g_flex_column_start">
		<view class="g_h_60"></view>
		<view class="g_flex_row_center g_mb_10">
			<img :src="miniAppInfo.logo" alt="" class="g_w_56 g_h_56 g_radius_8" />
		</view>
		<view style="font-size: 16px; font-weight: 400; color: #919191; line-height: 25px; margin-bottom: 60px; text-align: center">
			{{ miniAppInfo.slogan || "为劳动者创造价值" }}
		</view>
		<view class="m-form g_mb_50 g_pl_40 g_pr_40">
			<view class="g_bg_f_5 g_radius_6 g_pl_16 g_pr_16 g_flex_column_center g_pt_6 g_pb_6 g_mb_20">
				<u-input maxlength="11" v-model="form.tel" type="number" class="g_fs_16" placeholder="请输入手机号" placeholder-style="color:#999999;font-size:32rpx;line-height:1" />
			</view>
			<view class="g_bg_f_5 g_radius_6 g_pl_16 g_flex_column_center g_position_rela" v-if="isLoginCode">
				<view class="g_flex_row_between">
					<view class="g_flex_1 g_mr_20 g_pt_6 g_pb_6">
						<u-input maxlength="4" v-model="msgCode.code" @input="hideKeyboard" type="number" class="g_fs_16" placeholder="请输入验证码" placeholder-style="color:#999999;font-size:32rpx;line-height:1" />
					</view>
					<view class="btn-text g_flex_column_center g_bg_f_5 g_radius_6 g_flex_none g_pt_8 g_pb_8" @click="handleSendMsg">
						<button :class="form.tel.length == 11 ? (msgCode.countdown > 0 ? 'g_c_9' : '') : 'g_c_9'" :style="form.tel.length == 11 && msgCode.countdown <= 0 ? {color: themeColor} : {}" class="btn-con g_w_126 g_flex_row_center" style="font-size: 32rpx">{{ msgCode.btnText }}</button>
					</view>
				</view>
			</view>
			<view v-if="!isLoginCode" class="g_bg_f_5 g_radius_6 g_pl_16 g_pr_16 g_flex_column_center g_pt_6 g_pb_6">
				<u-input v-model="form.pwd" type="password" class="g_fs_16" placeholder="请输入密码" placeholder-style="color:#999999;font-size:32rpx;line-height:1" />
			</view>
			<view class="g_flex_row_between" style="color: #576b95">
				<view class="g_fs_14 g_pl_16 g_mt_8 biggerSize" @click="isLoginCode = !isLoginCode">{{ isLoginCode ? "密码登录" : "验证码登录" }}</view>
			</view>
		</view>
		<view>
			<view class="g_flex_row_center">
				<rh-button  btnText="登录/注册" type="primary" @clickBtn="goHome" width="260" height="44" />
			</view>

			<!-- #ifdef MP-WEIXIN -->
			<view class="g_flex_row_center g_mt_24 g_mb_24">
				<view class="g_flex_column_center">
					<view class="bor g_w_90 g_h_1 g_border_e_b"></view>
				</view>
				<view class="g_flex_column_center g_fs_15 g_c_9 g_ml_9 g_mr_9">或</view>
				<view class="g_flex_column_center">
					<view class="bor g_w_90 g_h_1 g_border_e_b"></view>
				</view>
			</view>
			<view class="g_mt_24 g_flex_row_center g_position_rela">
				<rh-button  width="260" height="44" icon="icon-shouji" btnText="本机号码一键登录" type="default" openType="getPhoneNumber" @clickTel="getphonenumber" />
				<view class="m-mask" @click="checkCheck" v-if="!switchChecked" style="position: absolute; left: 0; top: 0; width: 100%; height: 100%"></view>
			</view>
			<!-- #endif -->
		</view>
		<view class="g_flex_column_between g_flex_1 g_pb_24" hover-class="none" hover-stop-propagation="false">
			<view class="g_fs_12 g_c_9 g_flex_row_center g_mb_32" style="align-items: center; margin-top: 16px">
				<radio-group class="dib">
					<radio :checked="switchChecked" @click="switchChange" value="0" class="dib biggerSize" :color="themeColor" style="transform: scale(0.7)" />
				</radio-group>
				我已阅读并同意
				<navigator url="/root/person/agreeUser" class="aLink" style="color: #576b95;">《用户服务协议》</navigator>
				及
				<navigator url="/root/person/agreePrive" class="aLink" style="color: #576b95;">《隐私政策》</navigator>
			</view>
			<view class="g_flex_row_center" style="text-align: center; font-size: 12px; color: #999; line-height: 32px; box-sizing: border-box">
				<view> 人海云平台 技术支持 </view>
			</view>
		</view>
	</view>
</template>

<script>
import utilsLogin from "../utils/login.js";
export default {
	onShareAppMessage() {
		return this.G.shareFun();
	},
	data() {
		return {
			miniAppInfo: {},
			themeColor: getApp().globalData.themeColor,
			svgBaseImg: this.G.store().cdnBaseImg,
			isLoginCode: true,
			form: {
				tel: "",
				pwd: "",
			},

			path: "",
			level: "",

			msgCode: {
				// 短信倒计时
				code: "",
				btnText: "获取验证码", // 6s
				countdown: 0,
				timer: null,
			},
			fromPageType: "",
			currentId: null,
			switchChecked: false,
			loading: false,
		};
	},
	onLoad(options) {
		console.log("登录页：", options);
		this.path = options.path;
		this.level = options.level;
		if (options.type) {
			this.setOptions(options);
		}
		console.log("123");
		this.getCode((res) => {
			uni.setStorageSync("apply-code", res);
		});
		this.G.clearLocalStorage();
	},
	onShow() {
		let that = this;
		utilsLogin.clearLocalStorage();
		that.initLogo();
	},
	onHide() {
		if (this.msgCode.timer) {
			clearInterval(this.msgCode.timer);
		}
	},
	methods: {
		hideKeyboard(e) {
			console.log(e);
			if (e.length >= 4) {
				console.log("123123123");
				uni.hideKeyboard();
			}
		},
		switchChange() {
			console.log(this.switchChecked);
			this.switchChecked = !this.switchChecked;
		},
		setOptions(options) {
			console.log("options", options);
			this.fromPageType = options.type;
			if (options.type == "detail") {
				this.currentId = options.id;
			}
		},
		goHome() {
			let that = this,
				url = "",
				params = {};

			console.log("this.loading1", this.loading);
			if (that.form.tel == "") {
				uni.showToast({
					title: "请输入手机号",
					icon: "none",
				});
				return false;
			}
			if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(that.form.tel)) {
				uni.showToast({
					title: "请输入正确的手机号",
					icon: "none",
				});
				return false;
			}

			if (that.isLoginCode) {
				// 验证码登录
				if (that.msgCode.code == "") {
					uni.showToast({
						title: "请输入验证码",
						icon: "none",
					});
					return false;
				}
				url = that.api.login_code;
				params = {
					tel: that.form.tel,
					code: that.msgCode.code,
					loginType: "login",
					wxCode: "",
				};
			} else {
				// 密码登录
				if (that.form.pwd == "") {
					uni.showToast({
						title: "请输入密码",
						icon: "none",
					});
					return false;
				}
				url = that.api.login_user;
				params = {
					tel: that.form.tel,
					password: that.form.pwd,
					loginType: "password",
					wxCode: "",
				};
			}
			console.log("that.switchChecked", that.switchChecked);
			if (!that.switchChecked) {
				uni.showToast({
					icon: "none",
					title: "请先同意用户及隐私协议",
				});
				return false;
			}
			console.log("this.loading", this.loading);
			if (this.loading) {
				return false;
			}
			this.loading = true; // 防止重复点击
			// #ifdef MP-WEIXIN
			uni.checkSession({
				success() {
					//session_key 未过期，并且在本生命周期一直有效
					that.loginAccount(url, params);
				},
				fail() {
					// session_key 已经失效，需要重新执行登录流程
					that.getCode((res) => {
						uni.setStorageSync("apply-code", res);
						setTimeout(() => {
							that.loginAccount(url, params);
						}, 300);
					});
				},
			});
			// #endif
			// #ifdef H5 || APP-PLUS || MP-TOUTIAO || MP-KUAISHOU
			that.loginAccount(url, params);
			// #endif
		},
		checkCheck() {
			let that = this;
			if (!that.switchChecked) {
				uni.showToast({
					icon: "none",
					title: "请先同意用户及隐私协议",
				});
				return false;
			}
		},
		loginAccount(url, params) {
			let that = this,
				_params = {};
			params.wxCode = uni.getStorageSync("apply-code");
			_params = Object.assign(params, {
				path: that.path,
			});
			console.log("登录参数：", _params, " 获取分享参数：", uni.getStorageSync("apply-jobdetail-id"));
			that.G.Get(
				url,
				_params,
				(res) => {
					console.log("登录成功：", res);
					that.loading = false;
					that.setToken(res);
				},
				(err) => {
					console.log(err);
					that.loading = false;
				}
			);
		},
		initLogo() {
			let that = this;
			this.G.Get("/yishoudan/agency/getInfo", {}, (res) => {
				let obj = { ...res.agency, ...res.weixinConfig };
				for (let key in obj) {
					if (typeof obj[key] == "string" && obj[key].indexOf("http://") > -1) {
						obj[key] = obj[key].replace("http:", "https:");
					}
				}
				uni.setStorageSync("miniApp-info", obj);
				uni.setStorageSync("pgy-agency-id", res.agency.id);
				uni.setStorageSync("ai-name", res.agency.aiRobotName);
				uni.setStorageSync("ai-logo", res.agency.aiLogo);

				that.miniAppInfo = obj;
				// app.$forceUpdate();
			});
		},
		getCode(callback = () => {}) {
			uni.login({
				success(wxRes) {
					callback(wxRes.code);
				},
				fail(res) {
					console.log(res);
				},
			});
		},
		getphonenumber(e) {
			let that = this;
			console.log(e);
			// 进行临时变量的判断, 如果在注册页面获取过手机号授权, 则不再重新获取手机号, 直接登录
			if (uni.getStorageSync("TEMPORARY_CODE")) {
				let wxRes = uni.getStorageSync("TEMPORARY_CODE");
				that.G.Get(
					that.api.login_wechat,
					{
						openId: wxRes.openId,
						tel: wxRes.phoneNumber,
						unionid: wxRes.unionid,
					},
					(res) => {
						that.setToken(res);
					}
				);
				return;
			}
			if (e.detail.code) {
				// 允许授权。拿button返回信息换取token
				uni.checkSession({
					success() {
						//session_key 未过期，并且在本生命周期一直有效
						that.loginWX(e);
					},
					fail() {
						// session_key 已经失效，需要重新执行登录流程
						that.getCode((res) => {
							uni.setStorageSync("apply-code", res);
							setTimeout(() => {
								that.loginWX(e);
							}, 300);
						});
					},
				});
			} else {
				// 拒绝授权。
			}
		},
		loginWX(e) {
			let that = this;
			that.G.Get(
				that.api.login_getWxInfo,
				{
					code: uni.getStorageSync("apply-code"),
					btnCode: e.detail.code,
					iv: e.detail.iv,
					encryptedData: e.detail.encryptedData,
				},
				(wxRes) => {
					that.G.Get(
						that.api.login_wechat,
						{
							openId: wxRes.openId,
							tel: wxRes.phoneNumber,
							unionid: wxRes.unionid,
						},
						(res) => {
							that.setToken(res);
						}
					);
				}
			);
		},
		// 处理存储token

		setToken($data) {
			let that = this;

			console.log("获取登录用户信息：", $data);
			uni.setStorageSync("apply-userinfo", $data); // 获取用户信息, 参与实际逻辑
			uni.setStorageSync("apply-userinfo-copy", JSON.stringify($data)); // 仅用于查看数据，不参与实际逻辑
			uni.setStorageSync("apply-avatar", $data.imgSrc); // 单独存储 -- 头像，方便修改
			uni.setStorageSync("apply-username", $data.userName); // 单独存储 -- 用户名，方便修改
			uni.setStorageSync("apply-tel", $data.tel); // 单独存储 -- 手机号，方便修改
			uni.setStorageSync("apply-token", $data.token); // 单独存储 -- token，方便获取
			uni.setStorageSync("apply-uid", $data.user.id); // 单独存储 -- 用户名，方便修改
			uni.setStorageSync("apply-agencyId", $data.user.agencyId); // 单独存储 -- 代理id，方便获取
			uni.setStorageSync("apply-supplierAccount", $data.supplierAccount); // 单独存储 -- 是否是发单号，方便获取 0.不是发单号 1.是发单号
			uni.removeStorageSync("TEMPORARY_CODE");

			uni.$emit("isGlogin", {
				uid: $data.user.id,
			});
			if (that.fromPageType == "detail") {
				uni.navigateBack({
					delta: 1,
				});
				return;
			}
			// 登录跳转到首页的判断
			uni.setStorageSync("SHOW_INVITE", 1);
			that.G.Get(
				that.api.user_checkPermission,
				{},
				(rea) => {
					console.log("rearearearearearea", rea);
					if (rea.hasPermission == true) {
						uni.setStorageSync("HAS_PERMISSION", 1); // 1.有权限 2.无权限
					} else {
						uni.setStorageSync("HAS_PERMISSION", 2); // 1.有权限 2.无权限
					}
					if (rea.member == true) {
						uni.setStorageSync("IS_MINIAPP_MEMBER", true); // 1.有权限 2.无权限
						if (rea.isCreatorOrAdmin == true) {
							uni.setStorageSync("IS_MINIAPP_ADMIN", true); // 1.有权限 2.无权限
						} else {
							uni.setStorageSync("IS_MINIAPP_ADMIN", false); // 1.有权限 2.无权限
						}
					} else {
						uni.setStorageSync("IS_MINIAPP_MEMBER", false); // 1.有权限 2.无权限
					}
				},
				(err) => {
					if (err) {
						uni.setStorageSync("HAS_PERMISSION", 2);
					}
				}
			);
			// return;
			uni.setStorageSync("IS_CREATOR", 1); // 1是创建者 2是普通成员
			if (that.path == "root/merchantManagement/message") {
				uni.reLaunch({
					url: "/root/merchantManagement/message",
				});
			}
			if (that.path == "") {
				uni.switchTab({
					url: "/pages/home/index",
				});
			} else if (that.path == "detail") {
				uni.navigateBack({
					delta: 1,
				});
			} else {
				// 固定跳首页
				uni.switchTab({
					url: "/pages/home/index",
				});
			}
			// that.G.Get(that.api.login_agencyInfo, {}, (aRes) => {
			// 	console.log("获取团队信息:", aRes);
			// 	uni.setStorageSync("IS_CREATOR", aRes.agency.userId == $data.user.id || $data.admin == true ? 1 : 2); // 1是创建者 2是普通成员
			// });
		},

		// 发送验证码
		handleSendMsg() {
			let that = this;
			if (this.msgCode.countdown > 0) {
				return false;
			}
			if (that.form.tel == "") {
				uni.showToast({
					title: "请输入手机号后再获取",
					icon: "none",
				});
				return false;
			}
			if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(that.form.tel)) {
				uni.showToast({
					title: "请输入正确的手机号",
					icon: "none",
				});
				return false;
			}
			that.G.Get(
				that.api.login_sendMsg,
				{
					tel: that.form.tel,
				},
				(res) => {
					that.msgCode.countdown = 60;
					that.msgCode.btnText = that.msgCode.countdown + "s";
					clearInterval(that.msgCode.timer);
					that.msgCode.timer = setInterval(() => {
						if (that.msgCode.countdown > 0) {
							that.msgCode.countdown--;
							that.msgCode.btnText = that.msgCode.countdown + "s";
						} else {
							clearInterval(that.msgCode.timer);
							that.msgCode.timer = null;
							that.msgCode.btnText = "获取验证码";
						}
					}, 1000);
				}
			);
		},
		goRegisterPwd() {
			uni.navigateTo({
				url: "/root/other/register",
			});
		},
	},
};
</script>

<style lang="scss">
.p-login-index {
	min-height: 100vh;
	/* #ifdef MP-TOUTIAO || MP-KUAISHOU */
	background-color: #fff;
	/* #endif */
	.btn-text {
		.btn-con {
			border-left: 2rpx solid #e5e5e5;
			padding: 0 32rpx;
			background-color: transparent;
			border-radius: 0;
			height: 40rpx;
			line-height: 40rpx;
		}
	}

	.tel-btn {
		width: 500rpx;
		height: 84rpx;
		border: 2rpx solid #3578f6;
		left: 50%;
		transform: translateX(-50%);
		top: 0;
		border-radius: 44rpx;
		opacity: 0;
	}

	.g-components-panel-fixed {
		border-top: none;
	}
	.biggerSize {
		position: relative;
	}
	.biggerSize::after {
		content: "";
		width: 80px;
		height: 40px;
		position: absolute;
		left: 50%;
		top: 100%;
		z-index: 99;
		transform: translate(-50%, -50%);
	}
}
</style>
