<template>
  <div class="pb_content">
    <div class="tou">
      <span>班级管理</span>
    </div>
    <div class="pb_content_body">
      <div class="student_head">
        <div class="student_search">
          <span>
            <el-input
              placeholder="请输入班级名称"
              v-model="sClassName"
              clearable
            >
            </el-input>
          </span>
          <el-button type="primary" @click="searchClass" size="small"
            >查询</el-button
          >
        </div>
        <div class="student_button">
          <el-button type="primary" size="small" @click="dialogVisible = true"
            >添加班级</el-button
          >
        </div>
      </div>
      <div class="student_table">
        <el-table
          ref="table"
          :data="tableData"
          border
          :height="tableHeight"
          :fit="true"
          v-loading="isLoading"
          style="width: 100%; height: 60%"
          :header-cell-style="{ background: '#f1f1f1' }"
          :row-class-name="tableRowClassName"
        >
          <el-table-column
            prop="school"
            label="学校名称"
            min-width="25%"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="name"
            label="班级名称"
            min-width="25%"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="pNum"
            label="人数"
            min-width="25%"
            align="center"
          >
          </el-table-column>
          <el-table-column label="操作" min-width="20%">
            <template slot-scope="scope">
              <el-button
                @click="deleteClass(scope.row)"
                type="text"
                size="small"
                >删除</el-button
              >
            </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="!isListAjax && page"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="添加学生"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      width="25%"
      :before-close="handleClose"
      class="dialog_diy"
    >
      <el-form>
        <el-form-item label="所属学校" :label-width="formLabelWidth">
          <el-select v-model="oid">
            <el-option
              v-for="item in schoolArray"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" :label-width="formLabelWidth">
          <el-input
            v-model="className"
            auto-complete="off"
            placeholder="请输入班级..."
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="insertClass">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $ from "jquery";
export default {
  data() {
    return {
      isLoading: false,
      tableHeight: 50,
      sClassName: "",
      className: "",
      formLabelWidth: "80px",
      dialogVisible: false,
      tableData: [],
      total: 0,
      page: 1,
      oid: "",
      isListAjax: false,
      schoolArray: [],
    };
  },
  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;
        }
      };
    });
    //this.$refs.table.$el.offsetTop：表格距离浏览器的高度 //200表示你想要调整的表格距离底部的高度（你可以自己随意调整），因为我们一般都有放分页组件的，所以需要给它留一个高度
  },
  created() {
    this.page = 1;
    this.getClass();
    this.getOrg();
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if ((rowIndex + 1) % 2 === 0) {
        return "even_row";
      } else {
        return "";
      }
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.getClass();
    },
    handleClose(done) {
      done();
      // this.$confirm("确认关闭？")
      //   .then((_) => {
      //     done();
      //   })
      //   .catch((_) => {});
    },
    //查询学校
    getOrg() {
      this.ajax
        .get(this.$store.state.api + "selectOrg", "")
        .then((res) => {
          this.schoolArray = res.data[0];
          console.log(res.data[0]);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //搜索班级
    searchClass() {
      this.page = 1;
      // this.isListAjax = true;
      this.getClass();
    },
    //获取班级
    getClass() {
      this.isLoading = true;
      let params = {
        cn: this.sClassName,
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "getClassAdmin", params)
        .then((res) => {
          this.isListAjax = false;
          this.isLoading = false;
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          this.tableData = res.data[0];
          console.log(this.tableData);
        })
        .catch((err) => {
          this.isLoading = false;
          console.error(err);
        });
    },
    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;
        }
      }
    },
    //添加班级
    insertClass() {
      let _this = this;
      console.log(this.$store.state.userInfo);
      if (this.oid === "") {
        this.$message.error("请选择学校");
        return;
      }
      if (this.className === "") {
        this.$message.error("班级名字不能为空");
        return;
      }
      let params = [
        {
          n: this.className,
          oid: this.oid,
          cuid: this.$store.state.userInfo.uid,
        },
      ];
      let params2 = { oid: this.oid, n: this.className };
      let a = 1;
      $.ajax({
        url: this.$store.state.api + "getClassRepeat", //url路径
        type: "GET", //GET
        async: false, //或false,是否异步
        data: params2,
        timeout: 5000, //超时时间
        dataType: "json", //返回的数据格式：
        beforeSend: function (xhr) {},
        success: function (res, textStatus, jqXHR) {
          if (res[0][0].num > 0) {
            _this.$message.error("此学校已存在此班级！");
            a = 2;
          }
        },
        error: function (xhr, textStatus) {
          console.log(textStatus);
        },
        complete: function () {},
      });
      if (this.time() && a == 1) {
        this.ajax
          .post(this.$store.state.api + "addClassAdmin", params)
          .then((res) => {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.sClassName = "";
            this.className = "";
            this.page = 1;
            this.getClass();
            this.dialogVisible = false;
          })
          .catch((err) => {
            this.$message.error("添加失败");
            console.error(err);
          });
      }
    },
    //删除班级
    deleteClass(row) {
      let params = { id: row.id };
      this.$confirm("确定删除此班级吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ajax
            .get(this.$store.state.api + "deleteClass", params)
            .then((res) => {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.className = "";
              if (this.page != 1 && this.tableData.length == 1) {
                this.page--;
              }
              this.getClass();
              this.dialogVisible = false;
            })
            .catch((err) => {
              this.$message.error("删除失败");
              console.error(err);
            });
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.dialog_diy >>> .el-dialog__header {
  background: #3d67bc !important;
  padding: 15px 20px;
}
.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;
}
/* .student_head >>> .el-button--primary {
  background-color: #2268bc;
} */
.pb_content {
  box-sizing: border-box;
  padding: 20px;
}
.pb_content_body {
  margin-top: 10px;
}
.xls_button {
  font-size: 14px;
  cursor: pointer;
  text-decoration: underline;
  color: rgb(34, 104, 188);
}
.student_head {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.student_search {
  display: flex;
  width: 300px;
  align-items: center;
}
.student_search span {
  margin: 0 10px 0 0;
}
.student_button {
  display: flex;
  overflow: hidden;
  /* height: 40px; */
}
.student_button .el-button--primary {
  /* margin-right: 10px; */
}
.upload-demo {
  display: flex;
  flex-direction: column;
  align-items: end;
  /* position: relative; */
  width: 100px;
  overflow: hidden;
}
.student_table {
  margin: 20px 0;
}

.el-table >>> .even_row {
  background-color: #f1f1f1;
}

.tou {
  border-bottom: 1px solid #c9c9c9;
  height: 50px;
  font-size: 30px;
}
</style>
