<template>
  <view class="container" style="background-color: #fff; position: relative">
    <!-- <u-icon
		@click="goBack"
		name="arrow-left"
		color="#3ab3ae"
		size="20"
		:style="`display: inline-block; position: absolute; top: ${
		  statusBarHeight + 2
		}px; left: ${10}px;z-index: 999;`"
	  ></u-icon>-->
  
    <view style="width: 100%">
    
      <common-list-aliyun
        v-if="isSetFirstTime && videoData.playAuth"
        :encryptType="1"
        :vid="videoData.video"
        :playauth="videoData.playAuth"
        ref="player"
        :useFlashPrism="false"
        :autoplay="true"
        :isLive="false"
        :showBuffer="true"
        :cover="cover"
        :showBarTime="true"
        :disableSeek="true"
        showBarTime="500"
        width="300px"
        controlBarVisibility="always"
      >
      </common-list-aliyun>
  
    </view>
  </view>
</template>
<script>
import store from "@/store/index.js";
import $http from "@/config/requestConfig.js";
import { mapState, mapMutations } from "vuex";

// importScripts('@/static/aliplayer/aliplayer-min.js')
export default {
  props: ["currentVideo", "currentVideoList"],
  data() {
    return {
      platform: null,
      //当前是否是全屏模式
      isFullScreen: false,
      isfresh: false,
      isChange: false,
      isControl: true,
      timer: null,
      videoTitle: "",
      videoList: [],
      firstTime: 0,
      options: {},
      playAuth: "",
      currentTime: "",
      videoId: "",
      videoData: {},
      isSetFirstTime: false,
      screenType: null,
      videoUrl: null,
    };
  },
  computed: {
    ...mapState(["videoOssList"]),
  },

  watch: {
    currentVideo: {
      immediate: true,
      handler(newRoute) {},
    },
    timer(newValue) {
      this.$emit("child-event", newValue);
    },
  },

  // //页面显示
  mounted() {},
  beforeDestroy() {
    this.handleEnd();
    console.log("是否走啦习销毁");
    clearInterval(this.$store.state.videoTimer);
    // this.timer = null;
    // store.commit("setLoadingShow", null);
    plus.screen.lockOrientation("portrait-primary");

    console.log("是否走啦习销毁定时器", this.timer);
  },
  async onUnload() {
    uni.navigateTo({
      url: "/pages/curriculum/order/curriculum/back",
    });
    // #ifdef APP-PLUS
    plus.screen.lockOrientation("portrait-primary"); //锁死屏幕方向为竖屏

    // plus.screen.lockOrientation("portrait-primary");
    // #endif

    await this.setVideoTime();
    // this.player.dispose();
  },

  //第一次加载
  onLoad(options) {},

  methods: {
    changeVideoData() {
      this.isChange = false;
    },
    async changeVideo(data) {
      this.currentTime = "";
      this.firstTime = 0;
      this.isSetFirstTime = false;
      this.isChange = false;
      await this.init(data, true);
    },
    screenChange(data) {
      console.log(
        "status at line 这是当前的状态158:",
        data.status,
        data.primary
      );
      this.isFullScreen = !data.status;
      this.$emit("changeScreen", this.isFullScreen);
      // let fullScreen = e.detail.fullScreen; // 值true为进入全屏，false为退出全屏
      // if (!fullScreen) {
      //   //退出全屏
      //   this.isFullScreen = false;
      // } else {
      //   this.isFullScreen = true;
      // }
    },
    // 控制器的显示隐藏
    controlChange(e) {
      this.isControl = e.detail.show;
    },
    quitScreen() {
      // 退出全屏
      const ctx = this.$refs.myVideo;
      ctx.exitFullScreen();
    },
    // 播放进度改变
    videoTimeUpdateEvent(e) {
      this.playTime = parseInt(e.detail.currentTime);
      this.currentTime = parseInt(e.detail.currentTime);

      this.allTime = parseInt(e.detail.duration);

      this.recordTime({
        time: this.playTime,
      });
    },
    async init(data, isChange) {
      this.platform = this.$platform;
      this.isfresh = true;
      console.log("at line 59:", "是否先走init这里", this.platform);
      if (uni.getStorageSync("videoOssList")) {
        this.videoList = JSON.parse(uni.getStorageSync("videoOssList"));
      }
      this.options = data.currentVideo;

      this.videoId = this.options.video;
      console.log("这是苹果视屏id", this.videoId);
      await this.getLive(isChange);
      //   this.$emit("child-event", this.timer);
    },
    async getData(data, isChange) {
      if (!this.isSetFirstTime) {
        var netWork = data.userCourseVideoPositionEntity
          ? data.userCourseVideoPositionEntity.position
          : 0;
        var list = [];
        if (uni.getStorageSync("videoOssList")) {
          list = JSON.parse(uni.getStorageSync("videoOssList"));
          var index = list.findIndex((e) => e.id == data.id);

          if (netWork) {
            if (index >= 0) {
              this.firstTime =
                list[index].time > netWork ? list[index].time : netWork;
            } else {
              this.firstTime = netWork ? netWork : 0;
            }
          } else {
            if (index >= 0) {
              this.firstTime = list[index].time ? list[index].time : 0;
            } else {
              this.firstTime = 0;
            }
          }
        } else {
          this.firstTime = 0;
        }

        this.videoData = {
          ...data,
        };
        this.isChange = isChange ? isChange : false;
        // this.currentTime = this.firstTime;
        console.log(this.firstTime, "这是第一次播放时长222");
        // await this.setVideoTime();
        uni.setStorageSync("videoOssList", JSON.stringify(list));

        // if (this.currentVideo.type == 0 || this.currentVideo.type == 2) {
        //   await this.playVideo();
        // }
        console.log(this.firstTime, "这是第一次播放时长");

        this.isSetFirstTime = true;
      }
    },
    async playVideo(e) {
      this.videoContext = uni.createVideoContext("videoId", this);
      this.videoContext.seek(this.firstTime);

      //   this.videoContext.requestFullScreen();
    },
    recordTime(data) {
      this.currentTime = data.time;

      var list = [];
      if (uni.getStorageSync("videoOssList")) {
        list = JSON.parse(uni.getStorageSync("videoOssList"));
      }

      var index = list.findIndex((e) => e.id == this.videoData.id);
      if (list.length > 0 && index >= 0) {
        list[index] = {
          ...this.videoData,

          time: data.time,
        };
      } else {
        list.push({
          ...this.videoData,
          time: data.time,
        });
      }

      uni.setStorageSync("videoOssList", JSON.stringify(list));
    },
    // 获取数据
    async getLive(isChange) {
      var that = this;
      this.isfresh = false;
      var data = {
        ...this.options,
      };

      await $http
        .request({
          url: `sociology/course/checkVideo`,
          method: "Post", // POST、GET、PUT、DELETE，具体说明查看官方文档
          data,
          header: {
            //默认 无 说明：请求头
            "Content-Type": "application/json",
          },
        })
        .then(async (res) => {
          var data = {
            ...res.video,
          };
          if (this.currentVideo.type == 1) {
            var playAuth = res.video.playAuth.replace(/=/g, "");
            console.log("这是接口获取的视屏凭证111", playAuth);
            data = {
              ...data,
              videoId: res.video.video,
              playAuth: playAuth,
            };
            this.playAuth = playAuth;

            await that.getData(data, isChange);
          } else {
            console.log("这是接口获取的视屏凭证222", res.video, data);
            data = {
              ...data,
              playAuth: new Date().getTime(),
            };
            await that.getData(data, isChange);
          }
          console.log("是否获取到初始播放值", data);

          that.$forceUpdate();
        });
    },
    async handleEnd() {
      var list = JSON.parse(JSON.stringify(uni.getStorageSync("videoOssList")));
      var data = list.find((e) => e.id == this.videoData.id);
      this.currentTime = data.time;
      console.log(
        "this.currentTime at line 这是结束的时候掉的存储视频:",
        this.currentTime
      );
      clearInterval(this.$store.state.videoTimer);
      this.timer = null;

      await this.setVideoTime();
    },
    setVideoTime(time) {
      var data = {};
      // var list = uni.getStorageSync("videoOssList");

      // data = list.find((e) => e.id == this.videoData.id);
      // console.log("这是再走生命周期哦", this.currentTime);
      console.log("是否走了存储视屏," + this.videoData.id, this.currentTime);
      var data = {
        videoId: this.videoData.id,
        position: this.currentTime, //秒数
      };

      $http
        .request({
          url: `sociology/course/saveCoursePosition`,
          method: "Post", // POST、GET、PUT、DELETE，具体说明查看官方文档
          data,
          header: {
            //默认 无 说明：请求头
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          console.log("存储视屏时长接口返回信息", res);
          this.$forceUpdate();
        });
    },
    changePlayerTime(player) {
      console.log("this.firstTime at line 106:", this.firstTime);
      player.seek(this.firstTime);
    },
    goBack() {
      uni.navigateBack({
        delta: 1,
      });
    },

    async setVideoFirtsetTime(time) {
      this.currentTime = this.firstTime;
      console.log("这里准备开始设置播放时间:", this.currentTime);
      // await this.setVideoTime();
      // setTimeout(() => {
      // clearInterval(this.$store.state.videoTimer);

      store.commit(
        "setVideoTimer",
        setInterval(async () => {
          // if (this.currentTime) {
          await this.setVideoTime();
          // }
        }, 60000)
      );
      // }, 5000);
    },
  },

  created() {},
};
</script>

<style>
.container {
  width: 100vw;
  height: auto;

  /deep/.pause {
    width: 60rpx !important;
    height: 60rpx !important;
  }
}

.fds {
  background-color: blue;
  height: 600rpx;
  position: fixed;
  top: 60rpx;
}

.returnBack {
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  height: 88rpx;
  padding-left: 20rpx;
}

.txt {
  color: #fff;
}

.right_title {
  background: #000;
  height: 96rpx;
  justify-content: space-between;
  flex-direction: row;
  align-items: center;
  margin-left: auto;
}

.return {
  flex-direction: row;
  align-items: center;
  color: #fff;
}

.right_handle {
  width: 200rpx;
  flex-direction: row;
  justify-content: flex-end;
  padding-right: 20rpx;
}

cover-view {
  display: block;
  line-height: 1.2;
  overflow: hidden;
  white-space: nowrap;
  pointer-events: auto;
}

cover-view {
  visibility: visible !important;
}

cover-image {
  visibility: visible !important;
}

.fullScreenButton-container {
  color: #fff;
  float: right;
  height: 35px;
  margin-top: 6px;
  margin-right: 5px;
  display: flex;
  align-items: center;
  position: relative;

  i {
    color: #fff;
    display: inline-block;
    font-size: 22px;
    display: block;
    margin-top: 7px;
    cursor: pointer;

    & + i {
      margin-left: 3px;
    }

    @media (min-width: 768px) {
      &:hover + .player-tooltip {
        display: block;
      }
    }
  }

  .player-tooltip {
    &.prev {
      left: -10px;
    }

    &.list {
      left: 5px;
    }

    &.next {
      right: -12px;
    }
  }
}

.playlist-content {
  position: absolute;
  right: 0;
  width: 0px;
  padding-bottom: 48px;
  box-sizing: border-box;
  height: 100%;
  transition: all 0.38s ease-in-out;
  overflow: hidden;

  .list {
    background-color: #000;
    background-color: rgba(0, 0, 0, 0.3);
    height: 100%;
    overflow: auto;

    .video-item {
      color: #fff;
      padding: 0px 10px;
      line-height: 35px;
      font-size: 14px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      cursor: pointer;

      &.active {
        background-color: #000;
        color: #00ddff;
      }

      @media (min-width: 768px) {
        &:hover {
          background-color: #000;
          color: #00ddff;
        }
      }
    }
  }
}

.player-tooltip {
  position: absolute;
  display: none;
  font-size: 12px;
  color: #fff;
  line-height: 28px;
  letter-spacing: 0;
  text-align: center;
  background: #3c3c3c;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.1);
  height: 28px;
  top: -48px;
  padding: 0 5px;
  white-space: nowrap;
}

.playlist-skip-tip {
  padding: 5px 15px;
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 30;
  line-height: 30px;
  font-size: 14px;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.8);
  color: #000;
  text-align: center;
  transform: translate(-50%, -50%);
}

#rotating-div {
  width: 100vw;
  height: 100vh;
  background-color: #3498db;
  transform: rotate(90deg);
  /* 旋转90度 */
  transform-origin: center center;
  /* 设置旋转中心点在div中心 */
  position: fixed;
  /* 固定定位，全屏显示 */
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
}
</style>
