<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <el-card style="height: 950px">
          <el-form
            :model="queryParams"
            style="border-bottom: 1px solid #dfe6ec; padding: 10px 0 0 5px"
          >
            <el-form-item label="班级信息" prop="schoolYear">
              <el-select
                v-model="queryParams.schoolYear"
                @change="getTreeData"
                style="width: 100%"
                size="mini"
              >
                <el-option
                  v-for="item in yearList"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item></el-form-item>
          </el-form>
          <el-tree
            ref="tree"
            node-key="id"
            :data="treeData"
            :expand-on-click-node="false"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          ></el-tree>
          <!--        </div>-->
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card style="height: 950px" class="mt50">
          <el-row>
            <el-col :span="8">
              <el-form
                :inline="true"
                :model="formData"
                style="padding: 12px 0 0 0"
              >
                <!--                <el-form-item>-->
                <!--                  <el-button type="primary" plain size="mini"-->
                <!--                             @click="printTable">打印-->
                <!--                  </el-button>-->
                <!--                </el-form-item>-->
                <el-form-item label="学期" prop="termId">
                  <el-select
                    v-model="formData.termId"
                    @change="courseInfo"
                    placeholder="请选择学期"
                  >
                    <el-option label="上学期" value="0"></el-option>
                    <el-option label="下学期" value="1"></el-option>
                  </el-select>
                </el-form-item>
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <el-button
                      type="success"
                      plain
                      icon="el-icon-upload"
                      size="mini"
                      @click="handleImport"
                    >导入
                    </el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button
                      type="warning"
                      plain
                      icon="el-icon-download"
                      size="mini"
                      @click="handleExport"
                    >导出
                    </el-button>
                  </el-col>
                </el-row>
              </el-form>
            </el-col>
            <el-col :span="8">
              <div
                class="trash"
                id="trashId"
                draggable
                @dragenter="trashDragenter"
                @dragover="trashDragover"
                @dragleave="trashDragLeave"
                @drop="trashDrop"
              >
                <i
                  style="font-size: 40px; pointer-events: none"
                  class="el-icon-delete"
                ></i>
              </div>
            </el-col>
            <el-col :span="5" :offset="3">
              <div
                style="
                  width: 100%;
                  display: flex;
                  justify-content: center;
                  flex-direction: column;
                  align-items: center;
                "
              >
                <el-button type="primary" plain @click="printTable"
                >打 印
                </el-button>
                <br/>
                <el-button
                  type="primary"
                  class="affirmCourse"
                  size="medium"
                  @click="getTableValue"
                >确认课表信息
                </el-button>
              </div>
            </el-col>
          </el-row>
          <br/>
          <el-row>
            <el-col :span="21">
              <div class="course">
                <el-table
                  id="postFormContainer"
                  v-loading="loading"
                  border
                  :key="Math.random()"
                  :row-style="{ height: '35px' }"
                  :cell-style="{ padding: '0', margin: '0' }"
                  :data="courseList"
                  :row-key="
                    (row) => {
                      return row.id;
                    }
                  "
                  height="710px"
                >
                  <el-table-column label="节次" min-width="90" align="center">
                    <template slot-scope="scope">
                      {{ scope.row.sortName }}
                    </template>
                  </el-table-column>
                  <el-table-column label="时间" align="center" min-width="90">
                    <template slot-scope="scope">
                      <span style="font-size: 8px">
                        {{ scope.row.startTime }}--{{ scope.row.endTime }}</span
                      >
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="monday.courseName"
                    label="周一"
                    min-width="100"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <div
                        draggable
                        @dragstart="
                          (res) => {
                            dragstart(res, scope.$index, 'monday');
                          }
                        "
                        @dragover="dragover"
                        @drop="
                          (res) => {
                            drop(res, scope.$index, 'monday');
                          }
                        "
                        @dragend="dragend"
                        class="dragBox"
                      >
                        {{ scope.row.monday && scope.row.monday.courseName }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="tuesday.courseName"
                    droppable
                    label="周二"
                    min-width="100"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <div
                        draggable
                        @dragstart="
                          (res) => {
                            dragstart(res, scope.$index, 'tuesday');
                          }
                        "
                        @dragover="dragover"
                        @drop="
                          (res) => {
                            drop(res, scope.$index, 'tuesday');
                          }
                        "
                        @dragend="dragend"
                        class="dragBox"
                      >
                        {{ scope.row.tuesday && scope.row.tuesday.courseName }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="周三" min-width="100" align="center">
                    <template slot-scope="scope">
                      <div
                        draggable
                        @dragstart="
                          (res) => {
                            dragstart(res, scope.$index, 'wednesday');
                          }
                        "
                        @dragover="dragover"
                        @drop="
                          (res) => {
                            drop(res, scope.$index, 'wednesday');
                          }
                        "
                        @dragend="dragend"
                        class="dragBox"
                      >
                        {{
                          scope.row.wednesday && scope.row.wednesday.courseName
                        }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="周四" min-width="100" align="center">
                    <template slot-scope="scope">
                      <div
                        draggable
                        @dragstart="
                          (res) => {
                            dragstart(res, scope.$index, 'thursday');
                          }
                        "
                        @dragover="dragover"
                        @drop="
                          (res) => {
                            drop(res, scope.$index, 'thursday');
                          }
                        "
                        @dragend="dragend"
                        class="dragBox"
                      >
                        {{
                          scope.row.thursday && scope.row.thursday.courseName
                        }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="周五" min-width="100" align="center">
                    <template slot-scope="scope">
                      <div
                        draggable
                        @dragstart="
                          (res) => {
                            dragstart(res, scope.$index, 'friday');
                          }
                        "
                        @dragover="dragover"
                        @drop="
                          (res) => {
                            drop(res, scope.$index, 'friday');
                          }
                        "
                        @dragend="dragend"
                        class="dragBox"
                      >
                        {{ scope.row.friday && scope.row.friday.courseName }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="周六" min-width="100" align="center">
                    <template slot-scope="scope">
                      <div
                        draggable
                        @dragstart="
                          (res) => {
                            dragstart(res, scope.$index, 'saturday');
                          }
                        "
                        @dragover="dragover"
                        @drop="
                          (res) => {
                            drop(res, scope.$index, 'saturday');
                          }
                        "
                        @dragend="dragend"
                        class="dragBox"
                      >
                        {{
                          scope.row.saturday && scope.row.saturday.courseName
                        }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="周日" min-width="100" align="center">
                    <template slot-scope="scope">
                      <div
                        draggable
                        @dragstart="
                          (res) => {
                            dragstart(res, scope.$index, 'sunday');
                          }
                        "
                        @dragover="dragover"
                        @drop="
                          (res) => {
                            drop(res, scope.$index, 'sunday');
                          }
                        "
                        @dragend="dragend"
                        class="dragBox"
                      >
                        {{ scope.row.sunday && scope.row.sunday.courseName }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
            <el-col :span="2" :offset="1">
              <div class="courseBox">
                <div
                  v-for="(item, index) in courseTypeList"
                  :key="item.courseName"
                  draggable
                  @dragstart="
                (res) => {
                  dragCloneStart(res, index);
                }
              "
                  class="courseClone"
                >
                  {{ item.courseName }}
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

    </el-row>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--<div class="el-upload__tip" slot="tip">-->
          <!--  <el-checkbox v-model="upload.updateSupport"/>-->
          <!--  是否更新已经存在的用户数据-->
          <!--</div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板
          </el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import printJS from "print-js";
import {
  getNewYear,
  getClassType,
  getCourseInfo,
  getClassTree,
  saveClassTable,
} from "@/api/smartSchool/teachAffairAdministration/lessonManage";
import {getYearList} from "@/utils/utilLibrary/getYearList";
import {
  getFirstLeafNode,
  handleTreeData,
} from "@/utils/utilLibrary/getTreeClass";
import {getToken} from "@/utils/auth";
import {commonUpload} from "@/api/common";

export default {
  name: "index",
  components: {
    draggable,
  },
  dicts: [
    "Grade",
    "Class",
    "grade_type",
    "sys_user_sex",
    "education",
    "student_type",
    "child_state",
  ],
  created() {
    this.handleYearList(); // 获取年份选择框数组
    this.getSession(); //判断当前时间节点处在上学期还是下学期
    this.classType(); //获取课程种类
    this.newYear(); //获取数据中的最近年份
    // this.getTreeData()   //获取班级下拉树数据
  },
  computed: {
    // 上传的地址
    url: function () {
      console.log('')
      return `${process.env.VUE_APP_BASE_API}/schoolTimeTable/importTable/${this.formData.classId}/${this.formData.termId}`;
    },
  },
  data() {
    return {
      currentTreeDatas: {},
      loading: false,
      //是克隆还是拖动
      state: "",
      //目标元素的DOM
      listText: "",
      //被拖动方的信息
      dragIndex: "",
      dragWeekNum: "",
      //目标方的信息
      dragAimIndex: "",
      dragAimWeekNum: "",
      courseTypeList: [], //课程列表
      courseList: [], //课程表信息
      trashZone: undefined,
      minHeight: window.innerHeight - 224,
      trashOptions: {
        group: {
          name: "trash",
          draggable: ".dropitem",
          put: () => true,
          pull: false,
        },
      },

      listDate: [],
      activeName: "0",
      weeks: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      tableDate: [[], [], [], [], [], [], []],
      weekIndex: "",
      courseIndex: "",
      treeData: [],
      queryParams: {
        schoolYear: "",
      },
      formData: {
        classId: "",
        termId: "",
      },
      yearList: [],
      // 课程表导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        // updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},

      },
    };
  },
  methods: {
    newYear() {
      getNewYear().then((res) => {
        // this.$set(queryParams, "schoolYear", Number(res.schoolYear))
        this.queryParams.schoolYear = res.schoolYear;
        this.getTreeData(); //关键性的一句
      });
    },

    /** 获取班级下拉树数据 */
    getTreeData() {
      getClassTree(this.queryParams)
        .then((response) => {
          this.$nextTick(() => {
            try {
              this.treeData = handleTreeData(
                response.data,
                this.dict.type.grade_type,
                this.dict.type.Grade
              );
            } catch (exception) {
              this.treeData = [];
            }
            const searchItem = getFirstLeafNode(this.treeData[0]);
            this.handleNodeClick.apply(undefined, [searchItem]);
          });
        })
        .catch((error) => {
        });
    },

    // 节点点击事件
    handleNodeClick(data) {
      this.currentTreeDatas = data
      this.formData.classId = data.id;
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(data.id);
      });
      this.courseInfo();
    },

    /*   ------------------安全线---------------------    */
    //获取课程种类列表
    classType() {
      getClassType().then((res) => {
        // this.courseTypeList = res.rows
        this.courseTypeList = res.rows.map((item) => {
          return {
            id: item.id,
            courseName: item.courseName,
          };
        });
      });
    },

    //上传课程表信息给后端保存
    getTableValue() {
      console.log(306);
      this.loading = true;
      console.log(this.courseList, 307);
      this.courseList.map((item) => {
        this.courseTypeList.map((items) => {
          if (item.monday["courseName"] == items["courseName"]) {
            item.monday["id"] = items.id;
          }
          if (item.tuesday["courseName"] == items["courseName"]) {
            item.tuesday["id"] = items.id;
          }
          if (item.wednesday["courseName"] == items["courseName"]) {
            item.wednesday["id"] = items.id;
          }
          if (item.thursday["courseName"] == items["courseName"]) {
            item.thursday["id"] = items.id;
          }
          if (item.friday["courseName"] == items["courseName"]) {
            item.friday["id"] = items.id;
          }
          if (item.saturday["courseName"] == items["courseName"]) {
            item.saturday["id"] = items.id;
          }
          if (item.sunday["courseName"] == items["courseName"]) {
            item.sunday["id"] = items.id;
          }
          // return items
        });
        return item;
      });
      saveClassTable(
        this.formData.classId,
        this.formData.termId,
        this.courseList
      )
        .then((res) => {
          if (res.code == 200) {
            this.loading = false;
            this.$modal.msgSuccess("录入成功");
          }
        })
        .catch((err) => {
          this.loading = false;
          this.$modal.msgError("录入失败");
        });
    },

    //获取课表信息
    courseInfo() {
      this.loading = true;
      getCourseInfo(this.formData)
        .then((res) => {
          //课表
          this.courseList = [];
          this.courseList = res.rows;
          this.loading = false;
        })
        .catch((err) => {
        });
    },

    //判断当前时间节点处在上学期还是下学期
    getSession() {
      let d = new Date();
      let n = d.getMonth() + 1;
      if (n >= 2 && n < 8) {
        //下学期
        this.formData.termId = "1";
      } else {
        //上学期
        this.formData.termId = "0";
      }
    },

    handleYearList() {
      // 获取年份选择框数组
      this.yearList = getYearList();
      let a = {};
      a.value = new Date().getFullYear() + 1;
      a.label = a.value + "年";
      this.yearList.unshift(a);
    },

    //拖动模块
    dragstart(event, index, weekNum) {
      // 作用于：被拖拽的元素
      this.dragIndex = index;
      this.dragWeekNum = weekNum;
      this.state = "drag";
      event.dataTransfer.setData("drag_text", event.target.innerHTML); //1.设置拖拽元素的DOM
    },

    //右侧课程盒子触发事件
    dragCloneStart(event, index) {
      // 作用于：被拖拽的元素
      console.log(390);
      this.dragIndex = index;
      this.state = "clone";
      // let item = event.target.cloneNode(true);
      // event.target.parentElement.insertBefore(item, event.target.parentElement.children[index + 1]);
      event.dataTransfer.setData("drag_text", event.target.innerHTML); //1.设置拖拽元素的DOM
    },

    dragover(event) {
      // 作用于：目标元素,每100ms刷新一次
      event.preventDefault(); // *********必须声明的事件***********
    },

    drop(event, index, weekNum) {
      event.preventDefault();
      //作用于：目标元素
      this.dragAimIndex = index;
      this.dragAimWeekNum = weekNum;
      this.listText = event.target.innerHTML; //3.获取到目标元素的DOM
      const drag_text = event.dataTransfer.getData("drag_text"); //2.获取到拖拽元素的DOM
      event.target.innerHTML = drag_text; //4.将目标元素更改为拖拽元素
      if (this.state == "clone") {
        console.log(this.dragAimIndex, this.dragAimWeekNum, 415);
        this.courseList[this.dragAimIndex][this.dragAimWeekNum]["courseName"] =
          this.courseTypeList[this.dragIndex]["courseName"];
      }
    },

    trashDragenter(event) {
      // 作用于：被拖拽的元素
      event.preventDefault();
      document.getElementById("trashId").style.background = "#fc0101";
    },
    trashDragover(event) {
      // 作用于：目标元素
      event.preventDefault(); // *********必须声明的事件***********
    },
    trashDragLeave(event) {
      // 作用于：被拖拽的元素
      event.preventDefault();
      document.getElementById("trashId").style.background = "white";
    },
    trashDrop(event) {
      //作用于：目标元素
      event.preventDefault();
      document.getElementById("trashId").style.background = "white";
      this.courseList[this.dragIndex][this.dragWeekNum]["courseName"] = null;
      this.courseList[this.dragIndex][this.dragWeekNum]["id"] = null;
    },

    dragend() {
      // 作用于：被拖拽的元素
      event.preventDefault();
      event.target.innerHTML = this.listText;
      if (this.state == "drag") {
        let temp =
          this.courseList[this.dragIndex][this.dragWeekNum]["courseName"];
        this.courseList[this.dragIndex][this.dragWeekNum]["courseName"] =
          this.courseList[this.dragAimIndex][this.dragAimWeekNum]["courseName"];
        this.courseList[this.dragAimIndex][this.dragAimWeekNum]["courseName"] =
          temp;
      }
    },

    // 打印
    printTable() {
      // 重置表单
      printJS({
        printable: "postFormContainer",
        maxWidth: 10000,
        header: "",
        ignoreElements: ["no-print", "back-no-print", "front-no-print"],
        targetStyles: ["*"],
        gridHeaderStyle: "border: 1px solid black",
        type: "html",
        gridStyle: `text-align: center; border: 1px solid black`,
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "课程表导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.handleNodeClick(this.currentTreeDatas)
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        {dangerouslyUseHTMLString: true}
      );
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data.url;
      this.commonUpload(file);
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 导出
    handleExport() {
      this.download(
        `/schoolTimeTable/exportTable/${this.formData.classId}/${this.formData.termId}`,
        {
          ...this.queryParams,
        },
        `课程表_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="less">
.course {
  height: 700px;
  //overflow-y: auto;
  //overflow-x: auto;
}
</style>
<style scoped>
.trash {
  text-align: center;
  width: 350px;
  height: 80px;
  border: solid 1px black;
  border-radius: 5px;
  float: left;
  line-height: 80px;
}

/*.trash:hover {*/
/*  background: red;*/
/*  color: #690202;*/
/*}*/

.courseBox {
  width: 100%;
  /*width: 200px;*/
  /*height: 400px;*/
  /*margin-top: 110px;*/
  /*background: #7a6df0;*/
  /*margin-left: 50px*/
}

.courseClone {
  /*background: #1ab394;*/
  border: 1px solid black;
  font-size: 18px;
  width: 100px;
  height: 50px;
  line-height: 40px;
  text-align: center;
}

.courseClone:hover {
  cursor: pointer;
  background: rgba(98, 200, 234, 0.85);
}

.dragBox {
  font-size: 20px;
  width: 100%;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.dragBox:hover {
  cursor: pointer;
  background: rgba(98, 200, 234, 0.85);
}

/deep/ .el-table .cell {
  padding-left: 0px;
  padding-right: 0px;
}

/*.dragBox[data-v-86c11aba] {*/
/*  font-size: 20px;*/
/*  width: 100%;*/
/*  height: 50px;*/
/*  line-height: 50px;*/
/*  text-align: center;*/
/*}*/

</style>




