<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-upload2"
            size="mini"
            plain
            circle
            @click="diaUp = true"
          ></el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="导出班级名单" placement="bottom">
          <el-button
            type="primary"
            icon="el-icon-download"
            size="mini"
            plain
            circle
            @click="exportTeacherExl"
          ></el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="分班" placement="bottom">
          <img @click="toArchived" src="../../../assets/images/fenban.png" class="fenban" alt="" />
        </el-tooltip>
      </template>
    </back-box>
    <div class="page-content">
      <div class="grade-box">
        <div class="grade-item" v-for="(item, index) in dataList">
          <p class="h-title">
            <span>{{ item.gradeName }}</span>
            <el-button
              class="sub-btn"
              type="info"
              size="mini"
              round
              plain
              @click="openSubject(item)"
              >科目管理({{ item.subjectNames.length }})</el-button
            >
            <span class="txt" v-if="index == 0">拖动班级进行排序</span>
          </p>
          <draggable
            tag="ul"
            class="grade-info"
            v-model="item.classList"
            @start="start"
            @end="end(item)"
            v-bind="{
              animation: 300,
            }"
          >
            <li class="clazz-li" v-for="clazz in item.classList" :key="item.id">
              <div class="clazz-item">
                <p class="clazz-name">
                  {{ clazz.className }}
                  <i
                    class="el-icon-edit"
                    @click.stop="setClass(clazz, item.gradeName)"
                  ></i>
                </p>
                <div class="clazz-class">
                  <span>学生：{{ clazz.studentCount }}个</span>
                  <span>教师：{{ clazz.teacherCount }}个</span>
                </div>
              </div>
            </li>
          </draggable>
        </div>
      </div>
    </div>
    <el-dialog title="导入班级名单" :visible.sync="diaUp" width="600">
      <up-load
        :url="url"
        @upSuccess="upSuccess"
        fileName="班级名单"
      >
        <p class="down-txt" slot="down">
          通过Excel名单导入班级名单，点击
          <el-link type="danger" @click="downExcel">模板下载</el-link> 。
        </p>
      </up-load>
      <div class="dialog-footer" slot="footer">
        <el-button @click="diaUp = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改班级" :visible.sync="diaClass" width="400">
      <el-form
        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="班级编码：">
          <el-col :span="10">
            <el-input maxlength="30" v-model.trim="formClass.classCode" />
          </el-col>
        </el-form-item>
        <el-form-item label="入学年份：">
          <el-col :span="10">
            <el-date-picker
              v-model="formClass.intoSchoolYear"
              type="year"
              placeholder="选择年"
            >
            </el-date-picker>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="_SaveClass" type="primary">确 定</el-button>
        <el-button @click="diaClass = false">取 消</el-button>
        <el-popconfirm title="确定删除该班级吗？" @confirm="_RemoveClass">
          <el-button class="el-button-del" slot="reference" type="danger" plain
            >删 除</el-button
          >
        </el-popconfirm>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="diaSubject" width="400">
      <p slot="title" class="dia-tit">
        {{ formClass.gradeName }}
        <span class="tips">（默认科目和已经有任课老师的提示不能删除）</span>
      </p>
      <el-form class="form-box" label-width="80px" v-loading="loadingSub">
        <el-form-item label="科目：">
          <div class="subject-box">
            <el-checkbox-group v-model="subjectNames">
              <p
                class="p1"
                v-for="(item, index) in subjectList"
                :key="item.default"
              >
                <el-checkbox v-if="!item.checked" :label="item.value">{{
                  item.value
                }}</el-checkbox>
                <el-input
                  class="sub-ipt"
                  v-else
                  v-model="item.value"
                  @keyup.enter.native="_EditSub(item)"
                ></el-input>
                <i
                  class="el-icon el-icon-edit"
                  v-show="!item.checked"
                  @click="item.checked = true"
                ></i>
                <i
                  class="el-icon el-icon-check"
                  v-show="item.checked"
                  @click="_EditSub(item)"
                ></i>
                <i
                  class="el-icon el-icon-close"
                  v-show="item.checked"
                  @click="resetSub(item)"
                ></i>
                <i
                  v-show="!item.checked"
                  class="el-icon el-icon-delete"
                  @click="_DelSubject(item, index)"
                ></i>
              </p>
            </el-checkbox-group>
          </div>
          <el-col :span="8">
            <el-input
              placeholder="添加科目"
              v-model.trim="subjectName"
              maxlength="30"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-plus"
                @click="addSubjectName"
              ></i>
            </el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="_SaveSubject" type="primary">确 定</el-button>
        <el-button @click="diaSubject = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { downloadFile } from "@/utils";
import draggable from "vuedraggable";
export default {
  components: {
    draggable,
  },
  data() {
    return {
      code: "",
      loading: false,
      loadingDown: false,
      loadingSub: false,
      diaUp: false,
      diaClass: false,
      diaSubject: false,
      subjectLoading: false,
      url: "/api_html/school/manager/importClassAndStudent",
      formClass: {
        //修改班级信息
        gradeName: "",
        className: "",
        classCode: "",
        intoSchoolYear: "",
      },
      rulesClass: {
        className: [
          { required: true, message: "请输入班级名称", trigger: "blur" },
        ],
      },
      subjects: [], //科目列表(只有科目)
      subjectList: [], //科目列表
      subjectNames: [], //已有科目
      subjectName: "", //要添加的科目
      dataList: [],
    };
  },
  async created() {
    this.code = localStorage.getItem("csCode") || "";
    this._QueryData();
    this._QuerySubject();
  },
  methods: {
    toArchived(){
      this.$router.push({
        path:'/archived'
      })
    },
    openSubject(obj) {
      this.formClass.gradeName = obj.gradeName;
      this.subjectNames = [...obj.subjectNames];
      this.diaSubject = true;
    },
    start(e) {
      console.log(e);
    },
    end(obj) {
      let classListIds = obj.classList.map((item) => {
        return item.id;
      });
      this._SaveComponents(classListIds);
    },
    upSuccess(res) {
      //导入成功
      this.$message.closeAll();
      this.$message({
        showClose: true,
        message: `成功（${res.data.success}）`,
        type: "success",
        duration: 5000,
      });
      this.diaUp = false;
      this._QueryData();
    },
    setClass(obj, gradeName) {
      this.formClass.gradeName = gradeName;
      this.formClass.classId = obj.id;
      this.formClass.className = obj.className;
      this.formClass.classCode = obj.classCode || "";
      this.formClass.intoSchoolYear = obj.intoSchoolYear
        ? obj.intoSchoolYear + ""
        : "";
      this.diaClass = true;
    },
    _RemoveClass() {
      this.$refs.formClass.validate(async (valid) => {
        if (valid) {
          const { data, status, info } = await this.$request.removeClass({
            classId: this.formClass.classId,
          });
          if (status === 0) {
            this.$message.success("修改成功");
            this.diaClass = false;
            this._QueryData();
          } else {
            this.$message.error(info);
          }
        } else {
          this.$message.warning("输入有误请检查！");
          return false;
        }
      });
    },
    _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._QueryData();
          } else {
            this.$message.error(info);
          }
        } else {
          this.$message.warning("输入有误请检查！");
          return false;
        }
      });
    },
    addSubjectName() {
      //添加科目
      if (!this.subjectName) {
        this.$message.warning("请填写科目名称");
        return;
      } else if (this.subjects.includes(this.subjectName)) {
        this.$message.warning("科目已存在，请重新填写～");
        return;
      }
      this.subjectList.push({
        default: this.subjectName,
        value: this.subjectName,
        checked: false,
      });
      this.subjectNames.push(this.subjectName);
      this.subjectName = "";
    },
    resetSub(item) {
      item.value = item.default;
      item.checked = false;
    },
    async _EditSub(item) {
      if (this.subjects.includes(item.value)) {
        this.$message.warning("科目已存在，请重新填写～");
        return;
      }
      item.checked = false;
      const { status, info } = await this.$request.updateSubject({
        subjectName: item.value,
        oldSubjectName: item.default,
      });
      if (status === 0) {
        this.$message.success(info);
        let idx = this.subjectNames.findIndex((sub) => item == sub);
        this.subjectNames.splice(idx, 1, item.value);
        item.default = item.value;
      } else {
        item.checked = true;
        this.$message.error(info);
      }
    },
    async _DelSubject(obj, index) {
      if (this.subjectLoading) return;
      this.subjectLoading = true;
      const { status, info } = await this.$request.delSubject({
        subjectName: obj.default,
      });
      this.subjectLoading = false;
      if (status === 0) {
        this.$message.success(info);
        this.subjectList.splice(index, 1);
        this._QueryData();
      } else {
        this.$message.error(info);
      }
    },
    async _SaveSubject() {
      //保存修改年级信息
      if (!this.subjectNames.length) {
        this.$message.error("请选择科目！");
        return;
      }
      this.loadingSub = true;
      const { status, info } = await this.$request.updateGrade({
        gradeName: this.formClass.gradeName,
        subjectNames: this.subjectNames,
      });
      this.loadingSub = false;
      if (status === 0) {
        this.$message.success("修改成功~");
        this.diaSubject = false;
        this._QueryData();
        this._QuerySubject();
      } else {
        this.$message.error(info);
      }
    },
    async _SaveComponents(classListIds) {
      this.loading = true;
      let { status, info } = await this.$request.classSort({
        classIds: [...classListIds],
      });
      this.loading = false;
      if (status === 0) {
        this.$message.success("调整成功！");
      } else {
        this.$message.error(info);
      }
    },
    async _QueryData() {
      this.loading = true;
      let { data, status, info } = await this.$request.classManager();
      this.loading = false;
      if (status === 0) {
        this.dataList = [...data.list] || [];
      } else {
        this.$message.error(info);
      }
    },
    async _QuerySubject() {
      const { data, status, info } = await this.$request.subjectList();
      if (status === 0) {
        this.subjects = [...data?.subjectNames] || [];
        this.subjectList =
          data?.subjectNames.map((item) => {
            return {
              default: item,
              value: item,
              checked: false,
            };
          }) || [];
      } else {
        this.$message.error(info);
      }
    },
    async downExcel() {
      let data = await this.$request.classAndStudentTemplate();
      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);
      }
    },
    async exportTeacherExl() {
      this.loadingDown = true;
      let data = await this.$request.exportClassAndStudent();
      this.loadingDown = false;
      if (data) {
        let blob = new Blob([data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        downloadFile(`班级名单.xlsx`, blob);
      } else {
        this.$message.error("下载失败");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.fenban{
  width:28px;
  margin-left:10px;
  cursor: pointer;
}
.page-tit {
  margin-bottom: 20px;
}
.page-content {
  padding: 20px;
}
.grade-box {
  background: #f8f8f8;
  padding: 12px 0;
}
.el-button-del {
  margin-left: 10px;
}
.h-title {
  display: flex;
  align-items: center;
  .sub-btn {
    margin-left: 30px;
  }
  .txt {
    margin-left: 30px;
    font-size: 13px;
    color: #666;
  }
}
.dia-tit {
  .tips {
    font-size: 12px;
  }
}
.grade-item {
  .grade-info {
    display: flex;
    flex-wrap: wrap;
    padding: 20px 20px 0;
    .clazz-li {
      margin-right: 30px;
      margin-bottom: 20px;
      position: relative;
      background: #fff;
      .el-icon-edit {
        cursor: pointer;
        display: none;
        &:hover {
          color: #667ffd;
        }
      }
      &:hover {
        .el-icon-edit {
          display: inline;
        }
      }
    }

    .clazz-item {
      width: 220px;
      box-sizing: border-box;
      padding: 16px;
      border-radius: 10px;
      box-shadow: 1px 1px 3px #888;
    }
    .clazz-name {
      font-size: 16px;
      font-weight: bold;
      line-height: 18px;
      padding-bottom: 12px;
    }
    .clazz-class {
      display: flex;
      justify-content: space-between;
      font-size: 15px;
    }
  }
}
.subject-box {
  overflow: hidden;
  position: relative;
  .p1 {
    line-height: 20px;
    margin-bottom: 10px;
  }
}
:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  .p1 {
    padding-right: 50px;
    position: relative;
    &:hover {
      .el-icon {
        display: block;
        &:hover {
          color: #667ffd;
        }
      }
      .is-checked ~ .el-icon-delete {
        display: none;
      }
    }
  }
  .el-icon {
    font-size: 14px;
    color: #999;
    position: absolute;
    right: 10px;
    top: 3px;
    cursor: pointer;
    display: none;
  }
  .el-icon-check,
  .el-icon-close {
    display: block;
  }
  .el-icon-edit,
  .el-icon-check {
    right: 28px;
  }
}
.sub-ipt {
  :deep(.el-input__inner) {
    height: 24px;
    line-height: 24px;
  }
}
.form-box {
  :deep(.el-form-item__label) {
    line-height: 28px;
  }
  .el-icon-plus {
    cursor: pointer;
    &:hover {
      color: #667ffd;
    }
  }
}
</style>