<template>
	<div class="loginPage">
		<div class="lp_left">
			<img :src="showLoginMessage.banner" />
		</div>
		<div class="lp_right">
			<div v-if="allowOrgList.findIndex((i) => i.area) == -1" @click="backVersion" class="Version">
				{{ lang.Returnoldversion }}
			</div>
			<div class="lp_r_box">			
				<div class="lp_r_b_logo">
					<div>
						<el-image
							v-if="showLoginMessage.logo"
							style="width: 35px; height: 35px; border-radius: 50%"
							:src="showLoginMessage.logo"
						></el-image>
					</div>
					<div
						style="width: 100%; display: flex; justify-content: space-between"
					>
						<div>
							<div v-if="steps == 1">
								<span v-if="showLoginMessage.name">{{
									showLoginMessage.name
								}}</span>
								<span style="margin: 0" v-else>{{ lang.KekeleboPlatform }}</span>
							</div>
						</div>
						<div v-if="steps == 2" style="cursor: pointer" @click="steps = 1,stuInfoCode = {}">
							<i style="font-size: 30px" class="el-icon-back"></i>
						</div>
					</div>
				</div>
				<template v-if="steps == 1">
					<span v-if="['default', 'weChat', 'orgL', 'code'].includes(loginType)"
						>{{ lang.login }}</span
					>
					<span v-if="['bind'].includes(loginType)">{{ lang.Bindaccount }}</span>
					<div class="lp_r_b_formArea">
						<!-- 微信绑定，账号登录，组织号登录 -->
						<div
							class="fa_input"
							v-if="['default', 'bind', 'orgL'].includes(loginType)"
						> 
							<div
								class="fa_i_item"
								style="position: relative"
								v-if="loginType == 'orgL'"
							>
								<span>{{ lang.OrganizationNumber }}</span>
								<div>
									<input
										type="text"
										:placeholder="lang.enterorgnumber"
										v-model.trim="SuffixData"
										@input="getSuffix"
									/>
								</div>
								<div
									style="
										border: none;
										font-size: 12px;
										position: absolute;
										left: 0;
										bottom: -70%;
									"
									v-if="SuffixData.trim()"
								>
									{{ orginfo.length ? orginfo[0].name : lang.schoolnotexist }}
								</div>
							</div>
							<div class="fa_i_item">
								<span>{{ lang.account }}</span>
								<div>
									<!-- @change="getOrgData" -->
									<input
										type="text"
										:placeholder="lang.enteraccount"
										v-model.trim="account"
										@keyup.enter="loginFn"
									/>
								</div>
							</div>

							<div class="fa_i_item">
								<span>{{ lang.password }}</span>
								<div>
									<input
										type="password"
										:placeholder="lang.enterpassword"
										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 class="fa_input" v-if="['code'].includes(loginType)">
							<div class="fa_i_item" style="position: relative">
								<span v-if="prefixL == 'liyuan_'">{{ lang.SelectCampus }}</span>
								<span v-else>{{ lang.OrganizationNumber }}</span>
								<!-- v-if="prefixL == 'liyuan_'" -->
								<div v-if="prefixL == 'liyuan_'">
									<el-select
										v-loading="Codeloading"
										@change="getSuffix"
										v-model.trim="SuffixData"
										:placeholder="lang.Pleaseselect"
									>
										<el-option
											v-for="item in CodeOptions"
											:key="item.code"
											:label="item.name"
											:value="item.code"
										>
										</el-option>
									</el-select>
								</div>
								<div v-else>
									<input
										type="text"
										:placeholder="lang.enterorgnumber"
										v-model.trim="SuffixData"
										@input="getrandomcodeSuffix"
									/>
								</div>
								<div
									style="
										border: none;
										font-size: 12px;
										position: absolute;
										left: 0;
										bottom: -70%;
									"
									v-if="SuffixData.trim() && prefixL != 'liyuan_'"
								>
									{{ orginfo.length ? orginfo[0].name : lang.schoolnotexist }}
								</div>
							</div>

							<div class="fa_i_item">
								<span>{{ lang.randomcode }}</span>
								<div>
									<input
										type="text"
										:placeholder="lang.Pleaseenter"
										v-model.trim="icode"
										@keyup.enter="nextSteps"
									/>
								</div>
							</div>

						</div>
					</div>

					<div
						class="lp_r_b_btn"
						v-if="['code'].includes(loginType)"
						@click="nextSteps"
						v-loading="loading"
					>
						{{ lang.confirm }}
					</div>
					<div
						class="lp_r_b_btn"
						v-if="['default', 'orgL'].includes(loginType)"
						@click="loginFn"
						v-loading="loading"
					>
						{{ lang.login }}
					</div>
					<div
						class="lp_r_b_btn"
						v-if="loginType == 'weChat'"
						style="opacity: 0; cursor: default"
					>
						{{ lang.Accpaslogin }}
					</div>
					<div class="btn_box" v-if="loginType == 'bind'">
						<div class="lp_r_b_btn" @click="loginFn" v-loading="loading">
							{{ lang.Confirmbinding }}
						</div>
						<div class="lp_r_b_btn" @click="loginType = 'default'">
							{{ lang.Returnlogin }}
						</div>
					</div>
					<div class="lp_r_b_line">
						<template
							v-if="['default', 'weChat', 'orgL', 'code'].includes(loginType)"
						>
							<div></div>
							<span>{{ lang.Otherlogin }}</span>
							<div></div>
						</template>
					</div>
					<div class="lp_r_b_iconBtn">
						<div v-if="['default', 'weChat', 'orgL', 'code'].includes(loginType)" @click="getData">
							<!-- v-if="['default', 'weChat', 'orgL', 'code'].includes(loginType)" -->
							<el-tooltip effect="dark" :content="lang.Rancodelogin" placement="bottom">
								<img
									:src="
										loginType == 'code'
											? require('../../assets/login/codel.png')
											: require('../../assets/login/code.png')
									"
									:class="[loginType == 'code' ? 'backWin' : '']"
								/>
							</el-tooltip>
						</div>

						<div
							@click="(loginType = 'orgL'), (org = '')"
							v-if="
								['default', 'weChat', 'orgL', 'code'].includes(loginType) &&
								allowOrgList.findIndex((i) => i.area) == -1
							"
						>
							<el-tooltip effect="dark" :content="lang.OrgIDLogin" placement="bottom">
								<img
									style="width: 32px; object-fit: cover"
									:src="
										loginType == 'orgL'
											? require('../../assets/login/zzl.svg')
											: require('../../assets/login/orgh.svg')
									"
									:class="[loginType == 'orgL' ? 'backWin' : '']"
								/>
							</el-tooltip>
						</div>

						<div
							@click="wechatLogin"
							v-if="['default', 'weChat', 'orgL', 'code'].includes(loginType)"
						>
							<el-tooltip effect="dark" :content="lang.WeChatLogin" placement="bottom">
								<img
									:src="
										loginType == 'weChat'
											? require('../../assets/login/wxl.svg')
											: require('../../assets/login/wxh.svg')
									"
									:class="[loginType == 'weChat' ? 'backWin' : '']"
								/>
							</el-tooltip>
						</div>

						<div
							@click="(loginType = 'default'), (SuffixData = '')"
							v-if="['default', 'weChat', 'orgL', 'code'].includes(loginType)"
						>
							<el-tooltip
								effect="dark"
								:content="lang.Accpaslogin"
								placement="bottom"
							>
								<img
									:src="
										loginType == 'default'
											? require('../../assets/login/zhl.svg')
											: require('../../assets/login/zhh.svg')
									"
									:class="[loginType == 'default' ? 'backWin' : '']"
								/>
							</el-tooltip>
						</div>
					</div>
				</template>
				<div class="stuPage" v-if="steps == 2">
					<div>{{ lang.choosename }}</div>
					<div class="stuList">
						<!-- <span v-for="i in classJuri" :key="i.userid">{{ i.name }}</span> -->
						<!-- <div v-for="i in 10" :key="i" @click="selAcc(i)">yym</div> -->
							<div
								v-for="i in classJuri"
								:key="i.userid"
								:class="[stuInfoCode.userid == i.userid ? 'stuback' : '']"
								@click="selAcc(i)"
							>
								<el-tooltip effect="dark" :content="i.name" placement="top">
									<span>
										{{ i.name }}
									</span> 
								</el-tooltip>
							</div>
					</div>
					<div v-if="!classJuri.length" class="none">{{ lang.nostudents }}</div>
					<div class="lp_r_b_btn" @click="loginCode" v-loading="loading">
						{{ lang.Confirmlogin }}
					</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";
import "@/common/wxLogin";
import { getUser, loginOut,GetSuffix } from "@/api/user";
import { myMixin } from "@/mixins/mixin.js";

export default {
	mixins: [myMixin],
	name: "loginPage",
	data() {
		return {
			// 判断显示组织号区域
			SuffixShow: false,
			// 组织号查询区域结果
			SuffixData: "",
			orginfo: [],
			CodeOptions: [],
			// 随机码
			icode: "",
			// 根据随机码获取到的课程id
			courseId: "",
			// 随机码登录获取到的课程学生列表
			classJuri: [],
			// 随机码荔园登录获code数据加载框
			Codeloading: false,
			// 随机码登录页面切换
			steps: 1,
			// 随机码选择学生账户信息登录
			stuInfoCode: {},
			// 后缀
			org: "",
			account: "",
			password: "",
			loading: false,
			loginType: "default",
			redirect: this.$route.query["redirect"],
			org2:
				this.$route.query["org"] ||
				(window.location.href.includes("/liyuan")
					? window.sessionStorage.getItem("org2")
					: ""),
			oid: this.$route.query["oid"],
			// 组织列表
			OrgOptions: [],
			form: {},
			showName: "",
			oloading: false,
			openid: "",
			allowOrgList: [
				{
					area:
						parent.location.href.includes("lyxx") ||
						parent.location.href.includes("liyuan"),
					banner:
						"https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/20250421-1139511745206807965.jpg",
					logo: "https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/image%2051744962188550.svg",
					name: "荔园小学教育集团",
					list: [
						"3823a6a5-1b6e-11f0-a66a-005056924926",
						"292e34dc-1b6e-11f0-a66a-005056924926",
						"21d6b367-1b6e-11f0-a66a-005056924926",
						"1a1a172d-1b6e-11f0-a66a-005056924926",
						"1197f86b-1b6e-11f0-a66a-005056924926",
						"f235659b-1b6d-11f0-a66a-005056924926",
						"d87b62d3-1b6d-11f0-a66a-005056924926",
						"c25ea59b-1b6d-11f0-a66a-005056924926",
					],
				},
			],
		};
	},
	watch: {
		loginType(newValue) {
			if (newValue != "weChat") {
				if (this.$refs.QRcode && this.$refs.QRcode.innerHTML) {
					this.$refs.QRcode.innerHTML = "";
				}
			}
		},
	},
	computed: {
		showLoginMessage() {
			let _result = {
				banner: require("@/assets/login2.jpg"),
				logo: "",
				name: "",
			};

			if (this.allowOrgList.findIndex((i) => i.area) != -1) {
				let _index = this.allowOrgList.findIndex((i) => i.area);
				let _obj = this.allowOrgList[_index];
				_result.banner = _obj.banner;
				_result.name = _obj.name;
				_result.logo = _obj.logo;
			}

			return _result;
		},
		userRequest() {
			console.log('this.$region',this.$region);

			let _result = this.$region == 'hk' ? 'https://cloud.api.cocorobo.hk/api/user' : 'https://beta.api.cocorobo.cn/api/user'
			
			return _result;
		},
	},
	methods: {
		...mapActions({
			login: "user/login",
			logout: "user/logout",
		}),
		// 返回旧版本
		backVersion(){
			this.$confirm(this.lang.backoldversion, this.lang.tip, {
				confirmButtonText: this.lang.confirm,
				cancelButtonText: this.lang.Cancel,
				type: "warning",
			})
			.then(() => {
				console.log(this.$region);
				if (this.$region == 'beta') {
					window.topU.location.href = 'https://beta.cloud.cocorobo.cn/index.html'
				}else if(this.$region == 'hk'){
					window.topU.location.href = 'https://cloud.cocorobo.hk/'
				}else{
					window.topU.location.href = 'https://cloud.cocorobo.cn/index.html'
				}
			})
			.catch(() => {});
		},
		// 随机码获取组织后缀
		async getrandomcodeSuffix() {
			let params = [
				{
					functionName: API_CONFIG.ajax_getliyuanCode.functionName,
					mode: this.SuffixData
				},
			];
			const res = await this.$ajax.post(API_CONFIG.baseUrl, params);
			let data = [...res.data[0], ...res.data[1]];
			console.log('data', data);
			
			if (data.length) {
				this.orginfo = data;
				this.org = this.orginfo[0].mail;
			} else {
				this.orginfo = [];
				this.org = "";
			}
		},
		// 获取组织后缀
		async getSuffix() {
			if (!this.SuffixData){
				this.orginfo = [];
				this.org = "";
				return
			} 
			let res = await GetSuffix({ mode: this.SuffixData });
			console.log("res.data[0]", res.data[0]);

			if (res.data[0].length && this.SuffixData) {
				this.orginfo = res.data[0];
				this.org = this.orginfo[0].mail;
			} else {
				this.orginfo = [];
				this.org = "";
			}
			// let res = await getliyuanCode({ mode: this.SuffixData });
			// console.log("res.data", res.data);

			// if (res.data[0].length && this.SuffixData) {
			// 	this.orginfo = res.data[0];
			// 	this.org = this.orginfo[0].mail;
			// } else {
			// 	this.orginfo = [];
			// 	this.org = "";
			// }
		},
		async loginFn() {
			if (this.loading) return;
			this.loading = true;

			// loginType == orgL为组织号登录
			if (this.loginType == "orgL" && !this.org){
				this.loading = false;
				return this.$message.error(this.lang.enterorgnumber);
			}

			// if (this.loginType != 'orgL') {
			if ((await this.getOrgData()) == 2){
				this.loading = false;
				return (this.loginType = "orgL");
			} 
			// }
			const regEmail = new RegExp(
				"^[A-Za-z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"
			);
			if (this.account.length <= 0) {
				this.$message.error(this.lang.enteraccount);
				this.loading = false;
				return;
			}

			if (this.password.length < 6 || /[\u4e00-\u9fa5]/.test(this.password)) {
				this.$message.error(this.lang.passwordlength);
				this.loading = false;
				return;
			}

			// 荔园平台登录账号进行判断
			if (this.allowOrgList.findIndex((i) => i.area) != -1) {
				let _index = this.allowOrgList.findIndex((i) => i.area);
				let _list = this.allowOrgList[_index].list;
				if (
					this.OrgOptions.find((i) => i.Uorg == this.org) &&
					!_list.includes(this.OrgOptions.find((i) => i.Uorg == this.org).id)
				) {
					this.loading = false;
					return this.$message.error(this.lang.Accountcannot);
				}
			} else {

				let mergedList = this.allowOrgList.reduce((acc, curr) => {
					return [...acc, ...curr.list];
				}, []);
				let str = this.account.replace(/(^\s*)|(\s*$)/g, "");
				console.log('regEmail.test(str)',!regEmail.test(str),this.org);
				
				if (this.OrgOptions.find((i) => i.Uorg == this.org)) {
					if (
						mergedList.includes(
							this.OrgOptions.find((i) => i.Uorg == this.org).id
						)
					) {
						this.loading = false;
						return this.$message.error(this.lang.Accountcannot);
					}
				} else {
					if (regEmail.test(str)) {
						if (this.OrgOptions.find((i) => i.Uorg == str)) {
							if (
								mergedList.includes(
									this.OrgOptions.find((i) => i.Uorg == str).id
								)
							) {
								this.loading = false;
								return this.$message.error(this.lang.Accountcannot);
							}
						}
					}else{
						this.loading = false;
						return this.$message.error(this.lang.accountnotcreated);
					}

				}
			}

			let str = this.account.replace(/(^\s*)|(\s*$)/g, "");
			if (!this.org && !regEmail.test(str)) {
				// this.$message.error(
				// 	"请在账号后添加组织后缀（账号@组织号.com 如：123456@cocorobo.com）"
				// );

				if (this.allowOrgList.findIndex((i) => i.area) != -1) {
					this.$message.error(
						this.lang.addsuffix
					);
				} else {
					this.$message.error(this.lang.accountmustOrg);
					this.loginType = "orgL";
				}
				this.loading = false;
				return;
			}

			let orgValue = this.org ? "@" + this.org : "@cocorobo.cc";
			let email = "";

			// 判断用户输入账户带不带后缀
			if (!regEmail.test(str)) {
				email = str + orgValue;
			} else {
				email = str;
			}
			if (["default", "orgL"].includes(this.loginType)) {
				let params = {
					geetest_challenge: "",
					geetest_validate: "",
					geetest_seccode: "",
					loginUsername: email.trim(),
					loginPassword: window.btoa(this.password.trim()),
				};
				axios.defaults.withCredentials = true;
				console.log("👇", this.prefixL);
				// this.addOp3('1', "", { type:this.prefixL + "login" }, "success",'0c3735c9-a2ef-11ef-9b30-005056b86db5')
				axios
					.post(this.userRequest, qs.stringify(params))
					.then(async (res) => {
						console.log("this.userRequestres", res);
						let _data = res.data[0][0];
						let userjson = await getUser({ userid: _data.userid });
						if (userjson.data[0][0].type == 2) {
							this.loading = false;
							this.$message.error(this.lang.Nologinpermission);
							return;
						}

						console.log("userjson", userjson);
						if (_data.active === 1) {
							window.localStorage["identity"] = JSON.stringify(_data.identity);
							
							window.topU.U.UF.Cookie.set("cocoroboLoginType=2");
							window.topU
								? (window.topU.US.userInfo = _data)
								: (window.parent.US.userInfo = _data);
							await this.login();
							this.$message.success(this.lang.Loginsuccessful);
							if (
								userjson.data[0][0].type == 1 &&
								userjson.data[0][0].role == 1 &&
								userjson.data[0][0].rrole == 1 &&
								this.allowOrgList.findIndex((i) => i.area) != -1
							) {
								this.$router.push({ path: "/kanban" });
							} else {
								this.$router.push({ path: this.redirect || "/" });
							}
							this.addOp3(
								"1",
								"",
								{ type: this.prefixL + "login" },
								"success",
								_data.userid
							);
						} else {
							this.$message.error(this.lang.Loginfailed);
						}
						this.loading = false;
					})
					.catch((e) => {
						if (e.response && e.response.data == "Wrong email or password") {
							this.$message.error(this.lang.Accerror);
						} else {
							this.$message.error(this.lang.Loginfailed);
						}
						this.loading = false;
					});
			} else if (this.loginType == "bind") {
				// this.$message.info("绑定账号");
				let data = await this.$ajax.post(API_CONFIG.baseUrl2 + "checkOpenId", [
					{ email: email },
				]);
				if (!data.data[0].length) {
					this.$message.error(this.lang.Nocoracc);
					this.loading = false;
					return;
				}
				if (data.data[0][0].thirdpartyid) {
					this.$message.error(this.lang.hasbeenlinked);
					this.loading = false;
					return;
				}

				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(this.userRequest, qs.stringify(params))
					.then(async (res) => {
						console.log("res", res);
						let _data = res.data[0][0];
						let userjson = await getUser({ userid: _data.userid });
						if (userjson.data[0][0].type == 2) {
							this.loading = false;
							this.$message.error(this.lang.Nologinpermission);
							return;
						}

						console.log("userjson", userjson);
						if (_data.active === 1) {
							await this.$ajax.post(API_CONFIG.baseUrl2 + "UpdateOpenId", [
								{ userid: _data.userid, openid: this.openid },
							]);
							window.localStorage["identity"] = JSON.stringify(_data.identity);
							this.$message.success(this.lang.Bindingsuc);
							window.topU.U.UF.Cookie.set("cocoroboLoginType=2");
							window.topU
								? (window.topU.US.userInfo = _data)
								: (window.parent.US.userInfo = _data);
							await this.login();
							if (
								userjson.data[0][0].type == 1 &&
								userjson.data[0][0].role == 1 &&
								userjson.data[0][0].rrole == 1 &&
								this.allowOrgList.findIndex((i) => i.area) != -1
							) {
								this.$router.push({ path: "/kanban" });
							} else {
								this.$router.push({ path: this.redirect || "/" });
							}
						} else {
							this.$message.error(this.lang.Bindingfailed);
						}

						this.loading = false;
					})
					.catch((e) => {
						console.log(e);
						
						if (e.response && e.response.data == "Wrong email or password") {
							this.$message.error(this.lang.Accerror);
						} else {
							this.$message.error(this.lang.Bindingfailed);
						}
						this.loading = false;
					});
			}
		},
		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() {
			return new Promise((resolve) => {
				let params = [
					{
						functionName: API_CONFIG.ajax_liYuanOrg.functionName,
						uname: this.account,
					},
				];
				this.$ajax
					.post(API_CONFIG.baseUrl, params)
					.then((res) => {
						console.log("res", res);
						// 组织号登陆时不清空
						if (this.loginType != "orgL") {
							this.org = "";
						}
						this.OrgOptions = [];

						let getList = res.data[0];

						// if (this.allowOrgList.findIndex((i) => i.area) != -1) {
						// 	let _index = this.allowOrgList.findIndex((i) => i.area);
						// 	let _list = this.allowOrgList[_index].list;
						// 	getList = getList.filter((i) => _list.includes(i.id));
						// } else {
						// 	let mergedList = this.allowOrgList.reduce((acc, curr) => {
						// 		return [...acc, ...curr.list];
						// 	}, []);
						// 	getList = getList.filter((i) => !mergedList.includes(i.id));
						// }

						this.OrgOptions = getList;
						if (this.OrgOptions.length == 0)
							return this.$message.error(
								this.lang.Accnotfound
							);
						if (this.loginType == "orgL") return resolve(1);

						if (this.OrgOptions.length == 1) {
							this.org = this.OrgOptions[0].Uorg;
						} else if (this.OrgOptions.length > 0) {
							// liyuan走这里
							if (this.allowOrgList.findIndex((i) => i.area) != -1) {
								// console.log('1111');
								try {
									let _index = this.allowOrgList.findIndex((i) => i.area);
									let _list = this.allowOrgList[_index].list;
									this.org = this.OrgOptions.filter((i) =>
										_list.includes(i.id)
									)[0].Uorg;
								} catch (error) {
									console.log(error);
									return this.$message.error(
										this.lang.Accountcannot
									);
								}
							} else {
								// admin走这里

								let mergedList = this.allowOrgList.reduce((acc, curr) => {
									return [...acc, ...curr.list];
								}, []);

								if (
									this.OrgOptions.filter((i) => !mergedList.includes(i.id))
										.length == 1
								)
									return this.$message.error(
										this.lang.Accountcannot
									);
								this.$message.error(this.lang.accountmustOrg);
								this.loginType = "orgL";
								return resolve(2);

							}
						}
						return resolve(1);
					})
					.catch((err) => {
						console.log(err);
					});
			});
		},
		//获取组织或学校的数据
		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 = this.form.basics.title || 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/weixin.html"), //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);
			}, 0);
		},
		// 微信登录
		async getOpenId(openid) {
			// oiztX1dwR-W2mBJ5HcvaSEB8yKGY
			axios.defaults.withCredentials = false;
			let params = {
				openid: openid,
			};
			this.openid = openid;
			axios.defaults.withCredentials = true;
			axios
				.post(this.userRequest, qs.stringify(params))
				.then(async (res) => {
					console.log("res", res);
					let _data = res.data[0][0];
					// let userData = await this.ajax.get("https://pbl.cocorobo.cn/api/pbl/selectUser/selectUser", { userid: _data.userid });
					// let _uorg = userData.data[0][0].org;
					this.account = _data.username;
					await this.getOrgData();

					// if (
					// 	(this.allowOrgList.find((i) => i.id == this.org2) &&
					// 		parent.location.href.includes("lyxx")) ||
					// 	parent.location.href.includes("liyuan")
					// ) {
					// 	let _list = this.allowOrgList.find((i) => i.id == this.org2).list;
					// 	let _nowOrgId = this.OrgOptions.find((i) => i.Uorg == this.org).id;
					// 	if (!_list.includes(_nowOrgId)) {
					// 		this.wechatLogin();
					// 		await loginOut();
					// 		await this.logout();
					// 		return this.$message.error("该组织/学校不允许登录");
					// 	}
					// 	window.sessionStorage.setItem("org2", this.org2);
					// }

					if (this.allowOrgList.findIndex((i) => i.area) != -1) {
						let _index = this.allowOrgList.findIndex((i) => i.area);
						let _list = this.allowOrgList[_index].list;
						if (
							this.OrgOptions.find((i) => i.Uorg == this.org) &&
							!_list.includes(
								this.OrgOptions.find((i) => i.Uorg == this.org).id
							)
						) {
							this.$message.error(this.lang.Accountcannot);
							this.wechatLogin();
							await loginOut();
							await this.logout();
							return
						}
					} else {
						let mergedList = this.allowOrgList.reduce((acc, curr) => {
							return [...acc, ...curr.list];
						}, []);
						if (
							mergedList.includes(
								this.OrgOptions.find((i) => i.Uorg == this.org).id
							)
						) {
							this.$message.error(this.lang.Accountcannot);
							this.wechatLogin();
							await loginOut();
							await this.logout();
							return 
						}
					}
					let userjson = await getUser({ userid: _data.userid });
					if (userjson.data[0][0].type == 2) {
						this.$message.error(this.lang.Nologinpermission);
						return;
					}

					console.log("userjson", userjson);
					if (_data.active === 1) {
						window.localStorage["identity"] = JSON.stringify(_data.identity);
						window.topU.U.UF.Cookie.set("cocoroboLoginType=2");
						window.topU
							? (window.topU.US.userInfo = _data)
							: (window.parent.US.userInfo = _data);
						await this.login();
						if (
							userjson.data[0][0].type == 1 &&
							userjson.data[0][0].role == 1 &&
							userjson.data[0][0].rrole == 1 &&
							this.allowOrgList.findIndex((i) => i.area) != -1
						) {
							this.$router.push({ path: "/kanban" });
						} else {
							this.$router.push({ path: this.redirect || "/" });
						}
						this.$message.success(this.lang.Loginsuccessful);

						this.addOp3(
							"1",
							"",
							{ type: this.prefixL + "login" },
							"success",
							_data.userid
						);
					} else {
						this.$message.error(this.lang.Loginfailed);
					}

					this.loading = false;
				})
				.catch((err) => {
					console.log('错误信息',err.response);
					if (err && err.response && err.response.status === 401) {
						this.loginType = "bind";
					}
				});

			//
		},
		backSteps() {
			this.steps = 1;
			this.account = "";
			this.password = "";
			this.stuInfoCode = {};
		},
		// 随机码登录
		nextSteps() {
			if (!this.SuffixData) {
				this.$message.error(this.prefixL == 'liyuan_' ? this.lang.choosecampus : this.lang.enterrandomcode);
				return;
			}
			let reg = /^\d+$/;
			if (!reg.test(this.icode)) {
				this.$message.error(this.lang.codecorrectly);
				return;
			}

			let params = [
				{
					functionName: API_CONFIG.ajax_selectCourseByIc2.functionName, // 调用存储过程的名称
					code: this.icode,
					oid: this.SuffixData,
				},
			];

			this.$ajax
				.post(API_CONFIG.baseUrl, params)
				.then((res) => {
					if (res.data.length && res.data[0].length) {
						this.res = res.data[0][0];
						this.courseId = res.data[0][0].courseId;
						this.getClass(res.data[0][0].classid);
					} else {
						this.$message.error(this.lang.codenotexist);
					}
				})
				.catch((err) => {
					console.error(err);
				});
		},
		// 根据随机码获取学生
		getClass(classId) {
			let params = [
				{
					functionName: API_CONFIG.ajax_selectSnameByCid.functionName, // 调用存储过程的名称
					cid: classId,
				},
			];

			this.$ajax
				.post(API_CONFIG.baseUrl, params)
				.then((res) => {
					this.classJuri = res.data[0];
					this.steps = 2;
				})
				.catch((err) => {
					console.error(err);
				});
		},
		// 选择学生账户
		selAcc(val) {
			console.log("val", val);

			this.account = val.accountNumber;
			this.password = val.userpassword;
			this.stuInfoCode = val;
		},
		// 根据随机码获取的账号登录到课程里面
		async loginCode() {
			// let courseid = this.courseId;
			try {
				await this.$confirm(
					this.lang.loginaccount.replace(/\*/g, this.stuInfoCode.username),
					this.lang.tip,
					{
						confirmButtonText: this.lang.confirm,
						cancelButtonText: this.lang.Cancel,
						type: "warning",
					}
				);
				this.loading = true;

				console.log("this.stuInfoCode", this.stuInfoCode);
				// let loginData=JSON.stringify({openid: this.stuInfoCode.userid,edu: true})

				let params = {
					geetest_challenge: "",
					geetest_validate: "",
					geetest_seccode: "",
					openid: this.stuInfoCode.userid,
					edu: true
				};
				axios.defaults.withCredentials = true;
				axios
					.post(this.userRequest, qs.stringify(params))
					.then(async (res) => {
							console.log("res", res);
							this.loading = false;

							let _data = res.data[0][0];
							let userjson = await getUser({ userid: _data.userid });

							console.log("userjson", userjson);
							if (_data.active === 1) {
								window.localStorage["identity"] = JSON.stringify(_data.identity);
								
								window.topU.U.UF.Cookie.set("cocoroboLoginType=2");
								window.topU
									? (window.topU.US.userInfo = _data)
									: (window.parent.US.userInfo = _data);
								await this.login();
								this.$message.success(this.lang.Loginsuccessful);
								
								this.$router.push({ path: this.redirect || "/", query: { courseId: this.courseId } });
								this.addOp3(
									"1",
									"",
									{ type: this.prefixL + "stuCode_login" },
									"success",
									this.stuInfoCode.userid
								);
							} else {
								this.$message.error(this.lang.Loginfailed);
							}
					})
					.catch((err) => {
						this.loading = false;
						console.error(err);
					});
			} catch (error) {
				this.loading = false;
				console.error("登录过程中出错:", error);
			}
		},
		// 获取荔园校区数据
		getData() {
			this.loginType = "code";
			this.SuffixData = '';
			this.Codeloading = true;
			let params = [
				{
					functionName: API_CONFIG.select_liYuanCampus.functionName, // 调用存储过程的名称
					org: "3823a6a5-1b6e-11f0-a66a-005056924926", //组织id
				},
			];

			// 发起请求
			this.$ajax
				.post(API_CONFIG.baseUrl, params)
				.then((res) => {
					let data = res.data[0];
					console.log(data);

					this.CodeOptions = data;
					this.Codeloading = false;
				})
				.catch((err) => {
					this.Codeloading = false;
					console.error("请求失败，错误信息：", err);
				});
		},
	},
	mounted() {
		let _this = this;
		window.addEventListener("message", function (e) {
			// 监听 message 事件
			console.log('longin',e);
			if (e.data && e.data.method == "getOpenId") {
				console.log('e',e);
				console.log('e.data.code',e.data.code);
				console.log('_this.loginType',_this.loginType);

				if (e.data.code == 200) {
					_this.getOpenId(e.data.data.openid);
				} else {
					_this.$message.error("扫码登录失败请重新扫码");
					_this.wechatLogin();
				}
			}
		});
		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: contain;
	border-radius: 0 150px 0 0;
}

.lp_right {
	width: 50%;
	min-width: 520px;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
}
.Version{
	background: #f0f4fa;
	/* border-radius: 50%; */
	border-radius: 50px 50px 50px 50px;
	/* border: .5px #cad1dc solid; */
	position: absolute;
	color: #060e17;
	padding: 8px 15px;
	box-sizing: border-box;
	top: 30px;
	right: 20px;
	cursor: pointer;
}
.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;
	/* align-items: center; */
	justify-content: center;
}

.fa_i_item {
	width: 100%;
	height: 70px;
	margin-bottom: 30px;
}

.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: #e7e7e7;
}

.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%;
}

.btn_box {
	display: flex;
	gap: 10px;
}
.stuPage {
	margin: 10px;
	max-height: 500px;
	display: flex;
	flex-direction: column;
	gap: 20px;
}
.stuList {
	flex: 1;
	display: grid;
	max-height: 400px;
	overflow: auto;
	grid-template-columns: repeat(4, 1fr);
	gap: 15px;
}
.stuList div {
	padding: 3px 15px;
	border-radius: 3px;
	-webkit-line-clamp: 1;
	line-height: 22px;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	overflow: hidden;
	text-overflow: ellipsis;
	border: 1px #e7e7e7 solid;
	text-align: center;
	cursor: pointer;
}
.stuback {
	background: #006afe;
	color: #fff;
}
/* .backWin{ */
/* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); */
/* }  */
</style>
