<template>
  <div class="pb_content" style="background: unset">
    <div class="pb_content_body" style="
        background: #fff;
        padding: 0px 25px;
        box-sizing: border-box;
        border-radius: 5px;
      ">
      <div class="pb_head">
        <span>我的学生列表</span>
      </div>
      <div class="student_head">
        <div class="head_left">
          <el-input v-model="sPhoneUser" class="student_input" placeholder="请输入用户名"></el-input>
          <el-select v-model="cid" placeholder="请选择班级" class="student_input" @change="searchStudent">
            <el-option label="所有人" value=""></el-option>
            <el-option v-for="(item, index) in classJuri" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <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 newCss" :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" style="margin-left:10px;">只能上传xlsx文件，且不超过500kb</div>
          </el-upload>
          <!-- <el-button @click="exportExcel">导出学生</el-button> -->
          <div @click="getExcel">xls 上传样例</div>
        </div>
      </div>
    </div>
    <div class="pb_content_body">
      <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', fontSize: '17px' }"
          :row-class-name="tableRowClassName">
          <el-table-column label="姓名" min-width="10" align="center">
            <template slot-scope="scope">
              <div class="userImg">
                <div class="tx">
                  <img :src="
                    scope.row.headportrait != null
                      ? scope.row.headportrait
                      : tx
                  " alt />
                </div>
                <div style="
                    width: 150px;
                    text-align: left;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  ">{{ scope.row.name }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="学生账号" min-width="15" align="center">
            <template slot-scope="scope">
              <div>{{ scope.row.un ? scope.row.un : "" }}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="电话" min-width="15" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.phonenumber ? scope.row.phonenumber : "" }}</div>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="studentid" label="学号" min-width="10" align="center"></el-table-column> -->
          <!-- <el-table-column
            prop="school"
            label="学校"
            min-width="30"
            align="center"
          >
          </el-table-column>-->
          <el-table-column prop="classname2" label="班级" min-width="15" align="center">
          </el-table-column>
          <el-table-column label="操作" width="250px">
            <template slot-scope="scope">
              <div class="btnBox">
                <el-button class="de_button" type="primary" size="small"
                  @click="updateStudentA(scope.row)">修改</el-button>
                <div class="delete">
                  <img src="../../assets/remove.png" alt @click="deleteStudent(scope.row.userid, scope.row.state)" />
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="student_page">
        <el-pagination background layout="prev, pager, next" :page-size="10" :total="total" v-if="page"
          @current-change="handleCurrentChange"></el-pagination>
      </div>
    </div>
    <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="sId" 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">
          <span>
            <el-input placeholder="请输入学生账号" clearable v-model="sMail" class="add_input"></el-input>
          </span>
        </el-form-item>
        <el-form-item label="所属学校" :label-width="formLabelWidth">
          <el-input disabled style="width: 300px" v-model="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>
    <el-dialog :visible.sync="dialogVisibleUpdate" :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="userinfo.name" class="add_input"></el-input>
          </span>
        </el-form-item>
        <el-form-item label="学生学号" :label-width="formLabelWidth">
          <span>
            <el-input placeholder="请输入学生学号" clearable v-model="userinfo.studentid" class="add_input"></el-input>
          </span>
        </el-form-item>
        <el-form-item label="学生手机号" :label-width="formLabelWidth">
          <span>
            <el-input placeholder="请输入学生手机号" clearable v-model="userinfo.phonenumber" class="add_input"></el-input>
          </span>
        </el-form-item>
        <el-form-item label="学生账号" :label-width="formLabelWidth">
          <span>
            <el-input placeholder="请输入学生账号" clearable v-model="userinfo.un" class="add_input"></el-input>
          </span>
        </el-form-item>
        <el-form-item label="所属学校" :label-width="formLabelWidth">
          <el-input disabled style="width: 300px" v-model="schoolName"></el-input>
        </el-form-item>
        <el-form-item label="班级" :label-width="formLabelWidth">
          <el-select v-model="userinfo.classid" 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="updateStudent">修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $ from "jquery";
import pinyin from "../../../node_modules/js-pinyin/index";
export default {
  data() {
    return {
      tableHeight: "500px",
      isLoading: false,
      formLabelWidth: "100px",
      tableData: [],
      dialogVisible: false,
      dialogVisibleUpdate: false,
      userinfo: {},
      userinfoA: {},
      sName: "",
      sPhone: "",
      sId: "",
      schoolName: "",
      // sBySchool: [],
      // sBySchoolName:"",
      sByClass: "",
      sMail: "",
      schoolJuri: [],
      classJuri: [],
      fileListUpload: [],
      page: 1,
      total: 0,
      sPhoneUser: "",
      userid: this.$route.query.userid,
      oid: this.$route.query.oid,
      cid: '',
      tx: require("../../assets/avatar.png"),
    };
  },
  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.sMail);
      this.getClass();
      // this.getSchool();
    },
    handleClose(done) {
      done();
    },
    getExcel(res) {
      require.ensure([], () => {
        const { export_json_to_excel } = require("../../common/Export2Excel");
        const tHeader = ["学号", "学生姓名", "学生账号", "学生手机号", "班级"];
        const data = [];
        export_json_to_excel(tHeader, data, "上传学生样例");
      });
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getStudent();
    },
    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.sByClass === "") {
        this.$message.error("请为学生选择班级");
        return;
      } else if (this.sPhone != "" && !/^[1][3,4,5,7,8][0-9]{9}$/.test(this.sPhone)) {
        this.$message.error("手机号格式不正确");
        return;
      } else if (
        !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(this.sMail)
      ) {
        this.$message.error("邮箱格式不正确");
        return;
      }

      // else if (this.sId === "") {
      //   this.$message.error("学生学号不能为空");
      //   return;
      // } else if (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 {
        let params = { un: this.sMail };
        this.ajax
          .get(this.$store.state.api + "findMail", params)
          .then((res) => {
            if (res.data[0].length > 0) {
              this.$message.error("此学生账号已被注册");
            } else {
              // let params = { un: this.sId };
              // this.ajax
              //   .get(this.$store.state.api + "findSid", params)
              //   .then((res) => {
              // if (res.data[0].length > 0) {
              //   this.$message.error("此学生学号已被注册");
              // } else {
              this.add_Student();
              // }
              // })
              // .catch((err) => {
              //   console.error(err);
              // });
            }
          })
          .catch((err) => {
            console.error(err);
          });
        // }
        // })
        // .catch((err) => {
        //   console.error(err);
        // });
      }
    },
    add_Student() {
      let params = [
        {
          username: this.sMail,
          userpassword: 123456,
          alias: this.sName,
          oid: this.oid,
          ph: this.sPhone,
          sid: this.sId,
          cid: this.sByClass,
        },
      ];
      this.ajax
        .post(this.$store.state.api + "batchRegistration", params)
        .then((res) => {
          // console.log(res.data.uid, res.data.ph, res.data.oid, res.data.cid);
          // this.isLoading = false;

          let params = [
            {
              userid: res.data.uid,
              username: this.sName,
              sid: this.sId,
              type: 2,
              oid: res.data.oid,
              phone: res.data.ph,
              cid: res.data.cid,
              intro: "",
              sex: "0",
            },
          ];
          this.ajax
            // .post(this.$store.state.api + "updateUser", params)
            .post(this.$store.state.api + "updateUserByEdu", params)
            .then((res) => {
              console.log(res);
            })
            .catch((err) => {
              console.error(err);
            });
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.sPhone = "";
          this.sName = "";
          // this.sBySchool = [];
          this.sByClass = [];
          this.sMail = "";
          this.getStudent();
        })
        .catch((err) => {
          this.isLoading = false;
          this.$message({
            message: "新增失败",
            type: "error",
          });
          console.error(err);
        });
    },
    //获取班级列表
    getClass() {
      this.isLoading = true;
      let params = {
        oid: this.oid,
      };
      this.ajax
        .get(this.$store.state.api + "selectClassBySchool", 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 = {
        oid: this.oid,
        cid: this.cid,
        cu: "",
        cn: this.sPhoneUser,
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "selectStudent2", 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;
    },
    exportExcel() {
      try {
        let params = {
          oid: this.oid,
        };
        this.ajax
          .get(this.$store.state.api + "selectUserBySchool", params)
          .then((res) => {
            var res = res.data[0];
            //如果value的json字段的key值和想要的headers值不一致时，可做如下更改
            //将和下面的Object.fromEntries结合，将json字段的key值改变为要求的excel的header值
            var array = [];
            for (var i = 0; i < res.length; i++) {
              var _json = {};
              _json["用户名"] = res[i].username;
              _json["姓名"] = res[i].alias ? res[i].alias : "";
              _json["班级"] = res[i].classid ? res[i].classid : "";
              array.push(_json);
            }

            var XLSX = require("xlsx");
            const workbook = XLSX.utils.book_new(); //创建一个新的工作簿对象
            let ws = XLSX.utils.json_to_sheet(array); //将json对象数组转化成工作表
            ws["!cols"] = [
              //设置每一列的宽度
              { wch: 50 },
              { wch: 50 },
              { wch: 50 },
            ];
            XLSX.utils.book_append_sheet(workbook, ws, "sheet1"); //把sheet添加到workbook里，第三个参数是sheet名
            XLSX.writeFile(workbook, "学生信息.xlsx");
            // const wopts = { bookType: "xlsx", bookSST: false, type: "array" };//写入的样式bookType:输出的文件类型，type：输出的数据类型，bookSST: 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
            // const wbout = XLSX.write(workbook, wopts);// 浏览器端和node共有的API,实际上node可以直接使用xlsx.writeFile来写入文件,但是浏览器没有该API
            // FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), `${title} demo.xlsx`);//保存文件
            this.$message({
              message: "导出成功",
              type: "success",
            });
          })
          .catch((err) => {
            console.error(err);
          });
      } catch (e) {
        console.log(e, e.stack);
      }
    },
    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 = {};
            let a = "";
            var num = "";
            for (var cj = 0; cj < 3; cj++) {
              num += Math.floor(Math.random() * 10);
            }
            a =
              pinyin.getFullChars(v["学生姓名"]).toLowerCase() +
              num +
              "@cocorobo.cc";
            obj.sId = v["学号"];
            obj.name = v["学生姓名"];
            obj.mail = v["学生账号"] ? v["学生账号"] : a;
            obj.phone = 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.sId === "") {
              _b = 1;
              _this.$message.error("学生学号不能为空,请重新上传");
            }
            // 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.mail === "") {
              _b = 1;
              _this.$message.error("学生账号不能为空,请重新上传");
              break;
            } else if (
              !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(
                item.mail
              )
            ) {
              _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;
            // 	}
            // }
            //   for (var k = 0; k < arr.length; k++) {
            //     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;
            //       }
            //     }
            //     if (item.mail != "") {
            //       let params = { un: item.mail };
            //       let _a;
            //       _$.ajax({
            //         url: _this.$store.state.api + "findMail", //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;
            //       }
            //     }
            //     if (item.sId != "") {
            //       let params = { un: item.sId };
            //       let _a;
            //       _$.ajax({
            //         url: _this.$store.state.api + "findSid", //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 = [
            //     {
            //       alias: item.name,
            //       username: item.mail,
            //       userpassword: 123456,
            //       oid: _this.oid,
            //       ph: item.phone,
            //       cid: item.class,
            //     },
            //   ];

            //   _this.ajax
            //     .post(_this.$store.state.api + "batchRegistration", params)
            //     .then((res) => {
            //       let params = [
            //         {
            //           userid: res.data.uid,
            //           username: item.name,
            //           sId: item.sId,
            //           type: 2,
            //           oid: res.data.oid,
            //           phone: res.data.ph ? res.data.ph : "",
            //           cid: res.data.cid ? res.data.cid : "",
            //           intro: "",
            //           sex: "0",
            //         },
            //       ];
            //       _this.ajax
            //         .post(_this.$store.state.api + "updateUserByEdu", params)
            //         .then((res) => {
            //           console.log(res);
            //         })
            //         .catch((err) => {
            //           console.error(err);
            //         });
            //       loading.close();
            //       // _this.$message({
            //       //   message: "新增成功",
            //       //   type: "success",
            //       // });
            //       _this.getStudent();
            //       // 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();
          }
          let z = 2;
          let newArr = JSON.stringify(arr);
          let params = [
            {
              arr: newArr,
              userpassword: 123456,
              oid: _this.oid,
            },
          ];
          _this.ajax
            .post(_this.$store.state.api + "batchRegistrationMore", params)
            .then((res) => {
              if (res.data.type == 1) {
                _this.$message.error("有学生手机号码已被注册");
                z = 1;
              }
              if (res.data.type == 2) {
                _this.$message.error("有学生账号已被注册");
                z = 1;
              }
              if (res.data.type == 3) {
                _this.$message.error("有学生学号重复");
                z = 1;
              }
              if (z == 2) {
                _this.$message({
                  message: "新增成功",
                  type: "success",
                });
                _this.getStudent();
              }
              loading.close();
            })
            .catch((err) => {
              console.error(err);
            });
          _this.fileListUpload = [];
        };

        reader.readAsArrayBuffer(f);
      };

      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    getSchoolName() {
      let params = {
        oid: this.oid,
      };
      this.ajax
        .get(this.$store.state.api + "selectSchoolName2", params)
        .then((res) => {
          this.schoolName = res.data[0][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(() => { });
    },
    updateStudentA(res) {
      this.userinfo = JSON.parse(JSON.stringify(res));
      this.userinfoA = JSON.parse(JSON.stringify(res));
      this.dialogVisibleUpdate = true;
    },
    updateStudent() {
      if (this.userinfo.name === "") {
        this.$message.error("学生姓名不能为空");
        return;
      } else if (!this.userinfo.classid) {
        this.$message.error("请为学生选择班级");
        return;
      } else if (this.userinfo.phonenumber != "" && !/^[1][3,4,5,7,8][0-9]{9}$/.test(this.userinfo.phonenumber)) {
        this.$message.error("手机号格式不正确");
        return;
      } else if (
        !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(this.userinfo.un)
      ) {
        this.$message.error("邮箱格式不正确");
        return;
      }


      if (this.time()) {
        if (this.userinfoA.un != this.userinfo.un) {
          let params = { un: this.userinfo.un };
          this.ajax
            .get(this.$store.state.api + "findMail", params)
            .then((res) => {
              if (res.data[0].length > 0) {
                this.$message.error("此学生账号已被注册");
              } else {
                this.update_Student();
              }
            })
            .catch((err) => {
              console.error(err);
            });
        }else{
          this.update_Student();
        }

      }
    },
    update_Student() {
      let params = [
        {
          userid: this.userinfo.userid,
          username: this.userinfo.un,
          alias: this.userinfo.name,
          ph: this.userinfo.phonenumber,
          sid: this.userinfo.studentid,
          cid: this.userinfo.classid,
        },
      ];
      this.ajax
        .post(this.$store.state.api + "updateStudentInfo", params)
        .then((res) => {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.dialogVisibleUpdate = false;
          this.getStudent();
        })
        .catch((err) => {
          this.isLoading = false;
          this.$message({
            message: "修改失败",
            type: "error",
          });
          console.error(err);
        });
    },
  },
  created() {
    this.page = 1;
    this.getStudent();
    this.getSchoolName();
    this.getClass();
  },
};
</script>

<style scoped>
.pb_head>span:nth-child(2) {
  font-size: 20px;
  margin-left: 5px;
  color: #828282;
}

.pb_head {
  margin: 0 !important;
  width: 100% !important;
}

.student_page {
  margin-top: 10px;
}

.student_head {
  margin-top: 10px;
  padding-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

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

.head_right {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: baseline;
}

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

.student_table>>>.el-table,
.student_table>>>.el-table__body-wrapper {
  height: auto !important;
}

.el-table>>>.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;
}

.userImg {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.tx {
  width: 40px;
  margin-right: 10px;
}

.delete {
  width: 25px;
  height: 25px;
  cursor: pointer;
  margin-left: 10px;
}

.tx>img,
.delete>img {
  width: 100%;
  height: 100%;
}

.newCss {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: baseline;
}

.student_input.el-input {
  width: auto;
}

.student_input {
  margin-right: 10px;
}

.student_input>>>.el-input__icon {
  line-height: unset;
}

.btnBox {
  display: flex;
  align-items: center;
}
</style>
