<template>
  <div>
    <back-box>
      <template slot="title">
        <span>学生管理</span>
      </template>
      <template slot="btns" v-if="role == 'ROLE_XUEXIAO'">
        <el-tooltip
          effect="dark"
          content="设置答题器"
          placement="bottom"
          v-show="query.classType == 0"
        >
          <el-button
            type="primary"
            icon="el-icon-upload2"
            size="mini"
            plain
            circle
            @click="diaUp = true"
          ></el-button>
        </el-tooltip>
        <el-tooltip
          v-if="!code && query.classType == 0"
          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="answer-header">
      <div class="sel-box">
        <el-select
          class="sel"
          v-model="query.classType"
          @change="changeGrade(query.grade)"
          placeholder="选择类型"
        >
          <el-option label="行政班" :value="0"></el-option>
          <el-option label="教学班" :value="1"></el-option>
        </el-select>
        <el-select
          class="sel"
          v-model="query.grade"
          placeholder="选择年级"
          @change="changeGrade"
        >
          <el-option disabled label="全部" value=""></el-option>
          <el-option
            v-for="item in gradeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
          <el-option label="未分配" :value="80"></el-option>
          <el-option label="已毕业" :value="81"></el-option>
        </el-select>
        <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>
    <p
      class="total"
      v-if="
        studentList.length &&
        (query.grade == 80 || query.grade == 81 || !query.grade)
      "
    >
      共筛选出{{ studentList.length }}名学生。
    </p>
    <p
      class="total"
      v-if="
        getStuTotal && query.grade && query.grade != 80 && query.grade != 81
      "
    >
      共筛选出{{ getStuTotal }}名学生。
    </p>
    <div class="page-content">
      <div class="stu-box">
        <div
          class="stu-list"
          v-show="query.grade && query.grade != 80 && query.grade != 81"
        >
          <div class="h-title">班级列表</div>
          <ul class="stu-ul">
            <li
              class="stu-item"
              v-for="(item, index) in classList"
              :key="item.id"
              :class="query.classId == item.id ? 'active' : ''"
              @click="classDetail(item)"
            >
              {{ item.className }}（{{ item.studentCount }}）
            </li>
          </ul>
        </div>
        <div class="stu-detail" v-loading="loading">
          <div
            class="clazz-detail"
            v-if="
              clazzDetail.stationSn &&
              query.grade &&
              query.grade != 80 &&
              query.grade != 81
            "
          >
            <p>基站SN：{{ clazzDetail.stationSn }}</p>
            <p>配对码：{{ clazzDetail.pairingCode }}</p>
            <p>频点：{{ clazzDetail.frequency }}</p>
          </div>
          <ul class="s-ul">
            <li
              class="s-li"
              v-for="(item, index) in studentList"
              :key="item.id"
            >
              <el-popconfirm
                v-if="!code"
                title="确定删除吗？"
                @confirm="removeStu(item, index, $event)"
              >
                <i class="el-icon-delete" slot="reference"></i>
              </el-popconfirm>
              <i
                class="el-icon-user-solid"
                v-if="!code && query.grade != 81"
                @click.stop="openChangeClazz(item)"
              ></i>
              <div class="s-li-box" @click="sayChange(item)">
                <p class="name">
                  {{ item.studentName }}
                </p>
                <p class="p2" v-if="!query.classId">
                  <template v-if="item.classList && item.classList.length">
                    <template v-for="(clazz, index) in item.classList">
                      <span v-if="index == 0">
                        {{ clazz.gradeName }}﹒{{ clazz.className }}</span
                      >
                    </template></template
                  >
                  <template v-else>
                    {{
                      item.status == 0
                        ? "未分配"
                        : item.status == 2
                        ? "已毕业"
                        : ""
                    }}
                  </template>
                </p>
                <p class="p1">答题器：{{ item.clickerSn || "--" }}</p>
                <p class="p1">长学号：{{ item.studentCode }}</p>
                <p class="p1">短学号：{{ item.shortNumber || "--" }}</p>
              </div>
            </li>
          </ul>
          <el-empty
            :image-size="100"
            v-if="!studentList.length && loading == false"
            description="没有更多数据"
          ></el-empty>
        </div>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="学生调班"
      :visible.sync="diaChangeClass"
      width="400"
    >
      <el-form
        class="form-box"
        ref="formStuCla"
        :model="formStuCla"
        :rules="rulesStuCla"
        label-width="160px"
      >
        <el-form-item label="学生姓名：">
          <el-col :span="10">
            <el-input
              v-model="formStuCla.studentName"
              maxlength="20"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="当前班级：">
          <span>{{ formStuCla.className }}</span>
        </el-form-item>
        <el-form-item label="调到班级：" prop="classId">
          <el-col :span="10">
            <el-select
              class="sel"
              v-model="formStuCla.classId"
              placeholder="选择年级"
            >
              <el-option disabled label="请选择" value=""></el-option>
              <el-option
                v-for="item in classList"
                :key="item.id"
                :label="item.className"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="长学号：" prop="studentCode">
          <el-col :span="10">
            <el-input
              maxlength="12"
              placeholder="输入学生长学号"
              v-model.trim="formStuCla.studentCode"
            />
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="changeStu">确 定</el-button>
        <el-button @click="diaChangeClass = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="调班轨迹"
      :visible.sync="diaChangeClassTrack"
      width="400"
    >
      <el-form
        :model="formClassTrack"
        label-width="160px"
        v-loading="loadingClassLogs"
      >
        <el-form-item label="学生姓名：">
          <span>{{ formClassTrack.studentName }}</span>
        </el-form-item>
        <el-form-item label="当前班级：">
          <span>{{ formClassTrack.className }}</span>
        </el-form-item>
        <el-form-item label="历史班级：">
          <p v-for="item in formClassTrack.classList">
            {{ `${item.gradeName}-${item.className}：${item.createdTime}` }}
          </p>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="diaChangeClassTrack = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      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
      :close-on-click-modal="false"
      title="学生答题器绑定"
      :visible.sync="diaUp"
      width="600"
    >
      <upload
        id="downTeacher"
        :url="url"
        :params="{ type: query.classType }"
        @upSuccess="upSuccess"
        fileName="学生答题器绑定模板"
      >
        <p class="down-txt" slot="down">
          通过Excel名单导入学生答题器绑定模板，点击
          <el-link type="danger" @click="downExcel">模板下载</el-link> 。
        </p>
      </upload>
      <div class="dialog-footer" slot="footer">
        <el-button @click="diaUp = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
import { setGradeName } from "@/utils";
export default {
  data() {
    return {
      code: "",
      role: "",
      loading: false,
      loadingDown: false,
      loadingClassLogs: false,
      diaUp: false,
      url: "/api_html/school/manager/importStudentClicker",
      diaStu: false,
      diaChangeClass: false,
      diaChangeClassTrack: false,
      formClassTrack: {
        studentName: "",
        className: "",
        classList: [],
      },
      clazzDetail: { stationSn: "", pairingCode: "", frequency: "" },
      query: {
        classType: 0, //0行政 1教学班
        grade: "",
        classId: "",
        status: 0,
        studentCode: "",
        studentName: "",
      },
      formStu: {
        className: "",
        studentName: "",
        studentCode: "",
        shortNumber: "",
        sex: 1,
        clickerSn: "",
      },
      rulesStu: {
        studentName: [
          { required: true, message: "请输入学生名称", trigger: "blur" },
        ],
        studentCode: [
          { required: true, message: "请输入学生长学号", trigger: "blur" },
        ],
      },
      formStuCla: {
        studentName: "",
        studentId: "",
        oldClassId: "",
        className: "",
        classId: "",
        studentCode: "",
      },
      rulesStuCla: {
        studentName: [
          { required: true, message: "请输入学生名称", trigger: "blur" },
        ],
        classId: [{ required: true, message: "请选择班级", trigger: "blur" }],
        studentCode: [
          { required: true, message: "请输入学生号", trigger: "blur" },
        ],
      },
      gradeName: "",
      gradeList: [],
      classList: [],
      studentList: [],
      teacherDetail: {
        teacherName: "",
        loginName: "",
        sex: "",
        available: "",
        managerList: [],
        teacherCourseList: [],
        teacherGradeList: [],
      },
    };
  },
  computed: {
    getStuTotal: function () {
      let num = this.classList.reduce((pre, cur) => {
        return (pre += cur.studentCount);
      }, 0);
      return num;
    },
  },
  async created() {
    this.code = this.$store.getters.csCode;
    this.role =
      this.$store.getters.info.showRole ||
      this.$store.getters.info.permissions[0].role;
    await this._QueryDataGrade();
    await this._QueryClass();
    this._QueryData(3);
  },
  methods: {
    getGradeName(type) {
      return setGradeName(type);
    },
    openAddDia() {
      if (!this.query.classId) {
        this.$message.warning("暂无班级信息，请选择或导入班级！");
        return;
      }
      this.formStu.studentName = "";
      this.formStu.studentCode = "";
      this.formStu.shortNumber = "";
      this.formStu.sex = 1;
      this.formStu.clickerSn = "";
      this.diaStu = true;
    },
    classDetail(obj) {
      this.clazzDetail.stationSn = obj.stationSn;
      this.clazzDetail.pairingCode = obj.pairingCode;
      this.clazzDetail.frequency = obj.frequency;
      this.query.classId = obj.id;
      this.formStu.className = obj.className;
      this._QueryData(3);
    },

    async upSuccess(res) {
      this.$message.closeAll();
      this.$message({
        showClose: true,
        message: `成功（${res.data.success}）`,
        type: "success",
        duration: 5000,
      });
      //导入成功
      this.diaUp = false;
      await this._QueryClazz(this.query.grade);
      this._QueryData();
    },
    //添加学生
    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("学生姓名已存在");
            this.loading = false;
            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;
            await this._QueryClazz(this.query.grade);
            this._QueryData();
          } else {
            this.$message.error(info);
          }
        } else {
          this.loading = false;
          this.$message.error("数据有误，请检查！");
        }
      });
    },
    //学生调班轨迹
    sayChange(obj) {
      this._StudentClassLogs(obj);
      this.diaChangeClassTrack = true;
    },
    //学生调班弹窗
    openChangeClazz(obj) {
      console.log(obj);
      if (this.query.grade == 80 || !this.query.grade) {
        this._QueryClazz(obj.grade);
      }
      this.formStuCla.classId = "";
      this.formStuCla.studentId = obj.id;
      this.formStuCla.className = obj.classList && obj.classList[0]?.className;
      this.formStuCla.studentName = obj.studentName;
      this.formStuCla.studentCode = obj.studentCode;
      this.formStuCla.oldClassId = obj.classList && obj.classList[0]?.id;
      this.diaChangeClass = true;
    },
    //学生调班
    changeStu: _.throttle(
      function () {
        this.$refs.formStuCla.validate(async (valid) => {
          if (valid) {
            // if (this.formStuCla.classId == this.formStuCla.oldClassId) {
            //   this.$message.warning("班级无变更～");
            //   return;
            // }
            const { data, status, info } =
              await this.$request.studentChangeClass({
                name: this.formStuCla.studentName,
                studentId: this.formStuCla.studentId,
                oldClassId: this.formStuCla.oldClassId,
                classId: this.formStuCla.classId,
                studentCode: this.formStuCla.studentCode,
              });
            if (status == 0) {
              this.diaChangeClass = false;
              this.$message.success(info);
              await this._QueryClazz(this.query.grade);
              this._QueryData();
            } else {
              this.$message.error(info);
            }
          } else {
            this.$message.error("数据有误请检查！");
          }
        });
      },
      2000,
      { leading: true, trailing: false }
    ),

    //学生调班轨迹
    async _StudentClassLogs(obj) {
      this.loadingClassLogs = true;
      let { data, info, status } = await this.$request.studentClassLogs({
        studentId: obj.id,
      });
      this.loadingClassLogs = false;
      if (status == 0) {
        this.formClassTrack.className =
          (obj.classList && obj.classList[0]?.className) || "";
        this.formClassTrack.studentName = obj.studentName;
        this.formClassTrack.classList = (data.list && [...data.list]) || [];
      } else {
        this.$message.error(info);
      }
    },
    async removeStu(obj, index, $event) {
      const { data, status, info } = await this.$request.delStudent({
        type: this.query.classType,
        studentId: obj.id,
        classId: this.query.classId,
      });
      if (status === 0) {
        this.$message.success("删除成功");
        await this._QueryClazz(this.query.grade);
        this._QueryData();
      } else {
        this.$message.error(info);
      }
    },
    async changeGrade(val) {
      if (!val) return;
      this.query.classId = "";
      this.query.studentName = "";
      this.query.studentCode = "";

      this.formStu.className = "";
      this.clazzDetail.stationSn = "";
      this.clazzDetail.pairingCode = "";
      this.clazzDetail.frequency = "";
      if (val != 80 && val != 81) {
        await this._QueryClass(val);
      }
      this._QueryData(3);
    },
    serQuery(type) {
      let query = {};
      if (type == 1) {
        this.query.classId = "";
        this.query.studentCode = "";
        this.query.grade = "";
        query.studentName = this.query.studentName;
        query.status = 9;
      } else if (type == 2) {
        this.query.classId = "";
        this.query.studentName = "";
        this.query.grade = "";
        query.studentCode = this.query.studentCode;
        query.status = 9;
      } else if (type == 3) {
        this.query.studentName = "";
        this.query.studentCode = "";
        if (this.query.grade == 80) {
          this.query.classId = "";
          query.status = -1;
        } else if (this.query.grade == 81) {
          this.query.classId = "";
          query.status = 2;
        } else {
          query.grade = this.query.grade;
          query.classId = this.query.classId;
        }
      } else {
        query = { ...this.query };
      }
      return query;
    },
    async _QueryData(type) {
      if (type == 1) {
        if (!this.query.studentName) {
          this.$message.warning("输入学生姓名～");
          return;
        }
      } else if (type == 2) {
        if (!this.query.studentCode) {
          this.$message.warning("输入学生学号～");
          return;
        }
      }
      let query = this.serQuery(type);
      this.loading = true;
      this.studentList = [];
      const { data, status, info } = await this.$request.studentList({
        type: this.query.classType,
        ...query,
      });
      this.loading = false;
      console.log(status);
      if (status === 0) {
        this.studentList = (data.list && [...data?.list]) || [];
      } else {
        this.$message.error(info);
      }
    },
    async _QueryDataGrade() {
      const { data, status, info } = await this.$request.gradeList();
      if (status === 0) {
        this.gradeList =
          data.list?.map((item) => {
            return {
              value: item.grade,
              label: item.gradeName,
            };
          }) || [];
        this.query.grade = this.gradeList[0]?.value;
      } else {
        this.$message.error(info);
      }
    },
    async _QueryClass(value) {
      this.loading = true;
      this.classList = [];
      const { data, status, info } = await this.$request.schoolClassList({
        grade: value || this.query.grade,
        type: this.query.classType,
      });
      if (status === 0) {
        this.classList = (data.list && [...data?.list]) || [];
        this.query.classId = this.classList[0]?.id;
        this.formStu.className = this.classList[0]?.className;
        this.clazzDetail.stationSn = this.classList[0]?.stationSn;
        this.clazzDetail.pairingCode = this.classList[0]?.pairingCode;
        this.clazzDetail.frequency = this.classList[0]?.frequency;
      } else {
        this.$message.error(info);
      }
    },
    async _QueryClazz(value) {
      this.classList = [];
      const { data, status, info } = await this.$request.schoolClassList({
        grade: value,
        type: this.query.classType,
      });
      if (status === 0) {
        this.classList = (data.list && [...data?.list]) || [];
      } else {
        this.$message.error(info);
      }
    },
    async downExcel() {
      this.loadingDown = true;
      let { data, info, status } =
        await this.$request.studentClickerTemplateUrl();
      this.loadingDown = false;
      if (status == 0) {
        const a = document.createElement("a");
        a.href = data.downloadUrl;
        document.body.appendChild(a);
        a.click();
        a.remove();
      } else {
        this.$message.error(info);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page-content {
  padding: 0 20px;
}

.tips {
  display: flex;
  line-height: 16px;
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
}

.total {
  padding: 0 20px 10px;
  font-size: 14px;
  color: #666;
}

.stu-box {
  display: flex;
  background: #f8f8f8;
  border-radius: 10px;
  overflow: hidden;

  .answer-header {
    padding-top: 10px;
  }

  .stu-list {
    min-width: 200px;
    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: 4px;
        font-size: 20px;
        display: none;

        &:hover {
          color: #667ffd;
        }
      }

      .popconfirm-box {
        position: absolute;
        top: 6px;
        right: 31px;
        font-size: 17px;
        line-height: 24px;
        display: none;

        &:hover {
          color: #667ffd;
        }
      }

      &:hover {
        background: #eee;

        .el-icon-edit-outline {
          display: block;
        }

        .popconfirm-box {
          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;
    min-height: 200px;

    &-tit {
      display: flex;
      justify-content: space-between;
    }

    .s-ul {
      display: flex;
      flex-wrap: wrap;
      padding: 12px 0 0 20px;

      .s-li {
        position: relative;
        box-shadow: 2px 2px 5px #7f7f7f;
        margin: 0 20px 20px 0;

        .s-li-box {
          width: 160px;
          border-radius: 10px;
          min-height: 120px;
          padding: 0 12px 5px;
          cursor: pointer;
        }

        .el-icon-user-solid {
          position: absolute;
          top: 8px;
          left: 8px;
          font-size: 18px;
          color: #666;
          padding: 2px;
          display: none;
          cursor: pointer;

          &:hover {
            color: #667ffd;
          }
        }

        .el-icon-delete {
          position: absolute;
          top: 8px;
          right: 8px;
          font-size: 18px;
          padding: 2px;
          display: none;
          cursor: pointer;

          &:hover {
            color: #667ffd;
          }
        }

        &:hover {
          .el-icon-user-solid {
            display: block;
          }

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

        .p2 {
          color: #333;
          line-height: 20px;
          padding-bottom: 5px;
        }
      }
    }
  }

  .clazz-detail {
    display: flex;
    padding: 12px 12px 0 20px;

    p {
      margin-right: 16px;
      color: #666;
    }
  }
}
</style>