<template>
  <div class="page">
    <van-nav-bar :title="title" @click-left="onClickLeft">
      <template #left>
        <template v-if="$route.query && $route.query.code">
          <van-icon name="wap-home-o" />
          <span style="font-size: .32rem;color: #FFF;">首页</span>
        </template>
        <template v-else>
          <van-icon name="arrow-left" />
          <span style="font-size: .32rem;color: #FFF;">返回</span>
        </template>
      </template>
    </van-nav-bar>
    <div class="courseContent">
      <div class="tabs">
        <div v-show="showBack" class="toTop" @click="BackTop">
          <span><van-icon name="back-top"/></span>
        </div>
        <scroller ref="scroller" :on-scrolling="scrollChange">
          <div class="previewImg">
            <img :src="courseDetail.thumb" />
          </div>
          <div class="title">
            <span>{{ courseDetail.price }}</span>
            <p>{{ courseDetail.name }}</p>
            <i style="margin-right: .1rem;"
              >已更新{{ courseDetail.sections.length }}节课</i
            >
            <i
              >{{
                Number(courseDetail.baseClick) + Number(courseDetail.clickNum)
              }}次浏览</i
            >
          </div>
          <van-tabs v-model="activeTab" swipeable sticky>
            <van-tab title="课程介绍">
              <div class="images">
                <div
                  class="descImage"
                  v-for="(item, index) in courseDetail.images"
                  :key="index"
                >
                  <img :src="item" />
                </div>
              </div>
            </van-tab>
            <van-tab title="课程目录">
              <div class="catelog">
                <div class="logConetent">
                  <div
                    class="logLi"
                    v-for="(item, index) in courseDetail.sections"
                    :key="index"
                    @click="toSectionVidio(item, index)"
                  >
                    <p>{{ index + 1 }}、{{ item.name }}</p>
                  </div>
                </div>
              </div>
            </van-tab>
          </van-tabs>
          <div
            id="xxhh"
            style="height: 1.2rem;"
            v-if="!courseDetail.buy && canGive && canGive2"
          ></div>
        </scroller>
      </div>
      <div
        class="getCourse"
        v-if="!courseDetail.buy && canGive && canGive2"
        @click="useCode"
      >
        <van-button icon="fire-o" square class="getBtn"
          >点击领取课程名额</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { setWxConfig } from "../utils";
import wx from 'weixin-js-sdk'
import {
  learnerCourseDetail,
  getCourseCodeDetail,
  getCourseCode,
  getVideoSrc
} from "../api";
export default {
  name: "courseDetail",
  components: {},
  props: [],
  data() {
    return {
      showBack:false,
      activeTab: 0,
      title: "课程详情",
      courseDetail: {
        thumb: "",
        name: "",
        images: [],
        sections: [],
        buy: false
      },
      canGive: true,
      canGive2: true,
      giveCode: false,
      codeDetail: {
        enable: true
      }
    };
  },
  created() {
    // this.init();
  },
  activated(){
    this.init();
  },
  methods: {
    scrollChange(e){
      //需要滚动的界面实际长度大于整个页面长度
      if(e>40&&document.getElementsByClassName('page')[0].offsetHeight<document.getElementsByClassName('_v-content')[0].offsetHeight){
        this.showBack = true;
      }else{
        this.showBack = false;
      }
    },
    //回到顶部
    BackTop() {
      this.$refs.scroller.scrollTo(0, 0, 500);
    },
    // 领取课程提示
    useCode() {
      if (this.codeDetail && this.codeDetail.enable) {
        this.$dialog
          .confirm({
            title: "提示",
            message: "确定领取当前课程吗"
          })
          .then(() => {
            let data = {
              salesCode: this.codeDetail.salesCode,
              userId: this.codeDetail.userId,
              subjectId: this.codeDetail.subjectId
            };
            getCourseCode(data).then(res => {
              this.$toast.success("领取成功！");
              this.giveCode = true;
              this.getDetail();
            });
          });
      } else {
        this.$dialog.confirm({
          title: "提示",
          message: "该课程码已失效"
        });
        // this.$toast.fail("该课程码已失效");
      }
    },
    // 领取课程码课程
    getCodeDetail() {
      getCourseCodeDetail(this.$route.query.code).then(res => {
        this.codeDetail = res;
        if (!res && !this.courseDetail.buy) {
          this.$dialog.confirm({
            title: "提示",
            message: "该课程码已失效"
          });
          // this.$toast.fail("该课程码已失效");
        }
      });
    },
    // 章节点击观看视频
    toSectionVidio(item, index) {
      if (this.courseDetail.buy && this.courseDetail.enable) {
        let data = {
          index: index,
          link: item.link
        };
        sessionStorage.setItem("vd_info", JSON.stringify(data));
        this.$router.push({
          path: `/course/video/${this.$route.params.id}`
        });
      } else if (!this.courseDetail.buy) {
        this.$toast.fail("请先领取课程后再观看");
      } else {
        this.$toast.fail("课程已下架");
      }
    },
    // 返回首页
    onClickLeft() {
      if (this.$route.query && (this.$route.query.code)) {
        this.$router.push("/courseHome");
      } else {
        this.$router.go(-1);
      }
    },
    // 初始化
    init() {
      this.courseId = this.$route.params.id;
      if (this.$route.query && this.$route.query.code && this.$route.query.code != 2) {
        this.getDetail();
      } else {
        this.getDetail();
        this.canGive = false;
      }
    },
    //删除URL的指定参数
    urlDelP(url,name){
      var urlArr = url.split('?');
      if(urlArr.length>1 && urlArr[1].indexOf(name)>-1){
          var query = urlArr[1];
          var obj = {}
          var arr = query.split("&");
          for (var i = 0; i < arr.length; i++) {
              arr[i] = arr[i].split("=");
              obj[arr[i][0]] = arr[i][1];
          };
          delete obj[name];
          var urlte = urlArr[0] +'?'+ JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
          return urlte;
      }else{
          return url;
      };
    },
    // 获取用户此课程的详情
    getDetail() {
      learnerCourseDetail(this.courseId).then(res => {
        this.courseDetail = res;
        if(this.$isWx){
          let info = {
            title:this.courseDetail.name,// 分享标题
            desc:'听完觉得确实不错，忍不住要推荐~',// 分享描述
            link: `${window.location.href}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: this.courseDetail.thumb, // 分享图标
          }
          if(this.$route.query&&this.$route.query.code){
            let newUrl = this.urlDelP(window.location.href,'code')
            info.link = newUrl.includes('?')?`${newUrl}&code=2`:`${newUrl}?code=2`
          }else{
            info.link = window.location.href.includes('?')?`${window.location.href}&code=2`:`${window.location.href}?code=2`
          }
          setWxConfig(info);
        }
        if (
          this.courseDetail.buy &&
          this.$route.query &&
          this.$route.query.code &&
          this.$route.query.code != 2 &&
          !this.giveCode
        ) {
          this.$toast.fail("您已经购买课程，无需再次购买");
          return;
        }
        if (!this.courseDetail.enable) {
          this.canGive2 = false;
          this.$toast.fail("课程已下架");
          return;
        }
        if (
          !this.courseDetail.buy &&
          this.$route.query &&
          this.$route.query.code &&
          this.$route.query.code != 2 &&
          this.courseDetail.enable &&
          !this.giveCode
        ) {
          this.getCodeDetail();
        }
      });
    }
  },
  computed: {}
};
</script>
<style scoped lang="scss">
@import url("../utils/navBar.scss");
* {
  margin: 0;
  padding: 0;
}
img {
  display: block;
}
.page {
  // background-color: #fff;
  box-sizing: border-box;
  .courseContent {
    // padding: 0 0.2rem;
    // margin-top: 0.3rem;
    position: relative;
    .previewImg {
      // border-radius: 0.1rem;
      overflow: hidden;
      img {
        width: 100%;
        // height: 4rem;
        overflow: hidden;
        display: block;
      }
    }
    .title {
      padding: 0 0.2rem 0.2rem;
      background-color: #fff;
      margin-bottom: 0.2rem;
      span {
        font-size: 0.35rem;
        font-weight: 600;
        color: red;
        line-height: 0.8rem;
      }
      p {
        font-size: 0.32rem;
        font-weight: 600;
        color: #000;
        line-height: 0.4rem;
        margin-bottom: 0.2rem;
        /* white-space: pre-wrap; */
        /* overflow: hidden; */
        /* text-overflow: ellipsis; */
        /* white-space: nowrap; */
        /* word-break: break-all; */
        width: 100%;
        word-wrap: break-word;
      }
      i {
        font-size: 0.22rem;
        color: #888;
        line-height: 0.3rem;
        font-style: normal;
      }
    }
    .tabs {
      height: calc(100vh - 0.92rem);
      position: relative;
      .toTop {
        width: 1rem;
        height: 1rem;
        background-color: #ccc;
        border-radius: 50%;
        overflow: hidden;
        text-align: center;
        position: absolute;
        right: 0.4rem;
        bottom: 0.4rem;
        z-index: 999;
        span {
          font-size: 0.48rem;
          color: #fff;
          line-height: 1rem;
        }
      }
      .images {
        // margin-top: 0.1rem;
        img {
          width: 100%;
        }
      }
      .catelog {
        background: #fff;
        padding: 0.2rem;
        margin-top: 1px;
        border-top: 1px solid #efefef;
        position: relative;
        .sup {
          display: flex;
          justify-content: space-between;
          align-items: center;
          span {
            font-size: 0.24rem;
            color: #666;
            line-height: 3;
            margin-left: 0.1rem;
          }
        }
        .logConetent {
          .logLi {
            border: 1px solid #efefef;
            border-radius: 0.1rem;
            padding: 0 0.2rem;
            margin-bottom: 0.15rem;
            p {
              padding: 0.2rem 0;
              font-size: 0.3rem;
              color: #000;
              line-height: 1.3;
              // line-height: 3;
              // overflow: hidden;
              // text-overflow: ellipsis;
              // white-space: nowrap;
              // word-break: break-all;
            }
          }
        }
      }
    }
  }
  .getCourse {
    position: absolute;
    bottom: 0.1rem;
    left: 0.1rem;
    width: calc(100% - 0.2rem);
    .getBtn {
      width: 100%;
      background-color: #26a2ff;
      color: #fff;
      // animation: getFire 3s infinite linear;
      border-radius: 0.1rem;
    }
  }
}
@keyframes getFire {
  0% {
    transform: scale(0.95);
  }
  100% {
    transform: scale(1.05);
  }
}
</style>
