<template>
  <div
    class="pb_content"
    style="background: #fff; width: 98%; height: 95%; margin: 20px"
  >
    <div class="pb_head top">
      <span>学习资料</span>
      <div @click="addImg($event)">
        <input
          type="file"
          style="display: none"
          @change="beforeUpload1($event, 1)"
        />
        <div class="uploadThing">上传资料</div>
      </div>
    </div>
    <div class="pb_content_body" style="height: 70%">
      <div class="student_head">
        <div class="three">
          <div :class="choose == 0 ? 'choose' : ''" @click="sMtl(0)">
            第一天
          </div>
          <div :class="choose == 1 ? 'choose' : ''" @click="sMtl(1)">
            第二天
          </div>
          <div :class="choose == 2 ? 'choose' : ''" @click="sMtl(2)">
            第三天
          </div>
          <div :class="choose == 3 ? 'choose' : ''" @click="sMtl(3)">
            第四天
          </div>
          <div :class="choose == 4 ? 'choose' : ''" @click="sMtl(4)">
            第五天
          </div>
          <div :class="choose == 5 ? 'choose' : ''" @click="sMtl(5)">
            第六天
          </div>
          <div :class="choose == 6 ? 'choose' : ''" @click="sMtl(6)">
            第七天
          </div>
        </div>
      </div>
      <div class="student_table">
        <div class="boxCss">
          <div
            class="out_box"
            v-for="(item, index) in chapInfoNew"
            :key="index"
          >
            <div class="tup" v-if="item.fileT == 0">
              <img
                :src="
                  item.file.chapdataInfo
                    ? JSON.parse(item.file.chapdataInfo).url
                    : mtp
                "
                alt=""
                @click="
                  handlePictureCardPreview(
                    JSON.parse(item.file.chapdataInfo).url
                  )
                "
              />
              <div class="deleteWord" @click="deleteM(item.file.id)">
                <img src="../../assets/icon/delete.png" alt="" />
              </div>
            </div>
            <div class="tup" v-if="item.fileT == 1">
              <img
                src="../../assets/icon/stuVedio.png"
                alt=""
                @click="
                  handlePictureCardPreview(
                    JSON.parse(item.file.chapdataInfo).url
                  )
                "
              />
              <div class="deleteWord" @click="deleteM(item.file.id)">
                <img src="../../assets/icon/delete.png" alt="" />
              </div>
            </div>
            <div class="tup" v-if="item.fileT == 2">
              <img
                src="../../assets/icon/stuFile.png"
                alt=""
                @click="
                  handlePictureCardPreview(
                    JSON.parse(item.file.chapdataInfo).url
                  )
                "
              />
              <div class="deleteWord" @click="deleteM(item.file.id)">
                <img src="../../assets/icon/delete.png" alt="" />
              </div>
            </div>
            <div class="bottom_box">
              <div>
                {{
                  item.file.chapdataInfo
                    ? JSON.parse(item.file.chapdataInfo).name
                    : "图片暂无名称"
                }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="student_page">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="10"
          :total="total"
          v-if="page"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog :visible.sync="pictureDialog" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-dialog :visible.sync="vedioDialog" size="tiny">
      <video-player
        class="video-player vjs-custom-skin"
        ref="videoPlayer"
        :playsinline="true"
        :options="playerO"
        @play="onPlayerPlay($event)"
        style="width: 100%; height: 100%"
      ></video-player>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      choose: 0,
      chapInfo: [],
      chapInfoNew: [],
      cImgInfo: [],
      isLoading: false,
      noneBtnImg: false,
      mtp: require("../../assets/sp1.png"),
      //   msp: require("../../assets/sp1.png"),
      //   mfj: require("../../assets/yp1.png"),
      page: 1,
      total: 0,
      dialogImageUrl: "",
      userid: this.$route.query.userid,
      pictureDialog: false,
      vedioDialog: false,
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", //这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目   || "video/ogg"|| "video/webm"
            src: "", //url地址require("../../assets/media/aaa.mp4")
          },
        ],
        // poster: require("../../assets/tu31.png"), //你的封面地址
        // poster: dataRes.imgUrl, //你的封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, //当前时间和持续时间的分隔符
          durationDisplay: true, //显示持续时间
          remainingTimeDisplay: false, //是否显示剩余时间功能
          fullscreenToggle: true, //全屏按钮
        },
      },
      playerO: {},
    };
  },
  methods: {
    handleCurrentChange(val) {
      this.page = val;
      this.selectMtl();
    },
    addImg(e) {
      var el = e.currentTarget;
      el.getElementsByTagName("input")[0].click();
    },
    imgChange(file, fileList, type) {
      var _tmp = this.chapInfo;
      this.noneBtnImg = _tmp.length >= 1;
    },
    downFile(url) {
      window.open(url);
    },
    beforeUpload1(event, type) {
      var file = event.target.files[0];
      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(".")[file.name.split(".").length-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) {
            if (err) {
              var a = _this.$refs.upload1.uploadFiles;
              a.splice(a.length - 1, a.length);
              _this.$message.error("上传失败");
            } else {
              _this.cImgInfo.push({
                name: file.name,
                url: data.Location,
              });
              _this.addMtl();
              _this.cImgInfo = [];
              _this.selectMtl();
              _this.imgChange(null, null, type);
              console.log(data.Location);
            }
          });
      }
    },
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.pictureDialog = true;
    },
    handlePictureCardPreview1(url) {
      this.playerO = {};
      this.playerOptions.poster = "";
      this.playerOptions.sources[0].src = url;
      this.playerO = this.playerOptions;
      // this.dialogImageUrl = url;
      this.vedioDialog = true;
    },
    addMtl() {
      let params = {
        cInfo: this.cImgInfo[0],
        t: this.choose,
        cBy: this.userid,
      };
      this.ajax
        .get(this.$store.state.api + "addStuMtl", params)
        .then((res) => {
          this.$message.success("上传素材成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
    sMtl(type) {
      this.choose = type;
      this.selectMtl();
    },
    selectMtl() {
      this.isLoading = true;
      this.chapInfo = [];
      this.chapInfoNew = [];
      let params = {
        t: parseInt(this.choose),
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "selectStuMtl", params)
        .then((res) => {
          this.isLoading = false;
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          this.chapInfo = res.data[0];
          var a = ["BMP", "JPG", "JPEG", "PNG", "GIF"];
          var b = [
            "MP4",
            "MOV",
            "AVI",
            "WMV",
            "MPG",
            "MPEG",
            "RM",
            "RAM",
            "SWF",
            "FLV",
          ];
          var c = ["PPT", "PPTX", "PDF", "XLSX", "XLS", "DOC", "DOCX"];
          for (var i = 0; i < this.chapInfo.length; i++) {
            var d = JSON.parse(this.chapInfo[i].chapdataInfo).url;
            if (
              a.indexOf(
                d.split(".")[d.split(".").length - 1].toLocaleUpperCase()
              ) != -1
            ) {
              this.chapInfoNew.push({ file: this.chapInfo[i], fileT: 0 });
            } else if (
              b.indexOf(
                d.split(".")[d.split(".").length - 1].toLocaleUpperCase()
              ) != -1
            ) {
              this.chapInfoNew.push({ file: this.chapInfo[i], fileT: 1 });
            } else if (
              c.indexOf(
                d.split(".")[d.split(".").length - 1].toLocaleUpperCase()
              ) != -1
            ) {
              this.chapInfoNew.push({ file: this.chapInfo[i], fileT: 2 });
            }
          }
        })
        .catch((err) => {
          this.isLoading = false;
          console.error(err);
        });
    },
    deleteM(id) {
      this.isLoading = true;
      let params = {
        id: id,
      };
      this.ajax
        .get(this.$store.state.api + "deleteStuM", params)
        .then((res) => {
          this.isLoading = false;
          this.$message.success("删除成功");
          this.selectMtl();
        })
        .catch((err) => {
          this.isLoading = false;
          console.error(err);
        });
    },
    onPlayerPlay() {},
  },
  created() {
    this.selectMtl();
  },
};
</script>

<style scoped>
.student_head >>> .el-button--primary {
  background-color: #2268bc;
}
.student_head {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-direction: row;
  flex-wrap: nowrap;
}
.three {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 30px;
}

.three > div {
  cursor: pointer;
  margin-right: 40px;
}

.choose {
  border-bottom: 5px solid #3994fd;
}

.student_table {
  width: 100%;
  background: #f2f2f2;
  margin-top: 10px;
}

.tup {
  width: 200px;
  height: 191px;
  margin: 0 auto;
  position: relative;
}

.tup:hover .deleteWord {
  display: block;
}

.deleteWord {
  width: 25px;
  height: 25px;
  position: absolute;
  right: -25px;
  top: -10px;
  cursor: pointer;
  display: none;
}

.tup > img,
.deleteWord > img {
  width: 100%;
  height: 100%;
}

.out_box {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 250px;
  padding: 10px 0;
  background: #fff;
  margin: 0 25px 20px 0;
}

.bottom_box {
  display: flex;
  text-align: center;
  margin: 0 auto;
  padding: 10px 0 5px 0;
}
.bottom_box > div:nth-child(1) {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
  width: 200px;
}
.uploadThing {
  background: #2268bc;
  width: 90px;
  height: 35px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  line-height: 35px;
  cursor: pointer;
  border-radius: 4px;
}

.top {
  display: flex;
  justify-content: space-between;
}
.student_page {
  margin-top: 30px;
}
.boxCss {
  padding: 15px 0;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
}
</style>
