<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>
            <span class="s-num" v-if="item.classList"
              >（共{{ item.classList.length }}个班）</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">
                <i
                  class="el-icon-edit"
                  @click.stop="setClass(clazz, item.gradeName)"
                ></i>
                <p class="clazz-name ellipsis">
                  {{ clazz.className }}
                </p>
                <div class="clazz-class">
                  <p>学生：{{ clazz.studentCount }}个</p>
                  <p>教师：{{ clazz.teacherCount }}个</p>
                </div>
              </div>
            </li>
          </draggable>
        </div>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      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
      :close-on-click-modal="false"
      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
          v-if="!formClass.teacherCount && !formClass.studentCount"
          title="确定删除该班级吗？"
          @confirm="_RemoveClass"
        >
          <el-button class="el-button-del" slot="reference" type="danger" plain
            >删 除</el-button
          >
        </el-popconfirm>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :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, formatDate } from "@/utils";
import draggable from "vuedraggable";
export default {
  components: {
    draggable,
  },
  watch: {
    diaSubject: function (val) {
      if (!val) {
        this.subjectName = "";
        this.subjectList.map((item) => {
          item.checked = false;
        });
      }
    },
  },
  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: "",
        studentCount: "",
        teacherCount: "",
      },
      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();
      let txt = "";
      if (res.data.errorInfo && res.data.errorInfo.length) {
        res.data.errorInfo.map((item) => {
          txt += `<p style="padding-top:5px;">第${item.row}行：${item.error}</p>`;
        });
      }
      let sTxt = `<p>成功（${res.data.success}）</p>`;
      this.$message({
        showClose: true,
        dangerouslyUseHTMLString: true,
        message: sTxt + txt,
        type: "success",
        duration: 10000,
      });
      this.diaUp = false;
      this._QueryData();
    },
    setClass(obj, gradeName) {
      this.formClass.studentCount = obj.studentCount;
      this.formClass.teacherCount = obj.teacherCount;
      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;
    },
    async _RemoveClass() {
      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);
      }
    },
    _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,
            classCode: this.formClass.classCode,
            intoSchoolYear: formatDate(this.formClass.intoSchoolYear, "yyyy"),
          });
          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.subjects.push(this.subjectName);
      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;
      // }
      let idx = this.subjectNames.findIndex((sub) => item.default == sub);
      item.checked = false;
      const { status, info } = await this.$request.updateSubject({
        subjectName: item.value,
        oldSubjectName: item.default,
      });
      if (status === 0) {
        this.$message.success(info);
        this.subjectNames.splice(idx, 1, item.value);
        item.default = item.value;
      } else {
        item.value = item.default
        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.subjects.splice(index, 1);
        this.subjectNames.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;
  .s-num {
    font-size: 13px;
  }
  .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: 10px 20px 0;
    .clazz-li {
      margin-right: 20px;
      margin-bottom: 18px;
      position: relative;
      background: #fff;
      .el-icon-edit {
        cursor: pointer;
        display: none;
        &:hover {
          color: #667ffd;
        }
      }
      &:hover {
        .el-icon-edit {
          display: inline;
        }
      }
    }

    .clazz-item {
      width: 96px;
      padding: 14px 18px 14px 14px;
      border-radius: 10px;
      box-shadow: 1px 1px 3px #888;
      box-sizing: content-box;
      position: relative;
    }
    .el-icon-edit {
      position: absolute;
      right: 5px;
      top: 5px;
    }
    .clazz-name {
      font-size: 16px;
      font-weight: 700;
      line-height: 18px;
      padding-bottom: 6px;
      position: relative;
    }
    .clazz-class {
      // display: flex;
      // justify-content: space-between;
      font-size: 14px;
    }
  }
}
.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>