<template>
  <div>
    <div class="video-container" v-if="boxShow">
      <div class="return-btn">
        <el-button type="primary" size="mini" icon="el-icon-d-arrow-left"
          @click="$router.push({ path: '/oa/study/myStudy' })">返回我的学习</el-button>
        <div class="mt20">
          学习进度：
          <el-progress :text-inside="true" :status="formatStatus(percentage)" text-color="#fff" :stroke-width="26"
            :percentage="percentage"></el-progress>
        </div>
        <div class="mt20" style="color:#E23D28;font-size:12px;line-height:30px;">
          tips:视频不可拖动进度条，每隔30秒会自动保存，暂停也会保存视频进度，若出现学习进度一直不到100%，请退出后重新进入课程。
        </div>
      </div>
      <video ref="videoPlayer" width="1300" height="750" class="custom-video video-js vjs-big-play-centered"
        @play="handlePlay" @pause="handlePause" @ended="handleEnd">
      </video>
      <el-alert v-if="showProgressTip" type="info" :closable="false" class="progress-alert">
        已为您定位到上次播放位置：{{ formatTime(lastPosition) }}
      </el-alert>
    </div>
    <div class="mt20 text-center" v-else>
      抱歉，暂不支持手机端，请前往电脑端观看学习
    </div>
  </div>
</template>

<script>
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import { listResource, getResource, delResource, addResource, updateResource } from "@/api/oa/study/resource";
import { listStudy, getStudy, delStudy, addStudy, updateStudy } from "@/api/oa/study/myStudy";

export default {
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      videoId: '',
      videoPath: '',
      player: null,
      lastPosition: 0,
      getHours: '', //可获得的学时
      isComplete: false, //是否已经看完
      showProgressTip: false,
      resource: {},
      // 禁用功能配置
      disabledControls: [
        'progressControl', // 隐藏进度条
        'seekBar',         // 禁用拖拽
        'remainingTimeDisplay',
        'playbackRateMenuButton'
      ],
      videoDuration: undefined,
      percentage: 0,
      boxShow: false,
    };
  },
  watch: {
    videoPath() {
      this.$nextTick(() => {
        const video = this.$refs.videoPlayer;
        if (!video) return;
        video.pause();
        video.removeAttribute("src");
        video.load();
        setTimeout(() => {
          video.src = this.fullVideoPath;
          video.load();
        }, 100);
      });
    }
  },
  computed: {
    fullVideoPath() {
      return `${process.env.VUE_APP_BASE_API}/profile/upload/${this.videoPath}`
    }
  },
  created() {
    if (this.$store.getters.device === 'mobile') {
      this.boxShow = false;
      return
    } else {
      this.boxShow = true;
    }
    this.getData();
  },
  mounted() {
    this.initPlayer();
    this.loadLastPosition();
  },
  methods: {
    async getData() {
      let studyId = this.$route.params.id;
      let resData = await getStudy(studyId);
      let data = resData.data
      this.resource = data.resource;
      this.videoPath = data.resource.sourcePath;
      this.percentage = Number(data.lastPoint);
      if (Number(data.lastPoint) > 0 && Number(data.lastPoint) < 100) {
        this.showProgressTip = true;
      }
      if (Number(data.lastPoint) == 100) {
        this.isComplete = true;
        this.getHours = data.resource.hours;
        this.$message.warning('视频已学习完毕，若要再次学习，请重新点击复习。')
      }
    },
    // 初始化播放器
    initPlayer() {
      const self = this;
      this.player = videojs(this.$refs.videoPlayer, {
        // 增加错误处理回调
        errorDisplay: false,
        autoplay: false,
        controls: true,
        sources: [{ src: this.fullVideoPath, type: 'video/mp4' }],
        controlBar: {
          // children: this.disabledControls,
          // 自定义禁止拖拽的进度条
          progressControl: false, // 关闭进度条
          volumePanel: true      // 启用音量控制
        },
        userActions: {
          hotkeys: false,
          // 禁用双击全屏
          doubleClick: false
        }
      });
      let retryCount = 0;
      // 增加错误监听
      this.player.on('error', () => {
        console.error('播放器错误:', this.player.error());
        if (retryCount < 3) {
          this.player.src(this.fullVideoPath);
          this.player.load();
          retryCount++;
        }
      });

      // 节流保存（每30秒保存一次）
      this.player.on('timeupdate', _.throttle(() => {
        this.saveCurrentPosition();
      }, 30000));
    },
    // 加载上次播放位置
    async loadLastPosition() {
      this.videoId = this.$route.params.id;
      try {
        const { data } = await getStudy(this.videoId);
        const percentage = data.lastPoint || 0;
        // 添加 readyState 检查
        const checkReady = () => {
          return new Promise(resolve => {
            if (this.player.readyState() >= 2) { // HAVE_CURRENT_DATA
              resolve();
            } else {
              this.player.one('loadedmetadata', resolve);
            }
          });
        };
        await checkReady();
        const duration = this.player.duration();
        const targetTime = duration * (percentage / 100);

        // 使用播放器原生方法
        this.player.currentTime(targetTime);
        this.lastPosition = targetTime;

      } catch (error) {
        console.error('加载进度失败:', error);
      }
    },

    // 处理播放事件
    handlePlay() {
      this.player.currentTime(this.lastPosition);
    },

    // 处理暂停事件
    handlePause() {
      this.saveCurrentPosition();
    },

    // 处理视频结束
    async handleEnd() {
      this.$message.warning('视频已学习完毕，若要再次学习，请重新点击复习。')
      await updateStudy({
        studyId: this.videoId,
        lastPoint: 100,
        getHours: this.resource.hours,
        lastTime: this.parseTime(new Date(), '{y}-{m}-{d}')
      });
    },
    // 保存当前进度
    async saveCurrentPosition(isEnd = false) {
      const currentTime = this.player.currentTime();
      const duration = this.player.duration();
      let percentage = isEnd ? 100 : Number(((currentTime / duration) * 100).toFixed(2));
      if (isNaN(percentage)) {
        return
      }
      this.percentage = Number(percentage)
      try {
        if (Number(percentage) == 100) {
          return
        }
        await updateStudy({
          studyId: this.videoId,
          lastPoint: percentage,
          getHours: Math.round((this.resource.hours * percentage) / 100),
          lastTime: this.parseTime(new Date(), '{y}-{m}-{d}')
        });
        // 始终更新 lastPosition（即使播放结束）
        this.lastPosition = currentTime;
      } catch (error) {
        console.error('保存进度失败:', error);
      }
    },

    // 时间格式化
    formatTime(seconds) {
      const date = new Date(0);
      date.setSeconds(seconds);
      return date.toISOString().substr(11, 8);
    },
    formatStatus(row) {
      if (!row) {
        row = 0
        return 'exception'
      }
      if (row <= 20) {
        return 'exception'
      } else if (row > 20 && row <= 50) {
        return 'warning'
      } else if (row > 50 && row <= 80) {
        return null
      } else {
        return 'success'
      }
    },
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose();
    }
  }
};
</script>

<style lang="scss" scoped>
.video-container {
  position: relative;

  .return-btn {
    position: absolute;
    left: 20px;
    top: 30px;
    width: 130px;
  }

  .custom-video {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, 0%);
  }

  .progress-alert {
    position: absolute;
    bottom: 40px;
    width: 100%;
    z-index: 1;
  }
}
</style>