<template>
  <div>
    <back-box>
      <template slot="title">
        <span>学生管理</span>
      </template>
      <template slot="btns" v-if="!code">
        <el-tooltip effect="dark" content="添加学生" placement="bottom">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            plain
            circle
            @click="openAddDia"
          ></el-button>
        </el-tooltip>
      </template>
    </back-box>
    <div class="page-content">
      <div class="stu-box">
        <div class="stu-list">
          <div class="h-title">
            <el-select
              class="sel"
              v-model="query.gradeName"
              placeholder="选择年级"
              @change="changeGrade"
            >
              <el-option
                v-for="item in gradeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <ul class="stu-ul">
            <li
              class="stu-item"
              v-for="item in classList"
              :key="item.id"
              :class="query.classId == item.id ? 'active' : ''"
              @click="classDetail(item)"
            >
              <i
                v-if="!code"
                class="el-icon-edit-outline"
                @click.stop="setClass(item)"
              ></i>
              {{ item.className }}（{{ item.studentCount }}）
            </li>
          </ul>
        </div>
        <div class="stu-detail">
          <div class="answer-header">
            <div class="sel-box">
              <el-input
                placeholder="请输入学生姓名"
                v-model="query.studentName"
                class="input-with-select"
                @keyup.enter.native="_QueryData(1)"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="_QueryData(1)"
                ></el-button>
              </el-input>
              <el-input
                placeholder="请输入学生学号"
                v-model="query.studentCode"
                class="input-with-select"
                @keyup.enter.native="_QueryData(2)"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="_QueryData(2)"
                ></el-button>
              </el-input>
            </div>
          </div>
          <ul class="s-ul" v-loading="loading">
            <li
              class="s-li"
              v-for="(item, index) in studentList"
              :key="item.id"
            >
              <el-popconfirm
                v-if="!code"
                title="确定删除吗？"
                @confirm="removeStu(item, index)"
              >
                <i class="el-icon-delete" slot="reference"></i>
              </el-popconfirm>
              <p class="name">{{ item.studentName }}</p>
              <p class="p1">答题器：{{ item.clickerSn || "--" }}</p>
              <p class="p1">长学号：{{ item.studentCode }}</p>
              <p class="p1">短学号：{{ item.shortNumber || "--" }}</p>
            </li>
          </ul>
          <el-empty
            :image-size="100"
            v-if="!studentList.length && loading == false"
            description="没有更多数据"
          ></el-empty>
        </div>
      </div>
    </div>
    <el-dialog title="添加学生" :visible.sync="diaStu" width="400">
      <el-form
        ref="formBox"
        class="form-box"
        :model="formStu"
        :rules="rulesStu"
        label-width="160px"
      >
        <el-form-item label="所在班级：">
          <span>{{ formStu.className }}</span>
        </el-form-item>
        <el-form-item label="学生姓名：" prop="studentName">
          <el-col :span="10">
            <el-input
              maxlength="30"
              placeholder="输入学生姓名"
              v-model.trim="formStu.studentName"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="长学号：" prop="studentCode">
          <el-col :span="10">
            <el-input
              maxlength="12"
              placeholder="输入学生长学号"
              v-model.trim="formStu.studentCode"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="短学号：">
          <el-col :span="10">
            <el-input maxlength="12" v-model.trim="formStu.shortNumber" />
          </el-col>
        </el-form-item>
        <el-form-item label="性别：">
          <el-radio-group v-model="formStu.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答题器编码：">
          <el-col :span="10">
            <el-input v-model.trim="formStu.clickerSn" />
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="addStu">确 定</el-button>
        <el-button @click="diaStu = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改班级" :visible.sync="diaClass" width="400">
      <el-form
        class="form-box"
        ref="formClass"
        :model="formClass"
        :rules="rulesClass"
        label-width="160px"
      >
        <el-form-item label="所在年级：">
          <span>{{ formClass.gradeName }}</span>
        </el-form-item>
        <el-form-item label="班级名称：" prop="studentName">
          <el-col :span="10">
            <el-input maxlength="30" v-model.trim="formClass.className" />
          </el-col>
        </el-form-item>
        <el-form-item label="入学年份：" prop="studentCode">
          <el-col :span="10">
            <el-date-picker
              v-model="formClass.intoSchoolYear"
              type="year"
              value-format="yyyy"
              placeholder="选择年"
            >
            </el-date-picker>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="saveClass">确 定</el-button>
        <el-button @click="diaClass = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { downloadFile } from "@/utils";
export default {
  data() {
    return {
      code: "",
      url: "",
      diaStu: false,
      diaClass: false,
      query: {
        gradeName: "",
        classId: "",
        studentCode: "",
        studentName: "",
      },
      formStu: {
        className: "",
        studentName: "",
        studentCode: "",
        shortNumber: "",
        sex: 1,
        clickerSn: "",
      },
      rulesStu: {
        studentName: [
          { required: true, message: "请输入学生名称", trigger: "blur" },
        ],
        studentCode: [
          { required: true, message: "请输入学生长学号", trigger: "blur" },
        ],
      },
      formClass: {
        gradeName: "",
        className: "",
        intoSchoolYear: "",
      },
      rulesClass: {
        className: [
          { required: true, message: "请输入班级名称", trigger: "blur" },
        ],
      },
      gradeName: "",
      gradeList: [],
      classList: [],
      studentList: [],
      teacherDetail: {
        teacherName: "",
        loginName: "",
        sex: "",
        available: "",
        managerList: [],
        teacherCourseList: [],
        teacherGradeList: [],
      },
    };
  },
  async created() {
    this.code = localStorage.getItem("csCode") || "";
    await this._QueryDataGrade();
    await this._QueryClass();
    this._QueryData(3);
  },
  methods: {
    openAddDia() {
      this.formStu.studentName = "";
      this.formStu.studentCode = "";
      this.formStu.shortNumber = "";
      this.formStu.sex = 1;
      this.formStu.clickerSn = "";
      this.diaStu = true;
    },
    classDetail(obj) {
      this.query.classId = obj.id;
      this.formStu.className = obj.className;
      this._QueryData(3);
    },
    setClass(obj) {
      this.formClass.gradeName = obj.gradeName;
      this.formClass.classId = obj.id;
      this.formClass.className = obj.className;
      this.formClass.intoSchoolYear = obj.intoSchoolYear + "";
      this.diaClass = true;
    },
    saveClass() {
      this.$refs.formClass.validate(async (valid) => {
        if (valid) {
          const { data, status, info } = await this.$request.updateClass({
            classId: this.formClass.classId,
            className: this.formClass.className,
            intoSchoolYear: this.formClass.intoSchoolYear,
          });
          if (status === 0) {
            this.$message.success("修改成功");
            this.diaClass = false;
            this._QueryClass();
          } else {
            this.$message.error(info);
          }
        } else {
          this.$message.warning("输入有误请检查！");
          return false;
        }
      });
    },
    async removeStu(obj, index) {
      const { data, status, info } = await this.$request.delStudent({
        studentId: obj.id,
      });
      if (status === 0) {
        this.$message.success("删除成功");
        this.studentList.splice(index, 1);
        this._QueryClass();
      } else {
        this.$message.error(info);
      }
    },
    async changeGrade(val) {
      this.query.classId = "";
      await this._QueryClass(val);
      this._QueryData(3);
    },
    addStu() {
      let query = {};
      for (let key in this.formStu) {
        if (key != "className" && this.formStu[key]) {
          query[key] = this.formStu[key];
        }
      }
      this.loading = true;
      this.$refs.formBox.validate(async (valid) => {
        if (valid) {
          let hasName = this.studentList.find((item) => {
            return item.studentName == this.formStu.studentName;
          });
          console.log(hasName);
          if (hasName) {
            this.$message.warning("学生姓名已存在");
            return;
          }
          const { data, status, info } = await this.$request.addStudent({
            classId: this.query.classId,
            ...query,
          });
          this.loading = false;
          console.log(status);
          if (status === 0) {
            this.$message.success(info);
            this.diaStu = false;
            this._QueryClass();
            this._QueryData();
          } else {
            this.$message.error(info);
          }
        } else {
          this.$message.error("数据有误，请检查！");
        }
      });
    },
    async _QueryData(type) {
      let query = {};
      query.gradeName = this.query.gradeName;
      query.classId = this.query.classId;
      if (type == 1) {
        query.studentName = this.query.studentName;
        this.query.studentCode = "";
      } else if (type == 2) {
        query.studentCode = this.query.studentCode;
        this.query.studentName = "";
      } else if (type == 3) {
        this.query.studentName = "";
        this.query.studentCode = "";
      } else {
        query = this.query;
      }
      this.loading = true;
      const { data, status, info } = await this.$request.studentList({
        ...query,
      });
      this.loading = false;
      console.log(status);
      if (status === 0) {
        this.studentList = data.list || [];
      } else {
        this.$message.error(info);
      }
    },
    async _QueryDataGrade() {
      this.loading = true;
      const { data, status, info } = await this.$request.gradeList();
      if (status === 0) {
        this.gradeList =
          data.list?.map((item) => {
            return {
              value: item.gradeName,
              label: item.gradeName,
            };
          }) || [];
        this.query.gradeName = this.gradeList[0]?.value;
      } else {
        this.$message.error(info);
      }
    },
    async _QueryClass(value) {
      const { data, status, info } = await this.$request.schoolClassList({
        gradeName: value || this.query.gradeName,
      });
      if (status === 0) {
        this.classList = [...data.list] || [];
        this.query.classId = this.classList[0]?.id;
        this.formStu.className = this.classList[0]?.className;
      } else {
        this.$message.error(info);
      }
    },
    async downExcel() {
      let data = await this.$request.downDevice({
        id: this.id,
      });
      if (data && !data.code) {
        let blob = new Blob([data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        downloadFile(`设备信息.xlsx`, blob);
      } else {
        this.$message.error(data.info);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page-content {
  padding: 20px;
}
.stu-box {
  display: flex;
  background: #f8f8f8;
  border-radius: 10px;
  overflow: hidden;
  .stu-list {
    max-height: 80vh;
    .h-title {
      height: 40px;
      line-height: 40px;
      background: #eee;
    }
    .stu-item {
      font-size: 16px;
      color: #7f7f7f;
      line-height: 36px;
      cursor: pointer;
      padding-left: 12px;
      position: relative;
      .el-icon-edit-outline {
        position: absolute;
        top: 8px;
        right: 12px;
        font-size: 20px;
        display: none;
        &:hover {
          color: #667ffd;
        }
      }
      &:hover {
        background: #eee;
        .el-icon-edit-outline {
          display: block;
        }
      }
      &.active {
        color: #667ffd;
        background: #eee;
      }
    }
    .sel {
      width: 180px;
      :deep(.el-input__inner) {
        font-size: 16px;
        padding-left: 0;
        border: none;
        background: transparent;
      }
      :deep(.el-icon-arrow-up:before) {
        content: "\e78f";
      }
    }
  }
  .stu-detail {
    flex: 1;
    border-left: 0.5px solid #eee;
    .s-ul {
      display: flex;
      flex-wrap: wrap;
      padding-left: 20px;
      .s-li {
        width: 180px;
        height: 120px;
        box-shadow: 2px 2px 5px #7f7f7f;
        border-radius: 10px;
        margin: 0 20px 20px 0;
        padding: 0 12px 5px;
        position: relative;
        .el-icon-delete {
          position: absolute;
          top: 8px;
          right: 8px;
          font-size: 18px;
          padding: 2px;
          display: none;
          cursor: pointer;
          &:hover {
            color: #667ffd;
          }
        }
        &:hover {
          .el-icon-delete {
            display: block;
          }
        }
        .name {
          text-align: center;
          font-size: 16px;
          line-height: 18px;
          padding: 10px 0;
        }
        .p1 {
          color: #7f7f7f;
          line-height: 20px;
          padding-bottom: 5px;
        }
      }
    }
  }
}
</style>