<template>
  <div class="course-detail">
    <!-- 视频 -->
    <div class="video-box">
      <pica-video ref="picaVideo" :coverType="coverType" :download="btnClick1" @onVideoEnd="onVideoEnd" @onReplay="onReplay">
        <!-- 试看结束 -->
        <div class="cover" v-if="logged && coverType === 1">
          <course-covers
            coverTips="试看结束<br />请来云鹊医App学习完整课程"
            :isSingle="true"
            rightBtnText="立即购买"
            @btnClick="btnClick1"
          />
        </div>
        <!-- 付费课程，下载App -->
        <div class="cover" v-if="logged && coverType === 2">
          <course-covers coverTips="本课程为付费课程，请来云鹊医App学习" :isSingle="true" rightBtnText="去云鹊医App" @btnClick="btnClick" />
        </div>
        <!-- 下一个提示 -->
        <div class="next-countdown" v-if="coverType === 13">3秒后播放下一节</div>
        <!-- 未学完提示 -->
        <div class="cover" v-if="logged && coverType === 4">
          <course-covers coverTips="您已学习至最后一节<br />但本课程中仍有未学完的内容" :isSingle="true" rightBtnText="继续学完本课程" @btnClick="btnClick" />
        </div>
        <!-- 已学完，无考试 -->
        <div class="cover" v-if="logged && coverType === 5">
          <course-covers coverTips="您已完成全部学习<br />来云鹊医App参加考试巩固学习成果" leftBtnText="返回项目" @btnClick="btnClick" />
        </div>
        <!-- 未登录 -->
        <div class="cover" v-if="!logged">
          <course-covers coverTips="登录后马上学习课程" :isSingle="true" rightBtnText="去登录" @btnClick="goLogin" />
        </div>
      </pica-video>
    </div>
    <!-- 内容滚动 -->
    <div class="scroll-box">
      <div class="scroll-content">
        <div class="course-info">
          <div class="course-title">
            <span class="level">
              {{ course.typeStr }}
            </span>{{ course.courseName }}
          </div>
          <div class="course-num">
            <span class="num">{{ course.joinNum }}</span>人已学 /
            <span class="num">{{ course.favorNum }}</span>人收藏
            <span v-if="course.status === 3 || course.status === 4">/ 总进度<i class="percent">100%</i></span>
            <img v-if="course.status === 4" class="img" src="~@/images/has-cert-new.png" alt="" />
          </div>
        </div>
        <!-- tab栏 -->
        <div class="tab-box">
          <van-sticky :offset-top="videoH">
            <div class="tab-inner">
              <div
                class="tab-item"
                :class="{'tab-active': curtTabIdx === index}"
                v-for="(tab, index) in tabs"
                :key="index"
                @click="curtTabIdx=index">
                {{ tab.name }}
              </div>
              <div class="tab-line" :style="{left: `${tabLeft}px`}"></div>
              <DownloadButton v-if="showDownloadButton" tag="88401"></DownloadButton>
            </div>
          </van-sticky>
        </div>
        <brief-intro v-show="curtTabIdx === 0" :doctor-list="doctors" :intro="course.intro" :harvest="harvest" />
        <course-catalog v-show="curtTabIdx === 1" :list="chapters" :curtId="curtLectureId" :onToggle="onToggle" :onSelect="selectLecture" :download="download" />
        <course-ware v-show="curtTabIdx === 2" :url="pdfUrl" :visible="pdfVisible" :hidePpt="course.hidePpt" :showFlag="course.showFlag" />
        <course-comment v-show="curtTabIdx === 3" :list="qsList" :download="download" />
      </div>
    </div>
    <!-- 打开、下载App -->
    <!-- <div class="download-box">
      <img src="~@/images/icon-pica.png" alt="logo" />
      <div class="content">
        <p class="title">云鹊医</p>
        <p class="sub-title">高效学习 轻松学医</p>
      </div>
      <div class="btn-download">下载</div>
      <div class="btn-open">打开</div>
    </div> -->

    <Loading v-if="showLoading" />
  </div>
</template>

<script>
import PicaVideo from '@/components/course/pica-video';
import CourseCovers from '@/components/course/course-covers';
import BriefIntro from '@/components/course/brief-intro';
import CourseCatalog from '@/components/course/course-catalog';
import CourseWare from '@/components/course/course-ware';
import CourseComment from '@/components/course/course-comment';
import Loading from "@/components/common/common-loading";
import DownloadButton from "@/components/course/download-button";
import { getPdfFileUrl, formatLeftTimeObj, deepCopy } from '@/utils';

export default {
  components: {
    PicaVideo,
    CourseCovers,
    BriefIntro,
    CourseCatalog,
    CourseWare,
    CourseComment,
    Loading,
    DownloadButton
  },
  data() {
    return {
      course: {}, // 课程
      doctors: [], // 医生
      harvest: [], // 学习收获
      tabs: [
        { name: '简介' },
        { name: '目录' },
        { name: '课件' },
        { name: '讨论' },
      ],
      curtTabIdx: 0,
      tabW: 0, // tab的宽度
      videoH: 0, // 视频区高度
      chapters: [], // 目录
      curtLectureId: 0, // 当前播放课件id
      pdfUrl: '', // 当前pdf
      qsList: [], // 讨论列表
      coverType: 0, // 遮罩，
      showLoading: false,
      showDownloadButton: false,
    };
  },
  computed: {
    logged() {
      return this.$store.getters.logged;
    },
    tabLeft() {
      const num = this.curtTabIdx + 0.5;
      return this.tabW * num;
    },
    // 当前pdf是否可看
    pdfVisible() {
      const { showFlag, hidePpt } = this.course;
      let visible = false;
      if (showFlag === 0 && !hidePpt && this.logged) {
        visible = true;
      }
      return visible;
    }
  },
  mounted() {
    const { token, info } = this.$store.state.user;
    if (token && !info.id) {
      this.$store.dispatch('getUserInfo');
    }
    this.projectId = sessionStorage.getItem('projectId');
    this.goodsId = this.$route.query.goodsId;
    if (!this.projectId) {
      this.$router.replace('/not-found');
      return;
    }
    this.getCourseInfo();
    this.getCourseQas();
    const { height } = this.$el.querySelector('.video-box').getBoundingClientRect();
    const { width } = this.$el.querySelector('.tab-item').getBoundingClientRect();
    this.videoH = height;
    this.tabW = width;
    this.wechatShare(undefined, undefined, true);
  },
  methods: {
    getCourseInfo() {
      const { courseId } = this.$route.query;
      const projectId = this.projectId;
      this.showLoading = true;
      this.GET(`contents/courses/${courseId}/pcCourseInfo`, { projectId }).then(res => {
        this.showLoading = false;
        this.showDownloadButton = true;
        if (res.code == "000000") {
          const {
            showFlag = 0, // 0可看，10该课程为付费课程-请去App查看，20可试看，激活/购买后才可查看
            trySeeFlag = 0, // 1为试看
            trySeeTime = 0, // 试看时间
            courseHeader = {},
            introduction = [],
            directory: {
              chapters = [], // 目录
              lectureResourceList = [], // 课件
              lastLecture = {}, // 最后观看记录
            },
          } = res.data;
          let intro = '';
          for (let item of introduction) {
            if (item.type === 1) { // 医生
              this.doctors = item.dataList || [];
            }
            if (item.type === 2) { // 课程简介
              if (item.dataList && item.dataList[0]) {
                intro = item.dataList[0]['intro'] || '';
              }
            }
            if (item.type === 4) { // 学习收获
              this.harvest = item.dataList || [];
            }
          }
          this.course = { ...courseHeader, intro, showFlag, trySeeFlag, trySeeTime };
          const [chaptersAll, curtLecture] = this.getAllChapters(chapters, lectureResourceList, lastLecture, showFlag, trySeeFlag, trySeeTime);
          this.chapters = chaptersAll;
          this.curtLectureId = curtLecture.lectureId;
          this.pdfUrl = curtLecture.courseware ? getPdfFileUrl(curtLecture.courseware.filePath) : '';
          // 付费课程-请去App查看；或可试看且时长为0
          let enable = true;
          if (showFlag === 10 || (trySeeFlag && !trySeeTime)) {
            this.coverType = 2;
            enable = false
          }
          let history = 0;
          if (curtLecture.progress < 1 && !trySeeTime) {
            history = curtLecture.lastTime === 1 ? 0 : curtLecture.lastTime
          }
          this.$refs.picaVideo.switchUrl({
            chapterId: curtLecture.chapterId,
            courseId: curtLecture.courseId,
            lectureId: curtLecture.lectureId,
            url: curtLecture.pathUrl,
            proved: trySeeTime,
            history,
            enable, // 付费课程-请去App查看；或可试看且时长为0
          });
        } else {
          this.$toast(res.message);
        }
      });
    },
    // 将课件挂在目录上，获取播放id
    getAllChapters(chapters, resList, lastLecture, showFlag, trySeeFlag, trySeeTime) {
      const lectureObj = {};
      for (let item of resList) {
        lectureObj[item.lectureId] = { ...item };
      }
      let curtLecture = {};
      let unfinished = false;
      for (let i = 0; i < chapters.length; i++) {
        let chapter = chapters[i];
        chapter.chapterNameText = `${i + 1}.${chapter.chapterName}`;
        chapter.showAll = true;
        for (let j = 0; j < chapter.lectures.length; j++) {
          let lecture = chapter.lectures[j];
          let lectureId = lecture.lectureId;
          if (lectureObj[lectureId]) {
            lecture.courseware = lectureObj[lectureId]
          }
          lecture.lectureNameText = `${j + 1}.${lecture.lectureName}`;
          lecture.statusText = lecture.progress === 0 ? '未开始' : (lecture.progress === 1 ? '已学完' : `已学${parseInt(lecture.progress * 100)}%`);
          let btnText = '';
          if (showFlag === 10 || (trySeeFlag && !trySeeTime)) {
            btnText = ''; // 不可看
          }
          if (showFlag === 20 && trySeeFlag && trySeeTime) {
            btnText = '试看'; // 可试看
          }
          if (showFlag === 0) {
            btnText = lecture.progress === 1 ? '复习课程' : '学习';
          }
          lecture.btnText = btnText;
          const totalTime = formatLeftTimeObj(lecture.totalTime);
          const h = totalTime.h === '00' ? '' : `${totalTime.h}:`;
          lecture.totalTimeText = `${h}${totalTime.f}:${totalTime.s}`;
          if (lastLecture.lectureId) {
            if (lastLecture.lectureId === lecture.lectureId) {
              curtLecture = { ...lecture, lastTime: lastLecture.lastTime }
            }
          } else {
            // 取第一个未完成的
            if (lecture.progress < 1 && !unfinished) {
              curtLecture = { ...lecture };
              unfinished = true;
            }
          }
        }
      }
      return [chapters, curtLecture];
    },
    btnClick(index) {
      const coverType = this.coverType;
      switch(coverType) {
        case 1:
        case 2:
          this.download();
          break;
        case 4:
          this.selectLecture(this.prev);
          break;
        case 5:
          if (index === 1) {
            this.$sendBuriedData({
              component_tag: `884#88402`
            });
            window.history.back();
          } else {
            this.download();
          }
          break;
        default:
          //
      }
    },
    btnClick1() {
      this.$router.push({ path: '/goods-detail', query: { goodsId: this.goodsId, projectId: this.projectId } })
    },
    // 折叠、展开目录
    onToggle(index) {
      const item = this.chapters[index];
      item.showAll = !item.showAll;
      this.chapters.splice(index, 1, item);
    },
    // 选择课程
    selectLecture(lecture, isUserSelect) {
      if (isUserSelect && !this.logged) {
        this.goLogin();
        return;
      }
      const { showFlag, trySeeFlag, trySeeTime, examType } = this.course;
      // console.log(lecture);
      if (examType === 2) { // 是考试,mustLearnIds必须完成的lectureId
        this.$sendBuriedData({
          component_tag: `884#88405`
        });
        this.$toast('请前往云鹊医APP进行考试');
        return;
      }
      this.$sendBuriedData({
        component_tag: `884#88404#${lecture.lectureId}#${lecture.lectureName}`
      });
      if (lecture.lectureId === this.curtLectureId) {
        return;
      }
      let enable = true;
      if (showFlag === 10 || (trySeeFlag && !trySeeTime)) {
        this.coverType = 2;
        enable = false
      } else {
        this.coverType = 0;
      }
      this.curtLectureId = lecture.lectureId;
      this.pdfUrl = lecture.courseware ? getPdfFileUrl(lecture.courseware.filePath) : '';
      let history = 0;
      if (lecture.progress < 1) {
        history = lecture.lastTime === 1 ? 0 : lecture.lastTime
      }
      this.$refs.picaVideo.switchUrlAndPlay({
        chapterId: lecture.chapterId,
        courseId: lecture.courseId,
        lectureId: lecture.lectureId,
        url: lecture.pathUrl,
        proved: trySeeTime,
        history,
        enable, // 付费课程-请去App查看；或可试看且时长为0
      });
      setTimeout(() => {
        this.refreshCatalog();
      }, 1000);
    },
    // 刷新目录进度
    refreshCatalog() {
      const { courseId } = this.$route.query;
      const projectId = this.projectId;
      this.GET(`contents/courses/${courseId}/pcCourseInfo`, { projectId }).then(res => {
        if (res.code == "000000") {
          const {
            showFlag = 0, // 0可看，10该课程为付费课程-请去App查看，20可试看，激活/购买后才可查看
            trySeeFlag = 0, // 1为试看
            trySeeTime = 0, // 试看时间
            directory: {
              chapters = [], // 目录
              lectureResourceList = [], // 课件
              lastLecture = {}, // 最后观看记录
            },
          } = res.data;
          const [chaptersAll, curtLecture] = this.getAllChapters(chapters, lectureResourceList, lastLecture, showFlag, trySeeFlag, trySeeTime);
          this.chapters = chaptersAll;
        }
      })
    },
    getCourseQas() {
      const { courseId } = this.$route.query;
      const projectId = this.projectId;
      this.GET(`contents/courses/v2/${courseId}/qas`, { projectId, pageNo: 1, pageSize: 10 }).then(res => {
        if (res.code == "000000") {
          this.qsList  = res.data.model && res.data.model.qaPostModel || [];
        } else {
          this.$toast(res.message);
        }
      });
    },
    // 视频播放结束
    onVideoEnd(opt) {
      if (opt.type === 1) {
        let chapters = deepCopy(this.chapters);
        let curtI = 0;
        let curtJ = 0;
        let curtIndex = 0;
        let count = 0;
        let prev; // 第一个未完成的
        for (let i = 0; i < chapters.length; i++) {
          let lectures = chapters[i]['lectures'];
          for (let j = 0; j < lectures.length; j++) {
            count += 1;
            let lecture = lectures[j];
            if (this.curtLectureId === lecture.lectureId) {
              curtIndex = count;
              curtI = i;
              curtJ = j;
              lecture.progress = 1;
              lecture.statusText = '已学完';
              lecture.btnText = '复习课程';
            }
            if (!prev && lecture.progress < 1) {
              prev = { ...lecture }
            }
          }
        }
        if (curtIndex === count) { // 最后一个
          if (prev) {
            this.coverType = 4;
            this.prev = prev;
          } else {
            this.coverType = 5;
            this.course.status = 3;
          }
        } else { // 3秒后播放下一个
          let next = chapters[curtI]['lectures'][curtJ + 1] || chapters[curtI + 1]['lectures'][0];
          this.coverType = 13;
          setTimeout(() => {
            this.selectLecture(next);
          }, 3000)
        }
        this.chapters = chapters;
      } else if (opt.type === 2) { // 试看结束
        this.coverType = 1;
      }
    },
    onReplay() {
      this.coverType = 0;
    },
    // goLogin() {
    //   this.$store.dispatch('goLogin');
    // },
    // 去下载app
    download() {
      window.location.href = "https://a.app.qq.com/o/simple.jsp?pkgname=com.picahealth.yunque";
    }
  }
};
</script>

<style lang="less" scoped>
.course-detail{
  position: relative;
  height: 100%;
  padding-top: 210px;
  box-sizing: border-box;
  .video-box{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 210px;
  }
  .scroll-box{
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
  }
  .scroll-content{
    // padding-bottom: 60px;
  }
  .course-info{
    padding: 20px 15px;
    border-bottom: 6px solid #F8F9FA;
  }
  .course-title{
    line-height: 23px;
    font-size: 18px;
    font-weight: bold;
    .level{
      display: inline-block;
      color: #fff;
      font-weight: normal;
      font-size: 12px;
      background-color: #6A9FE9;
      margin-right: 5px;
      transform: translateY(-2px);
      padding: 0 3px;
      white-space: nowrap;
      border-radius: 1px;
    }
  }
  .course-num{
    color: #676869;
    font-size: 13px;
    margin-top: 10px;
    .num{
      color: #373839;
    }
    .percent{
      color: #4B9D8F;
    }
    .img{
      float: right;
      height: 20px;
    }
  }
  .tab-box{
    height: 50px;
  }
  .tab-inner{
    display: flex;
    position: relative;
    background-color: #fff;
    &::after{
      position: absolute;
      content: "";
      left: 0;
      bottom: 0;
      width: 200%;
      height: 0;
      border-bottom: 1px solid #F0F1F2;
      transform: scale(0.5);
      transform-origin: left center;
    }
  }
  .tab-item{
    color: #979899;
    font-size: 15px;
    width: 60px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .tab-active{
    color: #373839;
    font-weight: bold;
  }
  .tab-line{
    position: absolute;
    left: 30px;
    bottom: 3px;
    width: 10px;
    height: 3px;
    background-color: #449284;
    border-radius: 1.5px;
    transform: translate3d(-5px, 0, 0);
    transition: left 0.3s;
  }
  .download-box{
    display: flex;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #fff;
    img{
      display: block;
      width: 40px;
      height: 40px;
      margin: 10px 10px 0 15px;
    }
    .content{
      flex: 1;
      width: 50px;
      padding-top: 10px;
    }
    .title{
      font-size: 16px;
      line-height: 22px;
    }
    .sub-title{
      color: #717171;
      font-size: 12px;
      line-height: 18px;
    }
    .btn-download{
      color: #449284;
      display: inline-block;
      height: 30px;
      line-height: 30px;
      font-size: 14px;
      padding: 0 15px;
      margin-right: 15px;
      border: 1px solid #449284;
      border-radius: 15px;
    }
    .btn-open{
      color: #fff;
      display: inline-block;
      height: 30px;
      line-height: 30px;
      font-size: 14px;
      padding: 0 15px;
      margin-right: 15px;
      background-color: #449284;
      border-radius: 15px;
    }
  }
  .next-countdown{
    position: absolute;
    color: #fff;
    right: 10px;
    bottom: 44px;
    font-size: 12px;
    height: 24px;
    line-height: 24px;
    padding: 0 12px;
    border-radius: 12px;
    background-color: #373839;
  }
}
</style>

