<template>
	<div class="pb_content" style="min-width: 960px">
		<div class="pb_head">
			<span>学生列表</span>
			<span>Student List</span>
		</div>
		<div class="pb_content_body">
			<div class="student_head">
				<div class="head_left">
					<el-input
						v-model="sPhoneUser"
						class="student_input"
						placeholder="请输入手机号或用户名"
					></el-input>
					<el-button class="student_button" @click="searchStudent"
						>查询</el-button
					>
				</div>
				<div class="head_right">
					<el-button @click="addStudent">添加学生</el-button>
					<el-upload
						class="upload-demo"
						:http-request="handleChange"
						:on-remove="handleRemove"
						action="#"
						:file-list="fileListUpload"
						accept=".xlsx"
					>
						<el-button size="primary" type="primary">批量添加</el-button>
						<!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
					</el-upload>
					<div @click="getExcel">xls 上传样例</div>
				</div>
			</div>
			<div class="student_table">
				<el-table
					ref="table"
					:data="tableData"
					border
					:height="tableHeight"
					:fit="true"
					v-loading="isLoading"
					style="width: 100%"
					:header-cell-style="{ background: '#f1f1f1' }"
					:row-class-name="tableRowClassName"
					stripe
				>
					<el-table-column
						prop="name"
						label="姓名"
						min-width="10"
						align="center"
					>
					</el-table-column>
					<el-table-column
						prop="phonenumber"
						label="电话"
						min-width="15"
						align="center"
					>
					</el-table-column>
					<el-table-column
						prop="sex"
						label="性别"
						min-width="10"
						align="center"
					>
						{{ this.tableData.sex ? this.tableData.sex : "男" }}
					</el-table-column>
					<el-table-column
						prop="school"
						label="学校"
						min-width="30"
						align="center"
					>
					</el-table-column>
					<el-table-column
						prop="class"
						label="班级"
						min-width="15"
						align="center"
					>
					</el-table-column>
					<el-table-column label="操作" min-width="20">
						<template slot-scope="scope">
							<el-button
								class="de_button"
								type="primary"
								size="small"
								@click="deleteStudent(scope.row.userid, scope.row.state)"
								>删除</el-button
							>
						</template>
					</el-table-column>
				</el-table>
				<el-dialog
					:visible.sync="dialogVisible"
					:append-to-body="true"
					width="700px"
					:before-close="handleClose"
					class="add_student"
				>
					<div slot="title" class="header-title">
						<div class="logoImg">
							<img src="../../assets/logo.png" alt="" />
						</div>
						<div class="title_add_student">添加学生</div>
					</div>
					<el-form>
						<el-form-item label="学生名称" :label-width="formLabelWidth">
							<span>
								<el-input
									placeholder="请输入学生昵称"
									clearable
									v-model="sName"
									class="add_input"
								></el-input>
							</span>
						</el-form-item>
						<el-form-item label="学生手机号" :label-width="formLabelWidth">
							<span>
								<el-input
									placeholder="请输入学生手机号"
									clearable
									v-model="sPhone"
									class="add_input"
								></el-input>
							</span>
						</el-form-item>
						<el-form-item label="所属学校" :label-width="formLabelWidth">
							<el-input
								disabled
								style="width: 300px"
								:value="this.$store.state.userInfo.schoolName"
							></el-input>
						</el-form-item>
						<el-form-item label="班级" :label-width="formLabelWidth">
							<el-select v-model="sByClass" placeholder="请选择班级">
								<el-option
									v-for="(item, index) in classJuri"
									:key="index"
									:label="item.name"
									:value="item.id"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<div style="text-align: center; color: #adb3b7">
							注：添加学生的账号密码为123456
						</div>
					</el-form>
					<span slot="footer" class="dialog-footer flex">
						<el-button class="right" @click="insertStudent">确认</el-button>
					</span>
				</el-dialog>
			</div>
			<div class="student_page">
				<el-pagination
					background
					layout="prev, pager, next"
					:page-size="10"
					:total="total"
					@current-change="handleCurrentChange"
				>
				</el-pagination>
			</div>
		</div>
	</div>
</template>

<script>
	import $ from "jquery";
	export default {
		data() {
			return {
				tableHeight: "500px",
				isLoading: false,
				formLabelWidth: "100px",
				tableData: [],
				dialogVisible: false,
				sName: "",
				sPhone: "",
				// sBySchool: [],
				// sBySchoolName:"",
				sByClass: "",
				schoolJuri: [],
				classJuri: [],
				fileListUpload: [],
				page: 1,
				total: 0,
				sPhoneUser: "",
			};
		},
		mounted() {
			this.$nextTick(function () {
				this.tableHeight =
					window.innerHeight - this.$refs.table.$el.offsetTop - 200;
				if (this.tableHeight <= 530) {
					this.tableHeight = 530;
				}
				// 监听窗口大小变化
				let self = this;
				window.onresize = function () {
					self.tableHeight =
						window.innerHeight - self.$refs.table.$el.offsetTop - 200;
					if (self.tableHeight <= 530) {
						self.tableHeight = 530;
					}
				};
			});
		},
		methods: {
			tableRowClassName({ row, rowIndex }) {
				if ((rowIndex + 1) % 2 === 0) {
					return "even_row";
				} else {
					return "";
				}
			},
			searchStudent() {
				this.page = 1;
				this.getStudent();
			},
			addStudent() {
				this.dialogVisible = true;
				(this.sName = ""), (this.sPhone = ""), (this.sByClass = "");
				this.getClass();
				// this.getSchool();
			},
			handleClose(done) {
				done();
			},
			getExcel(res) {
				require.ensure([], () => {
					const { export_json_to_excel } = require("../../common/Export2Excel");
					const tHeader = [
						"学生姓名",
						"学生手机号",
						"性别",
						"学校",
						"班级",
						"（注:导入学校为:" + this.$store.state.userInfo.schoolName + "）",
					];
					const data = [];
					export_json_to_excel(tHeader, data, "上传学生样例");
				});
			},
			handleCurrentChange(val) {
				this.page = val;
			},
			time() {
				if (!this.now) {
					this.now = new Date().getTime();
					return true;
				} else {
					let time = new Date().getTime();
					if (time - this.now > 3000) {
						this.now = time;
						return true;
					} else {
						return false;
					}
				}
			},
			//新增学生
			insertStudent() {
				this.dialogVisible = true;
				if (this.sName === "") {
					this.$message.error("学生昵称不能为空");
					return;
				} else if (this.sPhone === "") {
					this.$message.error("学生手机号不能为空");
					return;
				} else if (this.sByClass === "") {
					this.$message.error("请为学生选择班级");
					return;
				} else if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(this.sPhone)) {
					this.$message.error("手机号格式不正确");
					return;
				}
				if (this.time()) {
					let params = { un: this.sPhone };
					this.ajax
						.get(this.$store.state.api + "findPhone", params)
						.then((res) => {
							if (res.data[0].length > 0) {
								this.$message.error("此学生手机号码已被注册");
							} else {
								this.add_Student();
							}
						})
						.catch((err) => {
							console.error(err);
						});
				}
			},
			add_Student() {
				let params = {
					ph: this.sPhone,
					username: this.sName,
					userpassword: 123456,
					type: 2,
					oid: this.$store.state.userInfo.organizeid,
					tid: this.$store.state.userInfo.userid,
					cid: this.sByClass,
				};
				this.ajax
					.get(this.$store.state.api + "insertStudent", params)
					.then((res) => {
						this.isLoading = false;
						this.$message({
							message: "新增成功",
							type: "success",
						});
						this.dialogVisible = false;
						this.sPhone = "";
						this.sName = "";
						// this.sBySchool = [];
						this.sByClass = [];
						this.getStudent();
					})
					.catch((err) => {
						this.isLoading = false;
						this.$message({
							message: "新增失败",
							type: "error",
						});
						console.error(err);
					});
			},
			//获取班级列表
			getClass() {
				this.isLoading = true;
				let params = {
					// username: this.$store.state.userInfo.userid,
					cu: "",
					cn: "",
					page: this.page,
				};
				this.ajax
					.get(this.$store.state.api + "selectClass", params)
					.then((res) => {
						this.isLoading = false;
						this.classJuri = res.data[0];
					})
					.catch((err) => {
						this.isLoading = false;
						console.error(err);
					});
			},
			// getSchool() {
			// 	this.isLoading = true;
			// 	let params = {
			// 		page: this.page,
			// 	};
			// 	this.ajax
			// 		.get(this.$store.state.api + "selectOrg", params)
			// 		.then((res) => {
			// 			this.isLoading = false;
			// 			this.schoolJuri = res.data[0];
			// 		})
			// 		.catch((err) => {
			// 			this.isLoading = false;
			// 			console.error(err);
			// 		});
			// },
			getStudent() {
				this.isLoading = true;
				let params = {
					uid: this.$store.state.userInfo.userid,
					cu: "",
					cn: this.sPhoneUser,
					page: this.page,
				};
				this.ajax
					.get(this.$store.state.api + "selectStudent", params)
					.then((res) => {
						this.isLoading = false;
						this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
						this.tableData = res.data[0];
					})
					.catch((err) => {
						this.isLoading = false;
						console.error(err);
					});
			},
			handleChange(file) {
				this.fileTemp = file.file;
				if (this.fileTemp) {
					if (
						this.fileTemp.type ==
							"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
						this.fileTemp.type == "application/vnd.ms-excel"
					) {
						this.importCount = 1;
						this.importfxx(this.fileTemp);
					} else {
						this.$message({
							type: "warning",
							message: "附件格式错误，请删除后重新上传！",
						});
					}
				} else {
					this.$message({
						type: "warning",
						message: "请上传附件！",
					});
				}
			},
			handleRemove(file, fileList) {
				this.fileTemp = null;
			},
			importfxx(obj) {
				const loading = this.$loading.service({
					background: "rgba(255, 255, 255, 0.7)",
					target: document.body,
				});
				var _$ = $;
				this.importCount++;
				let _this = this;
				// 通过DOM取文件数据
				this.file = obj;
				var rABS = false; //是否将文件读取为二进制字符串
				var f = this.file;
				var reader = new FileReader();
				//if (!FileReader.prototype.readAsBinaryString) {
				FileReader.prototype.readAsBinaryString = function (f) {
					var binary = "";
					var rABS = false; //是否将文件读取为二进制字符串
					var pt = this;
					var wb; //读取完成的数据
					var outdata;
					var reader = new FileReader();
					reader.onload = function (e) {
						var bytes = new Uint8Array(reader.result);
						var length = bytes.byteLength;
						for (var i = 0; i < length; i++) {
							binary += String.fromCharCode(bytes[i]);
						}
						var XLSX = require("xlsx");
						if (rABS) {
							wb = XLSX.read(btoa(fixdata(binary)), {
								//手动转化
								type: "base64",
							});
						} else {
							wb = XLSX.read(binary, {
								type: "binary",
							});
						}
						outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
						this.da = [...outdata];
						let arr = [];
						this.da.map((v) => {
							let obj = {};
							obj.name = v["学生姓名"];
							obj.phone = v["学生手机号"];
							obj.sex = v["性別"];
							obj.school = v["学校"];
							obj.class = v["班级"];
							arr.push(obj);
						});
						console.log(arr);
						let _b = 1;
						for (var i = 0; i < arr.length; i++) {
							let item = arr[i];
							if (item.class === "") {
								_b = 1;
								_this.$message.error("学生班级不能为空,请重新上传");
								break;
							} else if (item.name === "") {
								_b = 1;
								_this.$message.error("学生姓名不能为空,请重新上传");
								break;
							} else if (item.phone === "") {
								_b = 1;
								_this.$message.error("学生手机号不能为空,请重新上传");
								break;
							} else if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(item.phone)) {
								_b = 1;
								_this.$message.error("有学生手机号格式不正确,请重新上传");
								break;
							} else if (item.school === "") {
								_b = 1;
								_this.$message.error("学生学校不能为空,请重新上传");
								break;
							} else if (item.sex === "") {
								_b = 1;
								_this.$message.error("学生性别不能为空,请重新上传");
								break;
							}
							if (item.class != "") {
								let _a;
								let params = {
									className: item.class,
								};

								_$.ajax({
									url: _this.$store.state.api + "selectC", //url路径
									type: "GET", //GET
									async: false, //或false,是否异步
									data: params,
									timeout: 5000, //超时时间
									dataType: "json", //返回的数据格式：
									beforeSend: function (xhr) {},
									success: function (res, textStatus, jqXHR) {
										if (res[0].length == 0) {
											_a = 1;
											_this.$message.error(
												"有学生班级不存在，请去添加后并重新上传"
											);
										} else {
											item.classid = res[0][0].id;
										}
									},
									error: function (xhr, textStatus) {
										console.log(textStatus);
									},
									complete: function () {},
								});
								if (_a == 1) {
									_b = 1;
									break;
								}
							}
							if (item.school != "") {
								let _a;
								let params = {
									schoolName: item.school,
								};

								_$.ajax({
									url: _this.$store.state.api + "selectS", //url路径
									type: "GET", //GET
									async: false, //或false,是否异步
									data: params,
									timeout: 5000, //超时时间
									dataType: "json", //返回的数据格式：
									beforeSend: function (xhr) {},
									success: function (res, textStatus, jqXHR) {
										if (res[0].length == 0) {
											_a = 1;
											_this.$message.error(
												"有学生学校不存在，请去添加后并重新上传"
											);
										} else {
											item.schoolid = res[0][0].id;
										}
									},
									error: function (xhr, textStatus) {
										console.log(textStatus);
									},
									complete: function () {},
								});
								if (_a == 1) {
									_b = 1;
									break;
								}
							}
							if (item.phone != "") {
								let params = { un: item.phone };
								let _a;
								_$.ajax({
									url: _this.$store.state.api + "findPhone", //url路径
									type: "GET", //GET
									async: false, //或false,是否异步
									data: params,
									timeout: 5000, //超时时间
									dataType: "json", //返回的数据格式：
									beforeSend: function (xhr) {},
									success: function (res, textStatus, jqXHR) {
										if (res[0].length > 0) {
											_this.$message.error("此学生手机号码已被注册");
											_a = 1;
										}
									},
									error: function (xhr, textStatus) {
										console.log(textStatus);
									},
									complete: function () {},
								});
								if (_a == 1) {
									_b = 1;
									break;
								}
							}
							_b = 2;
						}
						if (_b == 2) {
							for (var i = 0; i < arr.length; i++) {
								let _i = i;
								let item = arr[i];
								let params = [
									{
										ph: item.phone,
										username: item.name,
										type: 2,
										oid: item.schoolid,
										tid: _this.$store.state.userInfo.userid,
										cid: item.classid,
									},
								];
								_this.ajax
									.post(_this.$store.state.api + "iStudent", params)
									.then((res) => {
										if (_i == arr.length - 1) {
											loading.close();
											_this.$message({
												message: "上传成功",
												type: "success",
											});
											_this.getStudent();
										}
									})
									.catch((err) => {
										_this.$message.error("添加失败");
										console.error(err);
									});
							}
						} else {
							loading.close();
						}

						_this.fileListUpload = [];
					};
					reader.readAsArrayBuffer(f);
				};

				if (rABS) {
					reader.readAsArrayBuffer(f);
				} else {
					reader.readAsBinaryString(f);
				}
			},
			// getSchoolName() {
			// 	let params = {
			// 		oid: this.$store.state.userInfo.organizeid,
			// 	};
			// 	this.ajax
			// 		.get(this.$store.state.api + "selectSchoolName", params)
			// 		.then((res) => {
			// 			this.sBySchool = res.data[0];
			// 			this.sBySchoolName = this.sBySchool[0].name;
			// 		})
			// 		.catch((err) => {
			// 			console.error(err);
			// 		});
			// },
			deleteStudent(id, state) {
				state = 0;
				let params = [{ uid: id, state: state}];
				this.$confirm("确定" + "删除" + "此学生吗?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				})
					.then(() => {
						this.ajax
							.post(this.$store.state.api + "deleteStudent", params)
							.then((res) => {
								this.$message({
									message: "操作成功",
									type: "success",
								});
								this.getStudent();
							})
							.catch((err) => {
								this.$message.error("操作失败");
								console.error(err);
							});
					})
					.catch(() => {});
			},
		},
		created() {
			this.page = 1;
			this.getStudent();
			// this.getSchoolName();
		},
	};
</script>

<style scoped>
	.pb_head > span:nth-child(2) {
		font-size: 20px;
		margin-left: 5px;
		color: #828282;
	}
	.student_head {
		display: flex;
		justify-content: space-between;
	}
	.head_left {
		display: flex;
	}
	.head_right {
		display: flex;
	}
	.student_input >>> .el-input__inner {
		height: 30px;
		width: 190px;
		font-size: 13px;
		padding: 0 10px;
	}
	.student_button {
		color: #fff;
		background: #2268bc;
		width: 60px;
		height: 30px;
		padding: 0 !important;
		font-size: 12px;
		line-height: 30px;
	}
	.head_right > button:nth-child(1) {
		color: #fff;
		background: #2268bc;
		width: 70px;
		height: 30px;
		padding: 0 !important;
		font-size: 12px;
		line-height: 30px;
	}
	.head_right > button:nth-child(2) {
		color: #fff;
		background: #2268bc;
		width: 70px;
		height: 30px;
		padding: 0 !important;
		font-size: 12px;
		line-height: 30px;
	}
	.head_right > div {
		font-size: 12px;
		line-height: 40px;
		margin-left: 10px;
		color: #2a6dbe;
		text-decoration: underline;
		cursor: pointer;
	}
	.student_table >>> .el-table--border td {
		border-right: 0px !important;
	}
	.el-table__row--striped .even_row {
		background-color: #f1f1f1 !important;
	}
	.de_button {
		color: #fff;
		background: #5190fd;
		width: 50px;
		height: 25px;
		padding: 0 !important;
		font-size: 12px;
		line-height: 25px;
	}
	.add_student >>> .el-dialog__header {
		padding: 20px 20px 10px;
		text-align: center;
		background: #32455b;
	}
	.add_student >>> .el-dialog__title {
		font-size: 14px !important;
		color: #fff !important;
	}
	.add_student >>> .el-dialog__headerbtn {
		font-size: 20px !important;
	}
	.add_student >>> .el-form-item__label {
		margin-left: 65px;
	}
	.add_student >>> .el-form-item {
		display: flex;
	}
	.add_student >>> .el-form-item__content {
		margin: 0 !important;
	}
	.add_input {
		width: 365px;
	}
	.add_student >>> .el-dialog__footer {
		text-align: center !important;
	}
	.right {
		width: 250px;
		color: #fff;
		background: #0e72e6;
		margin-bottom: 20px;
	}
	.header-title {
		display: flex;
	}
	.logoImg {
		width: 30px;
	}
	.logoImg > img {
		width: 100%;
		height: 100%;
	}
	.title_add_student {
		margin: 0 auto;
		color: #fff;
	}
	.upload-demo {
		line-height: 0px !important;
	}
	.upload-demo >>> .el-button {
		color: #fff;
		background: #2268bc;
		width: 70px;
		height: 30px;
		padding: 0 !important;
		font-size: 12px;
		line-height: 0 !important;
	}
</style>
