<template>
  <div
    class="pb_content"
    style="background: unset; height: 100%; overflow: auto"
  >
    <div
      class="pb_content_body"
      style="
        background: #fff;
        padding: 0px 25px;
        box-sizing: border-box;
        margin: 10px auto 0;
        /* 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 inputClass"
            @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
            v-show="false"
            class="upload-demo newCss"
            :http-request="handleChange"
            :on-remove="handleRemove"
            action="#"
            :file-list="fileListUpload"
            accept=".xlsx"
          >
            <el-button class="btnClassGM" 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" v-show="false">xls 上传样例</div>
        </div>
      </div>
    </div>
    <div class="pb_content_body" style="margin: 0 auto">
      <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
            prop="schoolName"
            label="学校"
            min-width="15"
            align="center"
          >
          </el-table-column>
          <el-table-column label="操作" width="220px">
            <template slot-scope="scope">
              <div
                class="delete"
                @click="deleteStudent(scope.row.userid, scope.row.state)"
              >
                <img src="../../../assets/remove.png" alt />
              </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 class="inputClass">
        <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="sMail"
              class="add_input"
            ></el-input>
          </span>
        </el-form-item>
        <el-form-item label="所属学校" :label-width="formLabelWidth">
          <el-select
            v-model="schoolName"
            placeholder="请选择学校"
            @change="checkEva"
          >
            <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>
</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,
      sName: "",
      sMail: "",
      sId: "",
      schoolName: "",
      schoolJuri: [],
      classJuri: [],
      fileListUpload: [],
      page: 1,
      total: 0,
      sPhoneUser: "",
      userid: this.$route.query.userid,
      oid: this.$route.query.oid,
      cid: '',
      org: this.$route.query.org,
      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.sMail = ""), (this.schoolName = "");
      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.sMail === "") {
        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.schoolName === ""){
        this.$message.error("请选择学校");
        return;
      }
      if (this.time()) {
        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 {
              this.add_Student();
            }
          })
          .catch((err) => {
            console.error(err);
          });
      }
    },
    add_Student() {
      let params = [
        {
          username: this.sMail,
          userpassword: 123456,
          alias: this.sName,
          org:this.org,
          oid: this.schoolName,
          ph: this.sPhone,
          sid: this.sId,
          cid: '',
        },
      ];
      this.ajax
        .post(this.$store.state.api + "batchRegistration1", params)
        .then((res) => {
          // debugger;
          let params = [
            {
              userid: res.data.uid,
              username: this.sName,
              sid: this.sId,
              type: 1,
              org:this.org,
              oid: res.data.oid,
              phone: res.data.ph,
              cid: '',
              intro: "",
              sex: "0",
            },
          ];
          this.ajax
            .post(this.$store.state.api + "updateUserByEdu1", params)
            .then((res) => {
              console.log(res);
            })
            .catch((err) => {
              console.error(err);
            });
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.sName = "";
          this.sMail = "";
          this.schoolName = "";
          this.getStudent();
        })
        .catch((err) => {
          this.isLoading = false;
          this.$message({
            message: "新增失败",
            type: "error",
          });
          console.error(err);
        });
    },
    //获取班级列表
    getClass() {
      this.isLoading = true;
      let params = {
        org: this.org,
      };
      this.ajax
        .get(this.$store.state.api + "selectSchoolByOrg", 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 = {
        org: this.org,
        cu: this.cid,
        cn: this.sPhoneUser,
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "selectTeacher", 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 = {};
            obj.name = v["教师姓名"];
            obj.mail = v["教师账号"];
            obj.school = v["学校"];
            arr.push(obj);
          });
          console.log(arr);
          let _b = 1;
          for (var i = 0; i < arr.length; i++) {
            let item = arr[i];
            if (item.school === "") {
              _b = 1;
              _this.$message.error("教师学校不能为空,请重新上传");
              break;
            } else if (item.name === "") {
              _b = 1;
              _this.$message.error("教师姓名不能为空,请重新上传");
              break;
            } else if (item.mail === "") {
              _b = 1;
              _this.$message.error("教师账号不能为空,请重新上传");
            }else if (
              !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(
                item.mail
              )
            ) {
              _b = 1;
              _this.$message.error("有教师账号格式不正确,请重新上传");
              break;
            }
          }
          let z = 2;
          let newArr = JSON.stringify(arr);
          let params = [
            {
              arr: newArr,
              userpassword: 123456,
              org: _this.org,
            },
          ];
          _this.ajax
            .post(_this.$store.state.api + "batchRegistrationMore1", params)
            .then((res) => {
              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(() => {});
    },
  },
  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: #8681b7;
  border-color: #8681b7;
  width: 60px;
  height: 30px;
  padding: 0 !important;
  font-size: 12px;
  line-height: 30px;
}
.head_right > button:nth-child(1) {
  color: #fff;
  background: #8681b7;
  border-color: #8681b7;
  width: 70px;
  height: 30px;
  padding: 0 !important;
  font-size: 12px;
  line-height: 30px;
}
.head_right > button:nth-child(2) {
  color: #fff;
  background: #8681b7;
  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: #454545;
}
.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: #8681b7;
  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: #8681b7;
  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;
  cursor: pointer;
}

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

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

.student_page
  >>> .el-pagination.is-background
  .el-pager
  li:not(.disabled).active {
  background-color: #5c549f;
  color: #fff !important;
}
.student_page
  >>> .el-pagination.is-background
  .el-pager
  li:not(.disabled):hover {
  color: #5c549f;
}

.el-select-dropdown__item.selected {
  color: #5c549f;
}

.inputClass.is-active >>> .el-input__inner,
.inputClass >>> .el-input__inner:focus {
  border-color: #5c549f;
}

.inputClass >>> .el-select .el-input.is-focus .el-input__inner {
  border-color: #5c549f;
}
.inputClass >>> .el-select .el-input__inner:focus {
  border-color: #5c549f;
}

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

.student_input {
  margin-right: 10px;
}

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