<template>
   
  <view
    class="container"
    id="Aliyun"
    :style="`background-color:# 000; position: relative; padding: 0`"
  >
    <div
      :videoData="videoData"
      style="color: #fff"
      ref="AliyunFresh"
      @tap="renderScript.handleClick"
      v-show="false"
      :change:videoData="renderScript.receiveMsg"
    ></div>

    <view
      v-if="show"
      style="
        width: 100%;
        height: 200px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 38rpx;
        text-align: center;
      "
    >
      此设备暂不支持观看当前视频<br />请移步到安卓手机进行学习！
    </view>
    <view v-else>
      <template v-if="showAliYunPlayer">
        <common-list-audio
          id="commonAudio"
          :showAliYunPlayer="showAliYunPlayer"
          @handleSuccessDispose="handleSuccessDispose"
          ref="commonVideoAliyun1"
          v-if="videoInfo.type == 2"
          :videoData="videoData"
          :currentVideoIndex="currentVideoIndex"
          :videoInfo="videoInfo"
          :curriculumData="curriculumData"
          :firstTime="firstTime"
        >
        </common-list-audio>
        <common-list-aliyun
          id="AliPlayer"
          :showAliYunPlayer="showAliYunPlayer"
          @handleSuccessDispose="handleSuccessDispose"
          ref="commonVideoAliyun"
          v-if="videoInfo.type != 2"
          :videoData="videoData"
          :firstTime="firstTime"
        >
        </common-list-aliyun>
      </template>

      <view v-else style="height: 200px"> </view>
    </view>
  </view>
</template>
<script>
import store from "@/store/index.js";
import $http from "@/config/requestConfig.js";
import { mapState, mapMutations } from "vuex";
import $ from "jquery";
export default {
  props: {
    currentVideoId: {
      type: Number,
      default: null,
    },
    currentVideoIndex: {
      type: Number,
      default: null,
    },
    curriculumData: {
      type: Object,
      default: {},
    },
    secondCountDown: {
      type: Number,
      default: null,
    },
    isfresh: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      showCountDown: false,
      playEndBlank: false,
      flag: false, //视频提示显示
      show: false, //视频提示显示
      // isfresh: false, //视频提示显示
      showAliYunPlayer: false, //视频提示显示
      content: "此设备暂不支持观看当前视频，请移步到安卓手机进行学习！",
      platform: null, //设备类型
      isFullScreen: false, //当前是否是全屏模式
      isOnLoad: false, //是否刷新
      isChange: false, //是否切换播放源
      videoList: [], //视频列表
      videoOssList: [], //本地视频列表
      options: {}, //父组件传参
      currentTime: "", //当前播放时间
      videoData: {}, //获取当前的播放信息，playAuth，m3u8url
      videoInfo: {}, //获取当前的播放信息，playAuth，m3u8url
      isSetFirstTime: false, //是否获取到初始播放时间
      firstTime: 0, //初始播放时间

      urlList: {
        checkVideo: "sociology/course/checkVideo",
      },
    };
  },
  computed: {
    // ...mapState(["videoOssList"]),
  },

  watch: {
    isOnLoad(newValue) {
      if (this.isOnLoad) {
        this.changeVideoData();
      }
    },
    timer(newValue) {
      this.$emit("child-event", newValue);
    },
    isfresh(newValue) {},

    videoOssList: {
      immediate: true,
      handler(newValue) {
        if (this.videoOssList.length > 0) {
          uni.setStorageSync("videoOssList", JSON.stringify(this.videoOssList));
        }
      },
    },
    currentVideoId: {
      immediate: true,
      handler(newValue) {
        if (newValue) {
          // if (!this.isfresh) {
          this.videoData = {};
          this.showAliYunPlayer = false;
          this.platform = this.$platform;
          this.show = false;
          this.isOnLoad = false;
          this.videoData = {};
          this.firstTime = 0;
          if (uni.getStorageSync("videoOssList")) {
            this.videoOssList = JSON.parse(uni.getStorageSync("videoOssList"));
          }
          this.$nextTick(() => {
            this.checkVideo();
          });
        }
      },
    },
  },
  //
  mounted() {},
  //子组件销毁前
  beforeDestroy() {
    plus.screen.lockOrientation("portrait-primary");
  },
  beforeUpdate() {},
  methods: {
    hideNextVideo() {
      this.showCountDown = false;
      this.playEndBlank = false;
      this.$emit("hideNextVideo");
    },
    destory() {
      if (this.showAliYunPlayer) {
        this.$nextTick(() => {
          this.$refs.commonVideoAliyun.destory();
          this.videoData = {};
        });
      }
    },
    handleSuccessDispose() {
      this.showAliYunPlayer = false;
      this.$emit("handleFresh", true);
    },
    //ios不能播放私有加密提示信息
    openShow() {
      this.show = true;
    },
    changeflag() {
      this.flag = 1;
    },

    changeVideoData() {
      if (this.videoData && this.videoData.id && this.flag == 1) {
        this.showAliYunPlayer = true;
      } else {
        this.showAliYunPlayer = false;
        setTimeout(() => {
          this.changeVideoData();
        }, 100);
      }
    },

    //获取 video 初始化信息 (播放凭证 + m3u8)
    async checkVideo() {
      await $http
        .request({
          url: this.urlList.checkVideo,
          method: "Post", // POST、GET、PUT、DELETE，具体说明查看官方文档
          data: {
            id: this.currentVideoId,
            loadAnimate: "none",
          },
          header: {
            "Content-Type": "application/json",
          },
        })
        .then(async (res) => {
          console.log("res at line 204:", res.video);
          var that = this;
          this.videoInfo = res.video;
          that.videoData = {
            id: that.currentVideoId,
            vid: res.video.video,
          };

          if (res.video.type == 1) {
            if (res.video.m3u8Url == null || res.video.m3u8Url == "") {
              //私有加密
              if (that.$platform == "ios") {
                that.show = true;
                return false;
              }
              that.videoData.playAuth = res.video.playAuth.replace(/=/g, "");
              that.videoData.encryptType = "1";
            } else {
              //标准加密
              that.videoData.source = res.video.m3u8Url;
            }
          } else {
            //mp4 mp3
            that.videoData.source = res.video.videoUrl;
          }

          var netWork = res.video.userCourseVideoPositionEntity
            ? res.video.userCourseVideoPositionEntity.position
            : 0;
          var list = [...that.videoOssList];
          if (list.length > 0) {
            list = [];
            var index = list.findIndex((e) => e.id == res.video.id);
            if (netWork) {
              if (index >= 0) {
                that.firstTime =
                  list[index].time > netWork ? list[index].time : netWork;
              } else {
                that.firstTime = netWork ? netWork : 0;
              }
            } else {
              if (index >= 0) {
                that.firstTime = list[index].time ? list[index].time : 0;
              }
            }
            if (res.video.duration - that.firstTime <= 2) {
              that.firstTime = 0;
            }
            that.videoOssList = [...list];
          }

          that.isOnLoad = true;
        });
    },
  },
};
</script>

<script module="renderScript" lang="renderjs">
import $ from "jquery";

export default {
	data() {
		return {

		};
	},

	watch: {

	},

	created() {

		if (typeof window.Aliplayer === 'function') {
		} else {
			// 动态引入较大类库避免影响页面展示
			this.loadWebPlayerSDK(); //引入播放器sdk、css
		}

	},

	mounted() {
		if (typeof window.Aliplayer === 'function') {
			this.initAliPlayer();
		}
	},
  destroyed(){
    $("#Aliyun").empty();
},
	methods: {

		handleClick(event, ownerInstance) {
			ownerInstance.callMethod("changeflag");
		},
		initAliPlayer() {
			this.$refs.AliyunFresh.click()
		},
    receiveMsg(newValue, oldValue, ownerVm, vm) {}, //是否刚开始设置播放时间
		//引入播放器sdk、css
		loadWebPlayerSDK() {
			return new Promise((resolve, reject) => {
				const s_tag = document.createElement("script"); // 引入播放器js
				s_tag.type = "text/javascript";
				s_tag.src =
					"https://g.alicdn.com/apsara-media-box/imp-web-player/2.20.3/aliplayer-min.js";
				s_tag.charset = "utf-8";
				s_tag.onload = () => {
					const s_tag1 = document.createElement("script"); // 引入播放器js
					s_tag1.type = "text/javascript";
					s_tag1.src =
						"https://player.alicdn.com/aliplayer/presentation/js/aliplayercomponents.min.js";
					s_tag1.charset = "utf-8";
					s_tag1.onload = () => {
						this.initAliPlayer();
						resolve();
					};
					document.body.appendChild(s_tag1);
				};
				document.body.appendChild(s_tag);

				const l_tag = document.createElement("link"); // 引入播放器css
				l_tag.rel = "stylesheet";
				l_tag.href =
					"https://g.alicdn.com/apsara-media-box/imp-web-player/2.20.3/skins/default/aliplayer-min.css";

				document.body.appendChild(l_tag);
			});
		},


	},
};
</script>

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

  /deep/.pause {
    width: 60rpx !important;
    height: 60rpx !important;
  }
}
.showCountDownd {
  box-sizing: border-box;
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.6);

  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: #fff;
  font-size: 38rpx;
  text-align: center;
  position: absolute;
  top: 0;
  right: 10rpx;
  z-index: 4;

  text {
  }
}
</style>
