<template>
  <div>
    <back-box>
      <template slot="title">
        <span>分班</span>
      </template>
    </back-box>
    <div class="page-content">
      <el-steps :active="step" align-center class="step">
        <el-step title="1 解散班级"></el-step>
        <el-step title="2 导入班级名单"></el-step>
        <el-step title="3 分班后任课老师"></el-step>
      </el-steps>
      <ul v-loading="loading">
        <li v-show="step == 0" style="padding:0px 200px;">
          <el-row class="row-subfix" style="margin-top: 20px;">
            <el-row class="row-subfix">
              <div class="row-line">
                <span class="line-subfix">选择年级：</span>
                <span class="line-value">
                  <el-select class="sel" v-model="grade" placeholder="选择年级" @change="changeGrade">
                    <el-option v-for="item in gradeList" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </span>
              </div>
            </el-row>
            <el-row class="row-subfix" style="margin-top: 20px;">
              <span class="line-subfix" style="float: left;">选择班级：</span>
              <div class="row-line"
                style="float: left;  background:rgb(245,247,250);padding:15px;width: calc(100% - 220px);  border-radius:5px;">
                <span class="line-value" style="min-height: 300px;border-radius: 4px; background: rgb(247,247,250);">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                    @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="checkedClass" style="margin-top: 15px;">
                    <el-checkbox v-for="(item, index) in classList" :label="item.id" :key="item.id">
                      {{ item.className }}
                    </el-checkbox>
                  </el-checkbox-group>
                </span>
              </div>
            </el-row>
          </el-row>
          <el-row class="row-subfix form-item" style="margin-top: 20px;">
            <span class="line-subfix" style="float: left;"> <i class="el-icon-warning" /></span>
            <div class="row-line" style="float: left; width: calc(100% - 220px);  border-radius:5px;">
              <div>请谨慎操作，班级归档后，学生解除班级关系且相关老师任课信息将不存在。</div>
              <div style="margin-top: 10px;opacity: 0.7;">如需保存解散前的班级名单与任课信息，可点击“保存名单”按钮。</div>
            </div>
          </el-row>
          <div style="margin:0px auto;width: 30%;">
            <el-button style="background: rgb(218,225,235) ;color:black;border:none !important;"
              @click="toClazz">取消</el-button>
            <el-button type="primary" @click="_downNameList">保存名单</el-button>
            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" title="确定要将所选班级解散吗吗？"
              @confirm="_ClassArchiving">
              <el-button slot="reference" v-loading="loadingDown"
                style="background: rgb(242,168,65) ;color:white;margin-left: 10px;border:none !important;">确定解散</el-button>
            </el-popconfirm>
          </div>
        </li>
        <li v-show="step == 1">
          <el-row class="row-subfix form-item">
            <div class="row-line" style="float: left;">
              <div>通过导入EXCEL文件方式添加班级名单，请按需求下载对应班级类型板并填写班级名单信息后，导入系统：</div>
              <div style="margin-top: 10px;opacity: 0.7;margin-left:20px;">
                行政班定义：由固定学生、固定教室构成，由专门的班主任进行管理;
              </div>
              <div style="margin-top: 5px;opacity: 0.7;margin-left:20px;">
                教学班定义：由不同行政班的学生临时组成，没有专门的班主任，是在选课制基础上，由于教学的需要而产生的。
              </div>
            </div>
          </el-row>
          <el-row class="row-subfix form-item" style="margin-top: 20px;">
            <el-button :icon="'el-icon-document'" @click="_downTemplate(0)">下载行政班名单模板</el-button>
            <el-button :icon="'el-icon-document'" @click="_downTemplate(1)">下载教学班名单模板</el-button>
          </el-row>
          <el-row class="row-subfix form-item" style="margin-top: 20px;">
            <upload id="downTeacher" drag :url="urlClazz"
              style="border:rgb(219,226,235) dashed 1px;width: 100%;padding:40px 0px;border-radius: 5px;"
              @upSuccess="upStudentSuccess" fileName="学生名单模板">
              <p class="down-txt" slot="down">
                通过Excel名单导入学生名单模板
              </p>
            </upload>
          </el-row>
        </li>
        <li v-show="step == 2">
          <el-row class="row-subfix form-item">
            <div class="row-line" style="float: left;">
              <div>通过导入EXCEL文件方式添加教师任课信息，请按需求下载板并填写任课信息后，导入系统:</div>
            </div>
          </el-row>
          <el-row class="row-subfix form-item" style="margin-top: 20px;">
            <el-button :icon="'el-icon-document'" @click="_downTemplate(2)">下载任课信息模板</el-button>
          </el-row>
          <el-row class="row-subfix form-item" style="margin-top: 20px;">
            <upload id="downTeacher" drag :url="urlTeacher"
              style="border:rgb(219,226,235) dashed 1px;width: 100%;padding:40px 0px;border-radius: 5px;"
              @upSuccess="upTeacherSuccess" fileName="任课老师名单模板">
              <p class="down-txt" slot="down">
                通过Excel名单导入任课老师名单模板
              </p>
            </upload>
          </el-row>
        </li>
        <li v-show="step != 0">
          <div class="btn-box">
            <el-button class="btn" round @click="step -= 1">上一步</el-button>
            <el-button v-show="step != 2" class="btn" type="primary" round @click="step += 1">下一步</el-button><el-button
              v-show="step == 2" class="btn" type="primary" round @click="toClazz">完成</el-button>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { downloadFile } from "utils";
export default {
  data() {
    return {
      loading: false,
      loadingClass: false,
      loadingDown: false,
      step: 0,
      grade: "",
      gradeList: [],
      checkAll: false,
      checkedClass: [],
      classList: [],
      urlClazz: "/api_html/school/manager/importClassAndStudent",
      urlTeacher: "/api_html/school/manager/importTeacher",
      isIndeterminate: true
    };
  },
  watch: {
    checkedClass(value) {
      this.checkAll = value.length == this.classList.length;
      this.isIndeterminate = value.length > 0 && value.length < this.classList.length;
    }
  },
  created() {
    this._QueryDataGrade();
  },
  methods: {
    async _downNameList() {
      this.loadingDown = true;
      await this.downStudentExcel();
      await this.downTeacherExcel();
      this.loadingDown = false;
    },
    handleCheckAllChange(val) {
      if (val) this.checkedClass = this.classList.map(item => item.id);
      else this.checkedClass = [];
    },
    async _downTemplate(type) {

      var template = type == 0 ? this.$request.classAndStudentTemplate : this.$request.tClassAndStudentTemplate;

      if (type == 2) template = await this.$request.teacherTemplate;
      console.log(type)
      let data = await template();

      if (data && !data.code) {

        let blob = new Blob([data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });

        downloadFile(type == 2 ? "教师任课信息" : type == 0 ? "行政班名单模板" : "教学班名单模板", blob);
      }
      else {
        this.$message.error(data.info);
      }
      // const classAndStudentTemplate =
      //   type == 0
      //     ? this.$request.classAndStudentTemplate ? type == 2 :
      //       await this.$request.teacherTemplate()
      //     : this.$request.tClassAndStudentTemplate;
      // let data = await classAndStudentTemplate();
      // if (data && !data.code) {
      //   let blob = new Blob([data], {
      //     type: "application/vnd.ms-excel;charset=utf-8",
      //   });
      //   downloadFile(type == 0 ? type == 2 ? "教师任课信息模板" : "行政班名单模板" : "教学班名单模板", blob);
      // } else {
      //   this.$message.error(data.info);
      // }
    },
    toClazz() {
      this.$router.push({
        path: "/setUpClazz",
      });
    },
    //切换年级
    changeGrade() {
      this._QueryClass();
    },
    //学生名单上传成功回调
    upStudentSuccess(res) {
      this.$message.closeAll();
      this.$message({
        showClose: true,
        message: `成功（${res.data.success}）`,
        type: "success",
        duration: 10000,
      });
    },
    //任课老师名单上传成功回调
    upTeacherSuccess(res) {
      this.$message.closeAll();
      this.$message({
        showClose: true,
        message: `成功（${res.data.success}）`,
        type: "success",
        duration: 10000,
      });
    },
    //导出学生名单
    async downStudentExcel() {

      const exportClassAndStudent = this.$request.exportClassAndStudent;

      let data = await exportClassAndStudent();

      if (data) {
        let blob = new Blob([data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        downloadFile(`班级名单.xlsx`, blob);
      } else {
        this.$message.error("下载失败");
      }
    },
    //导出任课老师名单
    async downTeacherExcel() {

      let data = await this.$request.exportTeacher();

      if (data) {
        let blob = new Blob([data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        downloadFile(`教师名单.xlsx`, blob);
      } else {
        this.$message.error("下载失败");
      }
      // let data = await this.$request.exportNoClassTeacher();

      // if (data) {
      //   let blob = new Blob([data], {
      //     type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      //   });
      //   downloadFile("未分配教师 名单.xlsx", blob);
      // } else {
      //   this.$message.error("下载失败");
      // }
    },
    //班级归档
    async _ClassArchiving() {
      if (!this.checkedClass.length) {
        this.$message.warning("班级不能为空，请选择班级～");
        return;
      }
      this.loading = true;
      const { status, info } = await this.$request.classArchiving({
        classIds: [...this.checkedClass],
      });
      this.loading = false;
      if (status === 0) {
        this.$message.success("班级归档成功！");
        this.step = 1;
        this._QueryDataGrade();
      } 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.grade = this.gradeList[0]?.value;
        this._QueryClass();
      } else {
        this.$message.error(info);
      }
    },
    //班级列表
    async _QueryClass() {
      this.classList = [];
      this.loadingClass = true;
      const { data, status, info } = await this.$request.schoolClassList({
        grade: this.grade,
        type: 0
      });
      this.loadingClass = false;
      if (status === 0) {
        this.classList = (data.list && [...data.list]) || [];
        this.checkedClass = this.classList.map(item => item.id);
      } else {
        this.$message.error(info);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.step {
  margin-bottom: 40px;
}

.form-item {
  width: 70%;
  display: flex;
  margin: 0 auto 20px;

  .check-box {
    flex: 1;
  }

  .all-check {
    margin-right: 30px;
  }

  &:first-of-type {
    .s-txt {
      line-height: 40px;
    }
  }

  .s-txt {
    width: 160px;
    flex-shrink: 0;
  }

  .sel {
    :deep(.el-input__inner) {
      border-radius: 20px;
    }
  }

  :deep(.el-checkbox) {
    margin-bottom: 12px;
  }

  .tips {
    display: flex;
    align-items: center;
    color: #666;
  }

  .el-icon-warning {
    font-size: 20px;
    color: #ec7f8c;
    margin-right: 10px;
  }
}

.btn-box {
  width: 80%;
  margin: 60px auto 0;
  display: flex;
  justify-content: flex-end;

  .btn {
    margin: 0 10px;
  }
}

.step-item {
  text-align: center;
}

.step-item2 {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #000;
  font-weight: 500;

  .p2 {
    font-size: 16px;
    margin: 0 0 20px -68px;

    .btn {
      margin-right: 14px;
    }
  }

  .p1 {
    width: 450px;
    text-align: left;
    margin-bottom: 20px;
  }
}

:deep(.down-txt) {
  justify-content: center;
  padding-left: 0;
}
</style>