<template>
	<div>
		<el-dialog
			title="个人信息"
			:visible.sync="dialogVisibleInfo"
			:append-to-body="true"
			width="500px"
			:before-close="handleClose"
			class="dialog_diy"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<!-- :show-close="isClosed || role || info.type == 2" -->
			<div style="width: 100%; height: 100%" v-loading="digLoading">
				<div class="info_box">
					<div class="img" v-loading="imgLoading">
						<img :src="info.headportrait ? info.headportrait : avator" alt="" />
						<div v-if="info.type == 1" class="mask" @click.stop="addImg($event)">
							<img src="../assets/info/camera_icon.png" alt="" />
							<input
								type="file"
								accept="image/*"
								capture="camera"
								style="display: none"
								@change="beforeUpload($event)"
							/>
						</div>
					</div>
					<div class="infoBar">
						<span
							:style="{ color: pageCut == 0 ? '#67B1FF' : '' }"
							@click="midInfo(0)"
							>我的资料</span
						>
						<span
							:style="{ color: pageCut == 1 ? '#67B1FF' : '' }"
							@click="midInfo(1)"
							v-if="info.type == 1"
							>修改密码</span
						>
					</div>
					<div class="info_box" style="padding: 0" v-if="pageCut == 0">
						<div class="info_span">
							<span>姓名：</span>
							<el-input
								v-model="info.username"
								placeholder="请输入姓名"
							></el-input>
						</div>					

						<div class="info_span">
							<span>性别：</span>
							<el-radio-group v-model="info.sex">
								<el-radio :label="0">男</el-radio>
								<el-radio :label="1">女</el-radio>
							</el-radio-group>
						</div>

						<!-- 学生弹框数据 -->
						<template v-if="info.type == 2">
							<div class="info_span" >
								<span>组织：</span>
								<el-select disabled placeholder="请选择">
									<el-option :label="orgName"></el-option>
								</el-select>
							</div>
							<div class="info_span">
								<span>学校：</span>
								<el-select disabled placeholder="请选择">
									<el-option :label="info.sBySchool"></el-option>
								</el-select>
							</div>
							<div class="info_span">
								<span>身份：</span>
								<el-select disabled placeholder="请选择">
									<el-option label="学生"></el-option>
								</el-select>
							</div>
						</template>
						
						<template v-if="info.type == 1">
							<div
								class="info_span"
								v-for="item in teaType"
								:key="item.id"
								:class="{
									'error-text': !item.value.length,
									'error-border': !item.value.length,
								}"
							>
								<span>
									{{ item.name + "：" }}
								</span>
								<el-select
									v-model="item.value"
									multiple
									:placeholder="'请选择' + item.name"
									@change="Ochange"
								>
									<el-option
										v-for="i in item.child"
										:key="i.id"
										:label="i.name"
										:value="i.id"
									>
									</el-option>
								</el-select>
							</div>
						</template>
						

						<div class="info_span">
							<span>微信登录：</span>
							<el-button
								type="danger"
								size="small"
								@click="wxLogin"
								v-if="info.thirdpartyid"
								>取消绑定</el-button
							>
							<el-button type="primary" size="small" @click="wxLogin" v-else
								>绑定微信</el-button
							>
						</div>
						<span
							v-if="pageCut == 0 && info.type == 1"
							slot="footer"
							class="dialog-footer"
							style="width: 90%; display: flex; justify-content: flex-end"
						>
							<el-button type="primary" @click="confirm()">确 认</el-button>
							<el-button @click="close()">关 闭</el-button>
						</span>
						<!-- <div class="info_span">
							<span>简介：</span>
							<textarea
								v-autoHeight="68"
								rows="2"
								class="binfo_input binfo_textarea"
								cols
								v-model="info.intro"
								placeholder="想说点什么..."
							></textarea>
						</div> -->
					</div>
					<div v-else>
						<div class="input_box">
							<span>原密码</span>
							<el-input
								class="input"
								v-model="opassword"
								placeholder="请输入原密码"
							></el-input>
						</div>
						<div class="input_box">
							<span>输入新密码</span>
							<div style="position: relative">
								<el-input
									:type="isLook ? 'type' : 'password'"
									class="input"
									v-model="password"
									placeholder="长度为8-16位，且包含大小写字母"
								></el-input>
								<div class="eye" @click="changeEye">
									<img :src="isLook ? eye : eyeOff" alt="" />
								</div>
							</div>
						</div>
						<div class="input_box">
							<span>再次输入新密码</span>
							<div style="position: relative">
								<el-input
									:type="isLook ? 'type' : 'password'"
									class="input"
									v-model="password1"
									placeholder="请再次输入修改密码"
								></el-input>
								<div class="eye" @click="changeEye">
									<img :src="isLook ? eye : eyeOff" alt="" />
								</div>
							</div>
						</div>
						<div class="input_box">
							<div
								style="width: 100%; display: flex; justify-content: flex-end"
							>
								<el-button type="primary" @click="updatePassword"
									>保存</el-button
								>
							</div>
						</div>
					</div>
				</div>
			</div>
		</el-dialog>
		<el-dialog
			title="绑定微信"
			:visible.sync="wechatDialogVisible"
			:append-to-body="true"
			width="400px"
			:before-close="handleClose2"
			class="dialog_diy"
		>
			<div class="fa_weChat">
				<div id="QRcode" class="QRcode" ref="QRcode"></div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="wechatDialogVisible = false">关 闭</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import avator from "../assets/info/teacher.jpg";
import { API_CONFIG } from "@/common/apiConfig";
import { updatePassword, getUser } from "@/api/user";
import store from "../store";

import "@/common/wxLogin.js";

export default {
	props: ["role", "userid", "oid","orgName"],
	watch: {
		dialogVisibleInfo(newVal) {
			if (newVal) {
				this.getTypeInfo();
			}
		},
	},
	directives: {
		autoHeight: {
			update(el, binding) {
				const { value } = binding;
				if (value && typeof value === "number") {
					el.style.height = `${value}px`;
				} else {
					el.style.height = "auto";
				}
			},
			componentUpdated(el) {
				el.style.height = `${el.scrollHeight + 5}px`;
			},
		},
	},
	data() {
		return {
			avator: avator,
			info: {},
			imgLoading: false,
			classJuri: [],
			teaType: [],
			teacherType: [],
			allItems: [],
			options: [],
			typeId: "",
			typeId2: "",
			formLabelWidth: "100px",
			oidArray: ["d67940a5-510c-40ea-9c9a-2631ab03013a"],
			resultInfo: "", // 用于存储字符串
			isClosed: false,
			dialogVisibleInfo: false,
			digLoading: false,
			pageCut: 0, //0修改信息也 1修改密码页
			wechatDialogVisible: false, //微信登录弹框
			isLook: false, //密码眼睛
			opassword: "",
			password: "",
			password1: "",
			eyeOff: require("../assets/info/eyeOff.png"),
			eye: require("../assets/info/eye.png"),
		};
	},
	// mounted() {
	// 	this.getTypeInfo();
	// },
	methods: {
		cha() {
			this.$forceUpdate();
		},
		openDig() {
			this.dialogVisibleInfo = true;
			this.updateInfo();
			// this.getTypeInfo();
		},
		updatePassword() {
			const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{8,16}$/;
			if (!reg.test(this.password)) {
				this.$message.error("密码长度为8-16位，且包含大小写字母");
				return;
			} else if (this.password != this.password1) {
				this.$message.error("两次新密码不相同");
				return;
			}
			let params = {
				userid: this.userid,
				opassword: this.opassword,
				password: this.password,
			};

			updatePassword(params)
				.then((res) => {
					if (res.data[0] && res.data[0].success == 1) {
						this.$message.success("修改成功");
						this.opassword = "";
						this.password = "";
						this.password1 = "";
					} else {
						this.$message.error("修改失败,原密码不正确");
					}
				})
				.catch((err) => {
					this.$message.error("修改失败");
					console.error(err);
				});
		},
		// 密码展示与隐藏开关
		changeEye() {
			this.isLook = !this.isLook;
		},
		//切换弹框
		midInfo(type) {
			if (type == 0) {
				this.pageCut = 0;
			} else {
				this.pageCut = 1;
			}
		},
		//获取分类类名
		getTypeInfo() {
			this.digLoading = true;
			let params = [
				{
					functionName: API_CONFIG.ajax_selectPerInfoAllTea.functionName, // 调用存储过程的名称
					oid: this.oid, //学校id
				},
			];
			this.$ajax
				.post(API_CONFIG.baseUrl, params)
				.then((res) => {
					this.teaType = res.data[0];
					let typeInfo = res.data[1];

					this.teaType.forEach((e) => {
						e.child = [];
						e.value = [];
						typeInfo.forEach((i) => {
							if (e.id == i.parentid) {
								e.child.push({ id: i.id, name: i.name });
							}
						});
					});
					// console.log(this.teaType, "teaType");
					this.options = res.data[2];
					this.getData();
				})
				.catch((err) => {
					this.digLoading = false;
					console.error(err);
				});
		},
		handleClose2(done) {
			done();
		},
		handleClose(done) {
			this.typeId = "";
			this.close();
			done();
		},
		close() {
			this.typeId = "";
			this.dialogVisibleInfo = false;
			// this.$emit("update:dialogVisibleInfo", false);
		},
		generateResultInfo() {
			// 从 teaType 中提取所有的值
			const selectedValues = this.teaType.flatMap((item) => item.value);

			// 确保 typeId 是数组，将其添加到 selectedValues 中
			const combinedValues = Array.isArray(this.info.teacherOffice)
				? selectedValues.concat(this.info.teacherOffice)
				: selectedValues.concat([this.info.teacherOffice]);

			// 将合并后的数组转换为逗号分隔的字符串
			this.resultInfo = combinedValues.join(",");
		},
		confirm() {
			if (!this.panData()) {
				this.$message.error("请完善教研室分类信息");
				return;
			}
			if (!this.info.username) {
				this.$message.error("姓名不能为空！");
				return;
			}
			// let teaTypeSelections = this.teaType.map(item => ({
			//   selectedValues: item.value.join(",")  // 如果是数组，转为逗号分隔的字符串
			// }));
			this.generateResultInfo();

			let params = [
				{
					functionName: API_CONFIG.ajax_updateliyuanUserInfo.functionName, // 调用存储过程的名称
					userid: this.userid,
					username: this.info.username,
					sex: this.info.sex,
					cclassid: this.resultInfo,
					h: this.info.headportrait ? this.info.headportrait : "",
				},
			];

			console.log(params);
			this.$ajax
				.post(API_CONFIG.baseUrl, params)
				.then(() => {
					this.$message.success("修改成功");
					this.updateInfo();
					this.dialogVisibleInfo = false;
				})
				.catch((err) => {
					this.$message.error("网络不佳");
					this.dialogVisibleInfo = false;
					console.error(err);
				});
		},
		updateInfo() {
			getUser({ userid: this.userid }).then((response) => {
				console.log(response);
				// const { data } = response
				const data = response.data[0][0];
				// console.log(response)
				store.commit("user/SET_USERINFO2", data);
			});
		},
		async getData() {
			this.digLoading = true;
			let params = [
				{
					functionName: API_CONFIG.ajax_selectliyuanUserInfo.functionName, // 调用存储过程的名称
					uid: this.userid,
				},
			];

			this.$ajax
				.post(API_CONFIG.baseUrl, params)
				.then((res) => {
					this.info = res.data[0][0];
					this.info.teacherOffice = [];
					let array = [];
					for (var i = 0; i < this.options.length; i++) {
						array.push(this.options[i].id);
					}
					this.info.teacherOffice = this.arrayToArray(
						this.info.cclassid.split(","),
						array
					);
					// console.log(this.info.cclassid);
					let count = 0;
					this.teaType.forEach((e) => {
						let array2 = [];
						for (var i = 0; i < e.child.length; i++) {
							array2.push(e.child[i].id);
						}
						e.value = this.arrayToArray(this.info.cclassid.split(","), array2);
						if (e.value.length) {
							count++;
						}
					});
					if (count != this.teaType.length) {
						this.dialogVisibleInfo = true;
					}
					if (!this.panData()) {
						this.isClosed = false;
					} else {
						this.isClosed = true;
					}
					this.digLoading = false;

					this.$forceUpdate();
				})
				.catch((err) => {
					this.digLoading = false;

					console.error(err);
				});
		},
		panData() {
			let count = 0;
			this.teaType.forEach((e) => {
				if (e.value.length) {
					count++;
				}
			});
			return count == this.teaType.length;
		},
		arrayToArray(arrayo, arrayt) {
			let array1 = arrayo;
			let array2 = arrayt;

			let commonElements = [];

			for (let i = 0; i < array1.length; i++) {
				for (let j = 0; j < array2.length; j++) {
					if (array1[i] === array2[j]) {
						commonElements.push(array1[i]);
					}
				}
			}
			return commonElements;
		},
		addImg(e) {
			var el = e.currentTarget;
			el.getElementsByTagName("input")[0].click();
			e.target.value = "";
		},
		beforeUpload(event) {
			// const loading = this.openLoading();
			var file = event.target.files[0];
			var credentials = {
				accessKeyId: "AKIATLPEDU37QV5CHLMH",
				secretAccessKey: "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",
			}; //秘钥形式的登录上传
			window.AWS.config.update(credentials);
			window.AWS.config.region = "cn-northwest-1"; //设置区域

			var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
			var imgA = [
				"png",
				"jpg",
				"jpeg",
				"bmp",
				"gif",
				"webp",
				"psd",
				"svg",
				"tiff",
			];
			if (
				imgA.indexOf(file.name.split(".")[file.name.split(".").length - 1]) ==
				-1
			) {
				this.$message.error("图片格式错误");
				return;
			}
			this.imgLoading = true;
			var _this = this;

			if (file) {
				var params = {
					Key:
						file.name.split(".")[0] +
						new Date().getTime() +
						"." +
						file.name.split(".")[file.name.split(".").length - 1],
					ContentType: file.type,
					Body: file,
					"Access-Control-Allow-Credentials": "*",
					ACL: "public-read",
				}; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
				var options = {
					partSize: 2048 * 1024 * 1024,
					queueSize: 2,
					leavePartsOnError: true,
				};
				bucket
					.upload(params, options)
					.on("httpUploadProgress", function () {
						//这里可以写进度条
						// console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
					})
					.send(function (err, data) {
						_this.imgLoading = false;
						// loading.close();
						if (err) {
							_this.$message.error("上传失败");
						} else {
							_this.info.headportrait = data.Location;
							_this.$forceUpdate();

							console.log(_this.checkJson);
							console.log(data.Location);
						}
					});
			}
		},
		wxLogin() {
			if (this.info.thirdpartyid) {
				this.$confirm("确定取消绑定微信吗？", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				})
					.then(() => {
						let params = [
							{
								functionName: API_CONFIG.ajax_UpdateOpenId.functionName, // 调用存储过程的名称
								uid: this.userid,
								openid: "",
							},
						];
						this.$ajax
							.post(API_CONFIG.baseUrl, params)
							.then(() => {
								this.$message.success("取消绑定成功");
								this.getData();
							})
							.catch((err) => {
								this.$message.error("取消绑定失败");
								console.error(err);
							});
					})
					.catch(() => {});
			} else {
				this.wechatDialogVisible = true;
				this.wechatLogin();
			}
		},
		wechatLogin() {
			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);
		},
		setOpenId(openid) {
			let params = [
				{
					functionName: API_CONFIG.ajax_UpdateOpenId.functionName, // 调用存储过程的名称
					uid: this.userid,
					openid: openid,
				},
			];
			this.$ajax
				.post(API_CONFIG.baseUrl, params)
				.then(() => {
					this.$message.success("绑定成功");
					this.wechatDialogVisible = false;
					this.getData();
				})
				.catch((err) => {
					this.$message.error("绑定失败请重新扫码");
					console.error(err);
				});
		},
		Ochange() {
			this.$forceUpdate();
		},
	},
	mounted() {
		let _this = this;
		window.addEventListener("message", function (e) {
			// 监听 message 事件
			console.log(e);
			if (e.data && e.data.method == "getOpenId") {
				console.log(e);
				console.log(e.data.code);
				console.log(_this.loginType);

				if (e.data.code == 200) {
					_this.setOpenId(e.data.data.openid);
				} else {
					_this.$message.error("扫码登录失败请重新扫码");
					_this.wechatDialogVisible = false;
					setTimeout(() => {
						_this.wechatDialogVisible = true;
						_this.wechatLogin();
					}, 1000);
				}
			}
		});
	},
};
</script>

<style scoped>
.dialog_diy >>> .el-dialog {
	/* height: 100%; */
	margin: 10vh auto !important;
}

.dialog_diy >>> .el-dialog__header {
	background: #454545 !important;
	padding: 15px 20px;
}

.dialog_diy >>> .el-dialog__body {
	height: calc(100% - 124px);
	box-sizing: border-box;
	padding: 0px;
}

.dialog_diy >>> .el-dialog__title {
	color: #fff;
}

.dialog_diy >>> .el-dialog__headerbtn {
	top: 19px;
}

.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close {
	color: #fff;
}

.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close:hover {
	color: #fff;
}

.dialog_diy >>> .el-dialog__body,
.dialog_diy >>> .el-dialog__footer {
	background: #fafafa;
}

.info_box {
	width: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 30px 0;
}

.info_box > .img {
	width: 80px;
	height: 80px;
	overflow: hidden;
	border-radius: 50%;
	position: relative;
}

.info_box > .img:hover > .mask {
	display: flex;
}

.info_box > .img > .mask {
	cursor: pointer;
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	/* display: flex; */
	align-items: center;
	justify-content: center;
	display: none;
}

.info_box > .img > .mask > img {
	width: 20px;
}

.info_box > .img > img {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.binfo_input {
	width: 100%;
	margin: 0;
	padding: 12px 14px;
	display: block;
	min-width: 0;
	outline: none;
	box-sizing: border-box;
	background: none;
	border: none;
	border-radius: 4px;
	background: #fff;
	font-size: 16px;
	resize: none;
	font-family: "Microsoft YaHei";
	min-height: 48px;
	/* border: 1px solid #3682fc00; */
	border: 1px solid #c0c4cc;
}

.binfo_textarea {
	border: 1px solid #c0c4cc;
	font-size: 16px;
	resize: none;
	/* background: #f6f6f6; */
	font-family: "Microsoft YaHei";
	font-size: 14px;
	color: #606266;
}

.binfo_input:focus-visible {
	border: 1px solid #3681fc !important;
}

.binfo_textarea::-webkit-input-placeholder {
	/* WebKit browsers */
	color: rgb(192, 196, 204);
}

.binfo_textarea:-moz-placeholder {
	/* Mozilla Firefox 4 to 18 */
	color: rgb(192, 196, 204);
}

.binfo_textarea::-moz-placeholder {
	/* Mozilla Firefox 19+ */
	color: rgb(192, 196, 204);
}

.binfo_textarea:-ms-input-placeholder {
	/* Internet Explorer 10+ */
	color: rgb(192, 196, 204);
}
.el-form-item__label {
	margin-left: -14px;
}
.elInput {
	margin-left: 10px;
}

.info_span {
	display: flex;
	margin-top: 10px;
	width: 350px;
	align-items: center;
}

.info_span > span:nth-child(1) {
	width: 100px;
	min-width: 100px;
	text-align: right;
	line-height: 40px;
}

.info_span > div {
	width: 250px;
}

.error-border >>> .el-input__inner {
	border: 1px solid red; /* 红色边框 */
}

.error-text {
	color: red; /* 红色文字 */
}
.infoBar {
	width: 100%;
	display: flex;
	justify-content: center;
	gap: 20px;
	margin: 10px 0;
}
.infoBar span {
	cursor: pointer;
}
.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; */
}
.input_box {
	display: flex;
	align-items: center;
	justify-content: center;
}
.input_box span {
	width: 100px;
	font-size: 14px;
	text-align: right;
	padding: 0 12px 0 0;
}
.input_box .input {
	width: 300px;
}
.input_box + .input_box {
	margin-top: 20px;
}
.eye {
	position: absolute;
	right: 10px;
	top: 8px;
	width: 25px;
	height: 25px;
	cursor: pointer;
}

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