<template>
  <view class="container" style="background-color: #000; position: relative">
    <u-icon
      @click="goBack"
      name="arrow-left"
      color="#3ab3ae"
      size="40"
      :style="`display: inline-block; position: absolute; top: ${
        statusBarHeight + 6
      }px; left: ${10}px;z-index: 999;`"
    ></u-icon>
    <div
      style="background-color: #000"
      ref="videoContent"
      @tap="renderScript.handleClick"
      id="url-player-test"
      :videoData="videoData"
      :firstTime="firstTime"
      :change:videoData="renderScript.receiveMsg"
      :change:firstTime="renderScript.receiveFirstTime"
    ></div>
    <div @tap="renderScript.emitData" ref="videoContent1" v-show="false">
      直接调用renderjs中的emitData的方法,传递当前播放时长
    </div>
    <div @tap="renderScript.endEmitData" ref="videoContent2" v-show="false">
      监听结束方法，记录播放时长
    </div>
  </view>
</template>
<script>
import $http from "@/config/requestConfig.js";
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      timer: null,
      videoTitle: "",
      videoList: [],
      firstTime: 0,
      options: {},
      playAuth: "",
      currentTime: "",
      videoId: "",
      videoData: {},
      isSetFirstTime: false,
      screenType: null,
    };
  },
  computed: {
    ...mapState(["videoOssList"]),
  },
  // //页面显示
  mounted() {},
  async onUnload() {
    uni.navigateTo({
      url: "/pages/curriculum/order/curriculum/back",
    });
    // #ifdef APP-PLUS
    plus.screen.lockOrientation("portrait-primary"); //锁死屏幕方向为竖屏

    // #endif
    this.timer = null;
    await this.setVideoTime();
    this.player.dispose();
  },

  //第一次加载
  onLoad(options) {
    console.log(options, "这是传参");
    // #ifdef APP-PLUS

    setTimeout(() => {
      plus.screen.unlockOrientation();
      plus.screen.lockOrientation("landscape-primary");
    }, 10);
    //	#endif

    if (uni.getStorageSync("videoOssList")) {
      this.videoList = JSON.parse(uni.getStorageSync("videoOssList"));
    }
    this.options = JSON.parse(options.data);

    this.videoId = this.options.video;

    this.timer = setInterval(() => {
      var that = this;
      if (this.currentTime) {
        that.setVideoTime();
      }
    }, 60000 * 10);
  },

  methods: {
    getData(data) {
      if (!this.isSetFirstTime) {
        var netWork = this.videoData.userCourseVideoPositionEntity
          ? this.videoData.userCourseVideoPositionEntity.position
          : 0;
        var list = JSON.parse(uni.getStorageSync("videoOssList"));
        var index = list.findIndex((e) => e.id == this.videoData.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;
          }
        }

        uni.setStorageSync("videoOssList", JSON.stringify(list));
        this.isSetFirstTime = true;
      }
    },
    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));
    },
    // 获取数据
    getLive() {
      var data = {
        ...this.options,
      };
      $http
        .request({
          url: `sociology/course/checkVideo`,
          method: "Post",
          data,
          header: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          var playAuth = res.video.playAuth.replace(/=/g, "");
          this.videoData = {
            ...res.video,
            videoId: res.video.video,
            playAuth: playAuth,
          };
          this.playAuth = playAuth;
          this.$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;

      await this.setVideoTime();
      this.timer = null;
    },
    setVideoTime(time) {
      var data = {
        videoId: this.videoData.id,
        position: this.currentTime, //秒数
      }
      $http
        .request({
          url: `sociology/course/saveCoursePosition`,
          method: "Post",
          data,
          header: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          this.$forceUpdate();
        });
    },
    changePlayerTime(player) {
      player.seek(this.firstTime);
    },
    goBack() {
      uni.navigateBack({
        delta: 1,
      });
    },
  },

  created() {
    this.getLive();
  },
};
</script>
<script module="renderScript" lang="renderjs">
export default {
	mounted() {
		this.loadWebPlayerSDK()
	},
	data() {
		return {
			player: null,
			curTime: null,
			curStatus: null
		}
	},

	watch: {
		curTime(val) {
			if (this.curTime !== null && this.curStatus !== null) {
				this.$refs.videoContent1.click()
			}
		}
	},

	methods: {
		handleClick(event, ownerInstance) {
			ownerInstance.callMethod('getData')

		},
		emitData(event, ownerInstance) {
			var that = this;
			ownerInstance.callMethod('recordTime', {
				time: that.curTime,
				status: that.curStatus
			})

		},
		endEmitData(event, ownerInstance) {
			ownerInstance.callMethod('handleEnd', )
		},
		getLive() {
			var player = new Aliplayer({
				id: "url-player-test",
				"vid": this.videoData
					.videoId, // 必选参数，可以通过点播控制台（路径：媒资库>音/视频）查询。示例：1e067a2831b641db90d570b6480f****。
				"playauth": this.videoData.playAuth, // 必选参数，参数值可通过调用GetVideoPlayAuth接口获取。
				"encryptType": 1, // 必选参数，当播放私有加密流时需要设置本参数值为1。其它情况无需设置。
				"playConfig": {
					"EncryptType": 'AliyunVoDEncryption'
				},
				width: '100%', //容器的大小
				height: '100%', //容器的大小

			}, function(player) {});
			this.player = player;
			//全屏播放

			player.one('canplay', function() {
				player.tag.play();

			});


			this.$refs.videoContent.click()

			var timer = setInterval(() => {
				var that = this;
				that.curTime = parseInt(this.player.getCurrentTime());
				that.curStatus = this.player.getStatus()

			}, 1000);
			this.player.on('ended', function() {
				this.$refs.videoContent2.click()

			})
		},
		receiveFirstTime(newValue, oldValue, ownerVm, vm) {
			if (this.player) {
				this.player.seek(newValue);
			}
		},
		checkValue() {
			if (!this.videoData.playAuth) {
				setTimeout(() => {
					this.checkValue();
				}, 1000);
			} else {

				this.getLive();
			}
		},
		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 = () => {
					this.checkValue();
					resolve();
				}
				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);
			});
		},
		loadComponent() {
			return new Promise((resolve, reject) => {
				const s_tag = document.createElement('script');
				s_tag.type = 'text/javascript';
				// 需要先下载组件 js 文件，放到项目 /static/ 目录下
				// 下载地址：https://github.com/aliyunvideo/AliyunPlayer_Web/blob/master/customComponents/dist/aliplayer-components/aliplayercomponents-1.0.9.min.js
				s_tag.src = './static/aliplayercomponents-1.0.9.min.js';
				s_tag.charset = 'utf-8';
				s_tag.onload = () => {
					resolve();
				}
				document.body.appendChild(s_tag);
			});
		}
	}
}
</script>
<style>
.container {
  width: 100vw;
  height: 100vh;
}
</style>
