<template>
	<div class="loginPage">
		<div class="lp_left">
			<img
				v-if="form.basics && form.basics.loginBanner"
				:src="form.basics.loginBanner"
			/>
			<img v-else src="@/assets/login.png" />
		</div>
		<div class="lp_right">
			<div class="lp_r_box">
				<div class="lp_r_b_logo" v-if="form.basics">
					<div>
						<el-image
							v-if="form.basics.loginLogo"
							style="width: 35px; height: 35px; border-radius: 50%"
							:src="form.basics.loginLogo"
						></el-image>
					</div>
					<span>{{ showName }}</span>
				</div>
				<span v-if="['default', 'weChat'].includes(loginType)">登录</span>
				<span v-if="['bind'].includes(loginType)">绑定账号</span>
				<div class="lp_r_b_formArea" v-loading="loading">
					<div class="fa_input" v-if="['default', 'bind'].includes(loginType)">
						<div class="fa_i_item">
							<span>账号</span>
							<div>
								<input
									type="text"
									placeholder="请输入账号"
									v-model="account"
									@change="getOrgData"
									@keyup.enter="loginFn"
								/>
							</div>
						</div>

						<div class="fa_i_item">
							<span>组织</span>
							<div>
								<el-select
									v-model="org"
									:popper-append-to-body="false"
									placeholder="请选择"
									:disabled="
										(OrgOptions.length == 1 && org) || OrgOptions.length == 0
									"
								>
									<el-option
										v-for="item in OrgOptions"
										:key="item.Uorg"
										:label="item.name"
										:value="item.Uorg"
									>
									</el-option>
								</el-select>
								<!-- <input
									type="text"
									placeholder="请输入组织号"
									v-model="org"
									@keyup.enter="loginFn"
								/> -->
							</div>
						</div>

						<div class="fa_i_item">
							<span>密码</span>
							<div>
								<input
									type="password"
									placeholder="请输入密码"
									v-model="password"
									@keyup.enter="loginFn"
								/>
							</div>
						</div>
					</div>
					<div class="fa_weChat" v-if="['weChat'].includes(loginType)">
						<div id="QRcode" class="QRcode" ref="QRcode"></div>
						<!-- @click="loginType = 'bind'" -->
					</div>
				</div>

				<div
					class="lp_r_b_btn"
					v-if="loginType == 'default'"
					@click="loginFn"
					v-loading="loading"
				>
					登录
				</div>
				<div
					class="lp_r_b_btn"
					v-if="loginType == 'weChat'"
					style="opacity: 0; cursor: default"
				>
					账号密码登录
				</div>
				<div
					class="lp_r_b_btn"
					v-if="loginType == 'bind'"
					@click="loginFn"
					v-loading="loading"
				>
					确认绑定
				</div>
				<div class="lp_r_b_line">
					<template v-if="['default', 'weChat'].includes(loginType)">
						<div></div>
						<span>其他登录方式</span>
						<div></div>
					</template>
				</div>
				<div class="lp_r_b_iconBtn">
					<div
						@click="wechatLogin"
						v-if="['default', 'weChat'].includes(loginType)"
					>
						<el-tooltip effect="dark" content="微信登录" placement="bottom">
							<img src="@/assets/login/wechat.svg" />
						</el-tooltip>
					</div>

					<div
						@click="loginType = 'default'"
						v-if="['default', 'weChat'].includes(loginType)"
					>
						<el-tooltip effect="dark" content="账号密码登录" placement="bottom">
							<img src="@/assets/login/account.svg" />
						</el-tooltip>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
import { mapActions } from "vuex";
import axios from "axios";
import qs from "qs";
import { API_CONFIG } from "@/common/apiConfig";

export default {
	name: "loginPage",
	data() {
		return {
			org: "",
			account: "",
			password: "",
			loading: false,
			loginType: "default",
			redirect: this.$route.query["redirect"],
			org2: this.$route.query["org"],
			oid: this.$route.query["oid"],
			// 组织列表
			OrgOptions: [],
			form: {},
			showName: "",
		};
	},
	methods: {
		...mapActions({
			login: "user/login",
		}),
		loginFn() {
			if (this.loading) return;

			if (this.account.length <= 0) {
				this.$message.error("请输入账号");
				return;
			}

			if (this.password.length < 6 || /[\u4e00-\u9fa5]/.test(this.password)) {
				this.$message.error("密码长度不少于6位或者密码包含特殊字符、中文");
				return;
			}

			let orgValue = this.org ? "@" + this.org : "@cocorobo.cc";
			let email = "";
			const regEmail = new RegExp(
				"^[A-Za-z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"
			);
			let str = this.account.replace(/(^\s*)|(\s*$)/g, "");

			// 判断用户输入账户带不带后缀
			if (!regEmail.test(str)) {
				email = str + orgValue;
			} else {
				email = str;
			}
			if (this.loginType == "default") {
				let params = {
					geetest_challenge: "",
					geetest_validate: "",
					geetest_seccode: "",
					loginUsername: email.trim(),
					loginPassword: window.btoa(this.password.trim()),
				};
				this.loading = true;
				axios.defaults.withCredentials = true;
				console.log("👇");
				axios
					.post("https://beta.api.cocorobo.cn/api/user", qs.stringify(params))
					.then(async (res) => {
						console.log("res", res);
						let _data = res.data[0][0];
						if (_data.active === 1) {
							window.localStorage["identity"] = JSON.stringify(_data.identity);
							this.$message.success("登录成功");
							await this.login();
							this.$router.push({ path: this.redirect || "/" });
						} else {
							this.$message.error("登录失败");
						}
						this.loading = false;
					})
					.catch((e) => {
						if (e.response && e.response.data == "Wrong email or password") {
							this.$message.error("账号或密码错误");
						} else {
							this.$message.error("登录失败");
						}
						this.loading = false;
					});
			} else if (this.loginType == "bind") {
				this.$message.info("绑定账号");
			}
		},
		async getLoading() {
			// 检查用户是否已登录
			const hasToken = this.$store.getters.token;
			if (hasToken) {
				// 如果已登录，直接重定向
				this.$router.push({ path: this.redirect || "/" });
				return;
			}
			const userid = await this.login();
			if (userid) {
				this.$router.push({ path: this.redirect || "/" });
			}
		},
		// 输入账号获取组织
		getOrgData() {
			let params = [
				{
					functionName: API_CONFIG.ajax_liYuanOrg.functionName,
					uname: this.account,
				},
			];
			this.$ajax
				.post(API_CONFIG.baseUrl, params)
				.then((res) => {
					console.log("res", res);
					this.org = "";
					this.OrgOptions = "";

					this.OrgOptions = res.data[0];
					if (this.OrgOptions.length == 1) {
						this.org = this.OrgOptions[0].Uorg;
						this.$forceUpdate();
					}
				})
				.catch((err) => {
					console.log(err);
					this.$message.error("获取组织失败");
				});
		},
		//获取组织或学校的数据
		getOrdOidData() {
			let params = [
				{
					functionName: API_CONFIG.ajax_schoolPermission.functionName, // 调用存储过程的名称
					org: this.org2, //组织id
					oid: this.oid, //学校id
				},
			];
			// 发起请求
			this.$ajax
				.post(API_CONFIG.baseUrl, params)
				.then((res) => {
					let data = res.data[0];
					console.log("data", data);
					this.form = JSON.parse(data[0].json);
					this.showName = data[0].name;
				})
				.catch((err) => {
					console.error("请求失败，错误信息：", err);
				});
		},
		wechatLogin(){
			this.loginType = 'weChat'
			setTimeout(() => {
				const randomState = Math.random().toString(36).substring(2); // 生成随机状态
				// eslint-disable-next-line no-undef
				new WxLogin({
					self_redirect:true,
					id: "QRcode", 
					appid: "wxe9d7fff3c659445f", 
					scope: "snsapi_login", 
					redirect_uri: encodeURIComponent("https://cocorobo.cn"),//https://liyuan.cocorobo.cn/#/wxTest
					state: randomState,
					style: "black",
					href: "data:text/css;base64,LmltcG93ZXJCb3gge2Rpc3BsYXk6IGZsZXg7fQouaW1wb3dlckJveCAucXJjb2RlIHt3aWR0aDogMjMycHg7IGhlaWdodDogMjMycHh9Ci5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9Ci5pbXBvd2VyQm94IC5pbmZvIHtkaXNwbGF5OiBub25lO30KLmxvZ2luUGFuZWx7d2lkdGg6MTAwJTtoZWlnaHQ6MTAwJTtkaXNwbGF5OmZsZXg7ZmxleC1kaXJlY3Rpb246Y29sdW1uO2FsaWduLWl0ZW1zOmNlbnRlcjtqdXN0aWZ5LWNvbnRlbnQ6Y2VudGVyO30KLnN0YXR1c19pY29uIHtkaXNwbGF5OiBub25lfQoud2ViX3FyY29kZV9wYW5lbF9hcmVhe2hlaWdodDoxMDAlO3dpZHRoOjEwMCU7ZGlzcGxheTpmbGV4O2FsaWduLWl0ZW1zOmNlbnRlcjtqdXN0aWZ5LWNvbnRlbnQ6Y2VudGVyO30K",
					onReady: function(isReady){
						console.log(isReady);
					}
				});
				setTimeout(() => {
					let iframe = this.$refs.QRcode.querySelector('iframe')
					iframe.style.width = '100%'
					iframe.style.height = '100%'
					
				}, 0);
				let timer = setInterval(() => {
					let iframe = this.$refs.QRcode && this.$refs.QRcode.querySelector('iframe')
					try {
						if(iframe.contentWindow.location.search.includes('code')){
							this.loginType = 'bind'
							console.log(iframe.contentWindow.location.search);
							
							clearInterval(timer)
						}
					} catch (error) {
						// console.log(error);
						
					}

				}, 50);
			},0);
		}
	},
	mounted() {
		// this.getLoading();
		this.getOrdOidData();
	},
};
</script>
<style scoped>
.loginPage {
	width: 100vw;
	height: 100vh;
	background-color: white;
	display: flex;
	align-items: center;
	justify-content: center;
}

.lp_left {
	max-width: 50%;
	width: 50%;
	max-height: 100%;
	height: 100%;
	overflow: hidden;
	box-sizing: border-box;
}

.lp_left > img {
	width: 100%;
	height: 100%;
	object-fit: cover;
	border-radius: 0 150px 0 0;
}

.lp_right {
	width: 50%;
	min-width: 520px;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}

.lp_r_box {
	width: 500px;
	height: auto;
	box-sizing: border-box;
	padding: 20px;
}

.lp_r_b_logo {
	display: flex;
	align-items: center;
}

.lp_r_b_logo > span {
	margin-left: 15px;
	font-weight: bold;
	font-size: 18px;
}

.lp_r_box > span {
	font-size: 46px;
	font-weight: bold;
	margin: 40px 0;
	display: block;
}

.lp_r_b_formArea {
	width: 100%;
	height: 250px;
	margin-bottom: 40px;
}

.fa_input {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: space-around;
}

.fa_i_item {
	width: 100%;
	height: 70px;
}

.fa_i_item > span {
	font-size: 16px;
	color: rgba(0, 0, 0, 0.9);
	font-weight: 600;
}

.fa_i_item > div {
	width: 100%;
	height: 40px;
	border: solid 1px rgba(213, 213, 213, 1);
	margin-top: 5px;
	border-radius: 8px;
	transition: 0.5s;
}

.fa_i_item > div > input {
	width: 100%;
	height: 100%;
	border: none;
	outline: none;
	text-indent: 1em;

	color: #000;
	font-size: 14px;
	background: none;
}

.fa_i_item > div >>> .el-select {
	width: 100%;
	height: 100%;
}

.fa_i_item > div >>> .el-select input {
	border: none;
	outline: none;
	background: none;
	text-indent: 1em;
	font-size: 14px;
	height: 40px;
	padding-left: 0;
	color: #000;
}

/* .fa_i_item > input {
	width: 100%;
	height: 45px;
	border: solid 1px rgba(213, 213, 213, 1);
	outline: none;
	border-radius: 8px;
	margin-top: 15px;
	text-indent: 1em;
	transition: 0.5s;
	color: #000;
	font-size: 16px;
} */

.fa_i_item > div >>> input::placeholder {
	color: rgba(142, 142, 147, 1);
}

.fa_i_item > div:focus-within {
	border-color: #006afe;
}

.fa_weChat {
	width: 300px;
	height: 300px;
	margin: 0 auto;
	display: flex;
	align-items: center;
	justify-content: center;
}

.fa_weChat > .QRcode {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
	/* background-color: black; */
}

.lp_r_b_btn {
	width: 100%;
	height: 45px;
	background-color: rgba(0, 106, 254, 1);
	border-radius: 10px;
	display: flex;
	justify-content: center;
	align-items: center;
	color: #fff;
	cursor: pointer;
	transition: 0.3s;
}

.lp_r_b_btn:hover {
	background-color: rgb(3, 87, 206);
}

.backBtn {
	background-color: #d9d9d9;
	color: #000;
}

.backBtn:hover {
	background-color: #adadad;
}

.lp_r_b_line {
	width: 100%;
	height: 20px;
	margin: 40px 0;
	display: flex;
	justify-content: center;
	align-items: center;
}

.lp_r_b_line > div {
	width: calc(100% / 2 - 70px);
	height: 1px;
	background-color: rgba(0, 0, 0, 0.3);
}

.lp_r_b_line > span {
	display: flex;
	margin: 0 20px;
}

.lp_r_b_iconBtn {
	width: 100%;
	height: 40px;
	display: flex;
	justify-content: center;
}

.lp_r_b_iconBtn > div {
	width: 32px;
	height: 32px;
	cursor: pointer;
	margin: 0 20px;
}

.lp_r_b_iconBtn > div > img {
	width: 100%;
	height: 100%;
}
</style>
