<template>
  <div class="pb_content2" style="background: #fff">
    <div class="pb_head">
      <van-icon
        name="arrow-left"
        color="#fff"
        class="pb_back"
        size="1.2rem"
        @click="goBack"
      />
      <span>提交作业</span>
    </div>
    <div class="pb_content_body">
      <div>
        <span>上传作业</span>
        <div class="myp_parent_textarea">
          <van-field
            v-model="message"
            rows="6"
            autosize
            type="textarea"
            placeholder="输入文字描述..."
            border
          />
        </div>
      </div>
      <div>
        <span>上传图片</span>
        <div>
          <!-- capture="camera"  -->
          <van-uploader
            v-model="fileList"
            :after-read="afterRead"
            preview-size="5rem"
            accept="image/*"
            v-loading="photoLoading"
          >
            <img src="../../assets/icon/photo.png" alt="" />
            <template #preview-cover>
              <div class=""></div>
            </template>
          </van-uploader>
          <!-- <div v-for="(item,idnex) in fileaaa" :key="idnex">
            {{ item.webkitRelativePath }} -- {{ item.name }}--{{ item.size }} --
            {{ item.type }}
          </div> -->
          <div>{{ error }}</div>
        </div>
      </div>
      <div>
        <span>上传视频</span>
        <div>
          <!-- capture="camera"   -->
          <van-uploader
            v-model="fileList2"
            :after-read="afterReadM"
            preview-size="5rem"
            accept="video/*"
            max-count="1"
            v-loading="mediaLoading"
            @click-preview="mediaPreview"
          >
            <img src="../../assets/icon/shipin.png" alt="" />
            <template #preview-cover>
              <div class=""></div>
            </template>
          </van-uploader>
          <!-- <div v-for="item in filebbb" :key="item.name">
            {{ item.webkitRelativePath }} -- {{ item.name }}--{{ item.size }} --
            {{ item.type }}
          </div> -->
          <!-- <div>{{fileMname}}</div> -->
        </div>
      </div>
      <div class="class_learn">
        <button @click="findWorkRepeat">提交作业</button>
      </div>
    </div>
    <van-overlay
      :show="show"
      @click="overlayShow"
      style="display: flex; align-items: center"
    >
      <div class="wrapper" @click.stop>
        <video-player
          class="video-player vjs-custom-skin"
          ref="videoPlayer"
          :playsinline="playsinline"
          @canplay="onPlayerCanplay($event)"
          :options="playerO"
          @play="onPlayerPlay($event)"
          style="width: 100%; height: 100%"
        ></video-player>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import "../../common/aws-sdk-2.235.1.min";

export default {
  data() {
    return {
      //   cid: this.$route.query.cid,
      message: "",
      fileList: [],
      fileList2: [],
      fileaaa: [],
      filebbb: [],
      now: null,
      photoLoading: false,
      mediaLoading: false,
      error: "",
      show: 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: {},
      fileMname: "",
    };
  },
  computed: {
    playsinline() {
      let ua = navigator.userAgent.toLocaleLowerCase();
      // x5内核
      if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
        return false;
      } else {
        // ios端
        return true;
      }
    },
  },
  methods: {
    overlayShow() {
      this.show = false;
      this.$refs.videoPlayer.player.pause();
    },
    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;
        }
      }
    },
    goBack() {
      this.$router.isBack = true;
      if (window.history.length <= 1) {
        this.$router.push({ path: "/" });
        return false;
      } else {
        this.$router.go(-1);
      }
    },
    //上传图片
    afterRead(file) {
      this.photoLoading = true;

      var _file = file.file;
      this.fileaaa.push(_file);
      file.status = "uploading";
      file.message = "上传中...";

      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;

      var mediaFormatList = ["png", "jpg", "jpeg"];

      if (
        mediaFormatList.indexOf(
          _file.name
            .split(".")
            [_file.name.split(".").length - 1].toLocaleLowerCase()
        ) == "-1"
      ) {
        _this.$toast.fail("请上传jpg或者png的图片格式文件");
        _this.fileList = _this.fileList.filter((fileA) => {
          return fileA.file.lastModified != file.file.lastModified;
        });
        file.status = "failed";
        file.message = "上传失败";
        this.photoLoading = false;

        return;
      }

      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.photoLoading = false;
            if (err) {
              _this.error = err;
              _this.$toast.fail("上传失败");
              file.status = "failed";
              file.message = "上传失败";
              //上传错误处理
              _this.fileList = _this.fileList.filter((fileA) => {
                return fileA.file.lastModified != _file.lastModified;
              });
            } else {
              //上传成功处理
              file.status = "success";
              // _file.url = data.Location;
              // _this.fileList.push(_file);
              _this.fileList = _this.fileList.filter((fileA) => {
                if (fileA.file.lastModified == _file.lastModified) {
                  fileA.url = data.Location;
                  return fileA;
                } else {
                  return fileA;
                }
              });
              console.log(data.Location);
            }
          });
      }
    },
    //上传视频
    afterReadM(file) {
      this.mediaLoading = true;
      var _file = file.file;
      this.filebbb.push(_file);
      file.status = "uploading";
      file.message = "上传中...";
      var renameReportFile = new File(
        [_file],
        "MEDIA" + new Date().getTime() + "." + _file.name.split(".")[1],
        { type: _file.type }
      );
      _file = renameReportFile;
      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.mediaLoading = false;
            if (err) {
              _this.$toast.fail("上传失败");
              file.status = "failed";
              file.message = "上传失败";
              //上传错误处理
              _this.fileList2 = _this.fileList2.filter((fileA) => {
                return fileA.file.lastModified != _file.lastModified;
              });
            } else {
              //上传成功处理
              file.status = "success";
              _this.fileList2 = _this.fileList2.filter((fileA) => {
                fileA.url = data.Location;
                var renameReportFile = new File(
                  [fileA.file],
                  "MEDIA." + fileA.file.name.split(".")[1],
                  { type: fileA.file.type }
                );
                fileA.file = renameReportFile;
                return fileA;
                // } else {
                //   return fileA;
                // }
              });
              console.log(data.Location);
            }
          });
      }
    },
    findWorkRepeat() {
      //   if (this.courseId == "") {
      //     this.$toast.fail("请选择课题");
      //     return;
      //   } else if (this.message == "") {
      //     this.$toast.fail("请填写作业描述");
      //     return;
      //   } else if (this.fileList.length == 0) {
      //     this.$toast.fail("请上传作业图片");
      //     return;
      //   } else if (this.fileList2.length == 0) {
      //     this.$toast.fail("请上传作业视频");
      //     return;
      //   }
      //   let params = {
      //     cid: this.cid,
      //     uid: this.$store.state.userInfo.userid,
      //     hid: this.courseId,
      //   };
      //   this.ajax
      //     .get(this.$store.state.api + "findWorkRepeat", params)
      //     .then((res) => {
      //       if (res.data[0].length) {
      //         this.$Dialog
      //           .confirm({
      //             title: "作业确认",
      //             message:
      //               "您已经提交了该作业了，如果您再提交将覆盖上次提交的作业！",
      //           })
      //           .then(() => {
      //             this.SubmitWork();
      //           })
      //           .catch(() => {
      //             // on cancel
      //           });
      //       } else {
      //         this.SubmitWork();
      //       }
      //     })
      //     .catch((err) => {
      //       console.error(err);
      //     });
      this.$toast.success("提交成功");
    },
    //提交作业
    SubmitWork() {
      if (this.time()) {
        var photo = [];
        var media = [];

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

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

        this.$store.commit("update", ["loading", true]);
        // 自定义加载图标
        this.$toast.loading({
          message: "提交中...",
          forbidClick: true,
          loadingType: "spinner",
          duration: 0,
        });
        let params = [
          {
            uid: this.$store.state.userInfo.userid,
            cid: this.cid,
            hid: this.courseId,
            ccontent: JSON.stringify({
              content: this.message,
              photo: photo.join(","),
              media: media.join(","),
            }),
          },
        ];
        this.ajax
          .post(this.$store.state.api + "submitWork", params)
          .then((res) => {
            this.$store.commit("update", ["loading", false]);
            this.$toast.success("提交成功");
            this.$router.go(-1);
          })
          .catch((err) => {
            this.$store.commit("update", ["loading", false]);
            this.$toast.fail("提交失败");
            console.error(err);
          });
      } else {
        return false;
      }
    },
    mediaPreview(file) {
      console.log(file);
      this.show = true;
      this.playerOptions.sources[0].src = file.url;
      this.playerO = this.playerOptions;
    },
    onPlayerCanplay() {},
    onPlayerPlay() {},
  },
  created() {},
};
</script>

<style scoped>
.myp_parent_textarea {
  width: 93%;
  margin: 0 auto;
  border: 1px solid rgb(207, 207, 207);
}
.van-cell {
  background: #fdfdfd;
}
.pb_content_body {
  font-size: 0.9rem;
  display: flex;
  flex-direction: column;
  /* justify-content: space-around; */
  width: 90%;
  margin: 0 auto;
}

.pb_content_body div {
  margin: 0.5rem 0 0;
}
.pb_content_body div > img {
  width: 5rem;
}
.pb_content_body .van-cell {
  margin: 0;
}
.sw_select >>> .el-input__inner {
  /* border: none !important; */
  border: 1px solid #eee !important;
}
.sw_select >>> .el-select {
  width: 12rem;
}
.class_learn button {
  color: white;
  background: rgb(81, 201, 154);
  border: none;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-size: 1rem;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
  transition: opacity 0.2s;
  height: 2rem;
  width: 100%;
  font-size: 0.8rem;
  line-height: 1.5rem;
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 11rem;
  width: 100%;
}
</style>
