<template>
  <div class="pb_content">
    <div class="pb_head top">
      <span>素材库</span>
      <div v-if="choose == 0" @click="addImg($event)">
        <input
          type="file"
          accept="image/png,image/gif,image/jpeg"
          style="display: none"
          @change="beforeUpload1($event, 1)"
        />
        <div class="uploadThing">上传图片</div>
      </div>
      <div v-if="choose == 1" @click="addImg($event)">
        <input
          type="file"
          accept="video/mp4,video/quicktime,video/x-msvideo"
          style="display: none"
          @change="beforeUpload2($event, 2)"
        />
        <div class="uploadThing">上传视频</div>
      </div>
      <div v-if="choose == 2" @click="addImg($event)">
        <input
          type="file"
          accept="application/pdf,.ppt,.pptx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
          style="display: none"
          @change="beforeUpload2($event, 3)"
        />
        <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>
      </div>
      <div class="student_table">
        <div v-if="this.choose == 0" class="boxCss">
          <div class="out_box" v-for="(item, index) in chapInfo" :key="index">
            <div class="tup">
              <img
                :src="
                  item.chapdataInfo ? JSON.parse(item.chapdataInfo).url : mtp
                "
                alt=""
                @click="
                  handlePictureCardPreview(JSON.parse(item.chapdataInfo).url)
                "
              />
              <div class="deleteWord" @click="deleteM(item.id)">
                <img src="../../assets/icon/delete.png" alt="" />
              </div>
            </div>
            <div class="bottom_box">
              <div>
                {{
                  item.chapdataInfo
                    ? JSON.parse(item.chapdataInfo).name
                    : "图片暂无名称"
                }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="this.choose == 1" class="boxCss">
          <div class="out_box" v-for="(item, index) in chapInfo" :key="index">
            <div class="tup">
              <img
                :src="msp"
                alt=""
                @click="
                  handlePictureCardPreview1(JSON.parse(item.chapdataInfo).url)
                "
              />
              <div class="deleteWord" @click="deleteM(item.id)">
                <img src="../../assets/icon/delete.png" alt="" />
              </div>
            </div>
            <div class="bottom_box">
              <div>
                {{
                  item.chapdataInfo
                    ? JSON.parse(item.chapdataInfo).name
                    : "图片暂无名称"
                }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="this.choose == 2" class="boxCss">
          <div class="out_box" v-for="(item, index) in chapInfo" :key="index">
            <div class="tup">
              <img
                :src="mfj"
                alt=""
                @click="downFile(JSON.parse(item.chapdataInfo).url)"
              />
              <div class="deleteWord" @click="deleteM(item.id)">
                <img src="../../assets/icon/delete.png" alt="" />
              </div>
            </div>
            <div class="bottom_box">
              <div>
                {{
                  item.chapdataInfo
                    ? JSON.parse(item.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: [],
      cImgInfo: [],
      isLoading: false,
      noneBtnImg: false,
      mtp: require("../../assets/tup1.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;
    },
    beforeUpload2(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 {
              if (type == 2) {
                _this.cImgInfo.push({
                  name: file.name,
                  url: data.Location,
                });
                _this.addMtl();
                _this.cImgInfo = [];
                _this.selectMtl();
                _this.imgChange(null, null, type);
              } else if (type == 3) {
                _this.cImgInfo.push({
                  name: file.name,
                  url: data.Location,
                });
                _this.addMtl();
                _this.cImgInfo = [];
                _this.selectMtl();
                _this.imgChange(null, null, type);
              }
              console.log(data.Location);
            }
          });
      }
    },
    addMtl() {
      let params = {
        cInfo: this.cImgInfo[0],
        t: this.choose,
        cBy: this.userid,
      };
      this.ajax
        .get(this.$store.state.api + "addMtl", params)
        .then((res) => {
          this.$message.success("上传素材成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
    sMtl(type) {
      this.choose = type;
      this.selectMtl();
    },
    selectMtl() {
      this.isLoading = true;
      let params = {
        t: parseInt(this.choose),
        page: this.page,
      };
      this.ajax
        .get(this.$store.state.api + "selectMtl", params)
        .then((res) => {
          this.isLoading = false;
          this.total = res.data[0].length > 0 ? res.data[0][0].num : 0;
          this.chapInfo = res.data[0];
        })
        .catch((err) => {
          this.isLoading = false;
          console.error(err);
        });
    },
    deleteM(id) {
      this.isLoading = true;
      let params = {
        id: id,
      };
      this.ajax
        .get(this.$store.state.api + "deleteM", 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_button {
																														display: flex;
																														overflow: hidden;
																														height: 40px;
																													} */
.student_head >>> .el-button--primary {
  background-color: #2268bc;
}
.student_head {
  display: flex;
  justify-content: space-between;
}
.three {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 200px;
  height: 30px;
}

.three > div {
  cursor: pointer;
}

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

.student_table {
  width: 100%;
  height: 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 15px 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 5px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
</style>
