<template>
  <div style="width: 100%">
    <el-main>
      <div class="tou">课程管理</div>
      <div>
        <el-input
          v-model="courseName"
          style="width: 200px; margin: 15px 0px"
          placeholder="课程名称搜索"
          @keyup.enter.native="search"
          clearable
        ></el-input>
        <el-button slot="append" type="primary" @click="search">查询</el-button>
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :header-cell-style="{ background: '#f1f1f1', 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          style="width: 100%"
          :height="tableHeight"
          v-loading="isLoading"
        >
          <el-table-column prop="cuser" label="创建人" min-width="10">
            <template slot-scope="scope">
              <div>
                {{scope.row.name ? scope.row.name : scope.row.username}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="课程名称" min-width="25">
          </el-table-column>
          <el-table-column prop="time" label="创建时间" min-width="10">
          </el-table-column>
          <el-table-column label="操作" min-width="10">
            <template slot-scope="scope">
              <div class="pb_buttonBox">
                <el-button
                  size="mini"
                  type="primary"
                  @click="goTo('/course?index=1&id=' + scope.row.courseId)"
                  >查看</el-button
                >
                <!-- <el-button
                  size="mini"
                  type="primary"
                  @click="updatePop(scope.row.courseId)"
                  >修改</el-button
                > -->
                <el-button
                  size="mini"
                  type="primary"
                  @click="deleteCourse(scope.row.courseId)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="student_page">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="10"
          :total="total"
          v-if="!isListAjax && page"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-main>
    <el-dialog
      title="修改课程"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      width="550px"
      :before-close="handleClose"
      class="dialog_diy"
    >
      <div class="course_create_box">
        <div class="course_name">
          <span>课程名称</span>
          <el-input
            v-model="courseTitle"
            placeholder="请输入课程名字"
          ></el-input>
        </div>
        <div class="course_type">
          <div class="course_type1">
            <span>分类</span>
            <el-select
              v-model="group"
              placeholder="请选择分类"
              @change="getGPop"
            >
              <el-option
                v-for="item in groupList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </div>
          <div class="course_type2">
            <span>年级</span>
            <el-select v-model="classX" placeholder="请选择分类">
              <el-option value="" label="所有年级"></el-option>
              <el-option
                v-for="item in classListX"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </div>
          <div class="course_type2">
            <span>权限</span>
            <el-input v-model="className" placeholder="" disabled></el-input>
            <!-- <el-select v-model="Juri" placeholder="请选择权限">
              <el-option label="所有人" value="0"></el-option>
              <el-option
                v-for="item in JuriList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select> -->
          </div>
        </div>
        <div class="course_name">
          <span>课程海报</span>
          <!-- :on-success="handle_success" -->
          <!-- :before-upload="beforeUpload1" -->
          <el-upload
            action="#"
            list-type="picture"
            v-loading="uploadLoading1"
            :http-request="beforeUpload1"
            ref="upload1"
            :on-preview="handlePictureCardPreview"
            :on-remove="handle_remove1"
            :show-file-list="true"
            :file-list="fileList1"
            accept="image/*"
            :limit="1"
          >
            <!-- <i class="el-icon-plus"></i> -->
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
        <div class="course_name">
          <span>视频上传</span>
          <!-- :disabled="true" -->
          <el-upload
            action="#"
            ref="upload"
            list-type="text"
            v-loading="uploadLoading"
            :on-remove="handle_remove"
            :show-file-list="true"
            :http-request="beforeUpload"
            :file-list="fileList"
            accept="video/*"
          >
            <!-- <i class="el-icon-plus"></i> -->
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <!-- <el-input  placeholder="请输入视频名称" v-for="item in fileList" :key="item.file"></el-input> -->
        </div>
        <div class="course_name">
          <span>创建作业</span>
          <div class="homework_box">
            <div
              class="course_homework"
              v-for="(item, index) in itemCount"
              :key="index"
            >
              <el-image
                style="width: 35px; height: 50px"
                :src="require('../../assets/homework.png')"
                fit="contain"
              ></el-image>
              <el-input
                placeholder="请输入作业名称"
                v-model="homeworkList[index].name"
              ></el-input>
            </div>
            <div
              style="
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
              "
            >
              <el-button size="small" type="primary" @click="addHomeworkBox"
                >点击添加</el-button
              >
              <el-button
                size="small"
                type="primary"
                style="margin: 5px 0 0 0"
                @click="reduceHomeworkBox"
                v-if="itemCount > 1"
                >点击删除</el-button
              >
            </div>
          </div>
        </div>
        <div class="course_name">
          <span>课程简介</span>
          <!-- <el-input
            type="textarea"
            placeholder="请输入课程简介..."
            :rows="6"
            resize="none"
            v-model="courseText"
          ></el-input> -->
          <editor-bar
            v-model="courseText"
            :isClear="isClear"
            @change="change"
          ></editor-bar>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateA()">修 改</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible1" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import EditorBar from "../../components/tools/wangEnduit";

export default {
  components: { EditorBar },
  data() {
    return {
      tableHeight: 500,
      courseName: "",
      dialogVisible: false,
      tableData: [
      ],
      page: 1,
      total: 0,
      isLoading: false,
      itemCount: 1,
      courseTitle: "",
      courseText: "",
      fileList: [],
      fileList1: [],
      homeworkList: [{ name: "" }],
      group: "",
      Juri: "",
      className: "",
      groupList: [],
      // JuriList: [],
      uploadLoading1: false,
      uploadLoading: false,
      updateId: "",
      groupA: "",
      isClear: true,
      dialogVisible1: false,
      dialogImageUrl: "",
      classX: "",
      classListX: [],
      isListAjax: false,
    };
  },
  methods: {
    goTo(path) {
      this.$router.push(path);
    },
    change(val) {
      console.log(val);
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.getCourse();
    },
    addHomeworkBox() {
      this.homeworkList.push({ name: "" });
      this.itemCount++;
    },
    reduceHomeworkBox() {
      var a = this.homeworkList;
      a.splice(a.length - 1);
      this.itemCount--;
    },
    handle_remove(file, fileList) {
      var _tmp = this.fileList;
      for (var i = 0, len = _tmp.length; i < len; i++) {
        if (_tmp[i].uid == file.uid) {
          _tmp.splice(i, 1);
          break;
        }
        this.fileList = _tmp;
      }
    },
    init() {
      this.itemCount = 1;
      this.courseTitle = "";
      this.courseText = "";
      this.homeworkList = [{ name: "" }];
      this.fileList = [];
      this.fileList1 = [];
      this.group = "";
      this.classX = "";
      this.Juri = "";
      this.$refs.upload1 ? (this.$refs.upload1.uploadFiles.length = 0) : "";
      this.$refs.upload ? (this.$refs.upload.uploadFiles.length = 0) : "";
      this.updateId = "";
    },
    beforeUpload(data) {
      var file = data.file;
      this.uploadLoading = true;
      var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域

      var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
      var _this = this;

      if (file) {
        var params = {
          Key:
            file.name.split(".")[0] +
            new Date().getTime() +
            "." +
            file.name.split(".")[1],
          ContentType: file.type,
          Body: file,
          "Access-Control-Allow-Credentials": "*",
          ACL: "public-read",
        }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
        var options = {
          partSize: 2048 * 1024 * 1024,
          queueSize: 2,
          leavePartsOnError: true,
        };
        bucket
          .upload(params, options)
          .on("httpUploadProgress", function (evt) {
            //这里可以写进度条
            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
          })
          .send(function (err, data) {
            _this.uploadLoading = false;
            if (err) {
              var a = _this.$refs.upload.uploadFiles;
              a.splice(a.length - 1, a.length);
              _this.$message.error("上传失败");
            } else {
              //上传成功处理
              _this.fileList.push({
                name: file.name,
                url: data.Location,
                uid: file.uid,
              });
              console.log(data.Location);
            }
          });
      }
    },
    beforeUpload1(data) {
      this.$refs.upload1.uploadFiles;
      this.uploadLoading1 = true;
      var file = data.file;
      var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域

      var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
      var _this = this;

      if (file) {
        var params = {
          Key:
            file.name.split(".")[0] +
            new Date().getTime() +
            "." +
            file.name.split(".")[1],
          ContentType: file.type,
          Body: file,
          "Access-Control-Allow-Credentials": "*",
          ACL: "public-read",
        }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
        var options = {
          partSize: 2048 * 1024 * 1024,
          queueSize: 2,
          leavePartsOnError: true,
        };
        bucket
          .upload(params, options)
          .on("httpUploadProgress", function (evt) {
            //这里可以写进度条
            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
          })
          .send(function (err, data) {
            _this.uploadLoading1 = false;
            if (err) {
              var a = _this.$refs.upload1.uploadFiles;
              a.splice(a.length - 1, a.length);
              _this.$message.error("上传失败");
            } else {
              //上传成功处理
              _this.fileList1.push({
                name: file.name,
                url: data.Location,
                uid: file.uid,
              });
              console.log(data.Location);
            }
          });
      }
    },
    //获取分组分类
    getGroup() {
      let params = {};
      this.ajax
        .get(this.$store.state.api + "getGroup", params)
        .then((res) => {
          this.groupList = res.data[0];
          console.log(this.groupList);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //获取权限
    // getJuri() {
    //   let params = { cid: this.$store.state.userInfo.userid };
    //   this.ajax
    //     .get(this.$store.state.api + "getJuri", params)
    //     .then((res) => {
    //       this.JuriList = res.data[0];
    //       console.log(this.JuriList);
    //     })
    //     .catch((err) => {
    //       console.error(err);
    //     });
    // },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible1 = true;
    },
    handle_remove1(file, fileList) {
      var _tmp = this.fileList1;
      for (var i = 0, len = _tmp.length; i < len; i++) {
        if (_tmp[i].uid == file.uid) {
          _tmp.splice(i, 1);
          break;
        }
        this.fileList1 = _tmp;
      }
    },
    getCourse() {
      this.isLoading = true;
      let params = { cn: this.courseName, page: this.page };
      this.ajax
        .get(this.$store.state.api + "getCourseAdmin", params)
        .then((res) => {
          this.isListAjax = false;
          this.isLoading = false;
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          this.tableData = res.data[0];
        })
        .catch((err) => {
          this.isLoading = false;
          console.error(err);
        });
    },
    changeHeight() {
      this.tableHeight =
        window.innerHeight - this.$refs.table.$el.offsetTop - 200;
      if (this.tableHeight <= 530) {
        this.tableHeight = 530;
      }
      // 监听窗口大小变化
      let self = this;
      window.onresize = function () {
        self.tableHeight =
          window.innerHeight - self.$refs.table.$el.offsetTop - 200;
        if (self.tableHeight <= 530) {
          self.tableHeight = 530;
        }
      };
      // this.$refs.table.$el.offsetTop：表格距离浏览器的高度 //200表示你想要调整的表格距离底部的高度（你可以自己随意调整），因为我们一般都有放分页组件的，所以需要给它留一个高度
    },
    time() {
      if (!this.now) {
        this.now = new Date().getTime();
        return true;
      } else {
        let time = new Date().getTime();
        if (time - this.now > 3000) {
          this.now = time;
          return true;
        } else {
          return false;
        }
      }
    },
    search() {
      this.page = 1;
      this.isListAjax = true;
      this.getCourse();
    },
    //删除课程
    deleteCourse(cid) {
      let params = [{ cid: cid }];
      if (this.time()) {
        this.$confirm("确定删除此课程吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.ajax
              .post(this.$store.state.api + "deleteCourseAdmin", params)
              .then((res) => {
                this.$message({
                  message: "删除成功",
                  type: "success",
                });
                if (this.page != 1 && this.tableData.length == 1) {
                  this.page--;
                }
                this.getCourse();
              })
              .catch((err) => {
                this.$message.error("修改失败");
                console.error(err);
              });
          })
          .catch(() => {});
      }
    },
    //uuid生成
    guid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
          var r = (Math.random() * 16) | 0,
            v = c == "x" ? r : (r & 0x3) | 0x8;
          return v.toString(16);
        }
      );
    },
    handleClose(done) {
      this.init();
      done();
    },
    //修改课程
    updatePop(id) {
      this.init();
      let params = { cid: id };
      this.updateId = id;
      this.ajax
        .get(this.$store.state.api + "getCourseDetail", params)
        .then((res) => {
          this.courseTitle = res.data[0][0].title;
          this.group = res.data[0][0].groupid;
          this.getGPop();
          this.Juri = res.data[0][0].juri;
          this.classX = res.data[0][0].classx;
          this.className = res.data[0][0].classnameA
            ? res.data[0][0].classnameA
            : "所有人";
          var chap = JSON.parse(res.data[0][0].chapters);
          this.fileList1.push({
            name: chap.poster.split("//")[1].split("/")[1].split(".")[0],
            url: chap.poster,
          });
          for (var i = 0; i < chap.midia.split(",").length; i++) {
            this.fileList.push({
              name: chap.midia.split(",")[i].split("//")[1].split("/")[1],
              url: chap.midia.split(",")[i],
            });
          }
          // this.homeworkList.length = 0;
          this.itemCount = chap.homework.length;
          this.homeworkList = [];
          for (var i = 0; i < chap.homework.length; i++) {
            this.homeworkList.push({
              hid: chap.homework[i].hid,
              name: chap.homework[i].name,
            });
            // homeA.push({ hid: this.guid(), name: this.homeworkList[i] });
          }
          this.courseText = res.data[0][0].brief;
          this.dialogVisible = true;
          this.updateBoolean = true;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //修改课程
    updateA() {
      if (this.courseTitle === "") {
        this.$message.error("请输入课程名称");
        return;
      } else if (this.group === "") {
        this.$message.error("请选择课程分类");
        return;
      } else if (this.Juri === "") {
        this.$message.error("请选择课程权限");
        return;
      } else if (this.fileList1.length == 0) {
        this.$message.error("请上传课程海报");
        return;
      } else if (this.fileList.length == 0) {
        this.$message.error("请上传课程视频");
        return;
      } else if (this.homeworkList.length == 0) {
        this.$message.error("请添加课程作业");
        return;
      } else if (this.courseText === "") {
        this.$message.error("请输入课程简介");
        return;
      }
      for (var i = 0; i < this.homeworkList.length; i++) {
        if (this.homeworkList[i].hid && this.homeworkList[i].name == "") {
          this.$message.error("不能把已有的作业修改成空");
          return;
        }
      }
      var photo = [];
      var media = [];

      for (var i = 0; i < this.fileList1.length; i++) {
        photo.push(this.fileList1[i].url);
      }

      for (var i = 0; i < this.fileList.length; i++) {
        media.push(this.fileList[i].url);
      }

      var homeA = [];
      for (var i = 0; i < this.homeworkList.length; i++) {
        if (this.homeworkList[i].name === "") {
        } else if (this.homeworkList[i].hid) {
          homeA.push({
            hid: this.homeworkList[i].hid,
            name: this.homeworkList[i].name,
          });
        } else {
          homeA.push({ hid: this.guid(), name: this.homeworkList[i].name });
        }
      }
      var chap = {
        homework: homeA,
        midia: media.join(","),
        poster: photo.join(","),
      };
      let params = [
        {
          cid: this.updateId,
          t: this.courseTitle,
          gid: this.group,
          class: this.classX,
          j: this.Juri,
          chap: JSON.stringify(chap),
          b: this.courseText.replace(/%/g, "%25"),
        },
      ];
      if (this.time()) {
        this.$confirm("确定修改此课程吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.ajax
              .post(this.$store.state.api + "updateCourse", params)
              .then((res) => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });

                this.getCourse();
                this.init();
                this.dialogVisible = false;
              })
              .catch((err) => {
                this.$message.error("修改失败");
                console.error(err);
              });
          })
          .catch(() => {});
      }
    },
    getGPop() {
      this.classX = "";
      let params = { pid: this.group };
      this.ajax
        .get(this.$store.state.api + "getGroupGrade", params)
        .then((res) => {
          this.classListX = res.data[0];
        })
        .catch((err) => {
          console.error(err);
        });
    },
  },
  created() {
    this.$nextTick(function () {
      this.page = 1;
      this.getCourse();
      this.changeHeight();
      // this.getGroup();
      // this.getJuri();
    });
  },
};
</script>

<style scoped>
.tou {
  border-bottom: 1px solid #c9c9c9;
  height: 50px;
  font-size: 30px;
}
.dialog_diy >>> .el-dialog__header {
  background: #3d67bc !important;
  padding: 15px 20px;
}
.dialog_diy >>> .el-dialog__title {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn {
  top: 19px;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}
.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close:hover {
  color: #fff;
}
.student_page {
  margin-top: 15px;
}

.course_create_box {
  font-size: 18px;
}
.course_name {
  margin-top: 10px;
}
.course_name span {
  margin-bottom: 10px;
  display: block;
}
.homework_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.course_homework {
  width: 130px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  margin: 0 10px 10px 0;
}
.course_type {
  margin-top: 10px;
  display: flex;
}
.course_type1 span {
  margin-bottom: 10px;
  display: block;
}
.course_type2 {
  margin-left: 20px;
}
.course_type2 span {
  margin-bottom: 10px;
  display: block;
}
</style>
