<template>
  <div class="newLesson">
    <!--竖屏导航-->
    <div class="header" v-if="!nowLesson.old">
      <i class="lessonHeader home" @click="backList"></i>
      <i :class="{lessonHeader:true, defaultLook:nowShow !== 1,look:nowShow===1}" @click="type=1"></i>
      <i :class="{lessonHeader:true, defaultPlay:nowShow !== 2,play:nowShow===2}" @click="type=2"></i>
      <i :class="{lessonHeader:true, defaultFun:nowShow !== 3,fun:nowShow===3}" @click="type=3"></i>
    </div>
    <!--横屏导航-->
    <div class="header-h" v-if="!nowLesson.old">
      <i :class="{headerHP:true, defaultLook:nowShow !== 1,lookHP:nowShow===1}" @click="type=1">
        <img :src="HP.look2" alt />
      </i>
      <i :class="{headerHP:true, defaultPlay:nowShow !== 2,playHP:nowShow===2}" @click="type=2">
        <img :src="HP.play2" alt />
      </i>
      <i :class="{headerHP:true, defaultFun:nowShow !== 3,funHP:nowShow===3}" @click="type=3">
        <img :src="HP.listen1" alt />
      </i>
      <i class="headerHP home" @click="backList">
        <img :src="HP.back" alt />
      </i>
    </div>
    <!--老课包返回按钮-->
    <img :src="backUrl" v-if="nowLesson.old" @click="backList" class="backImg" />
    <!--内容-->
    <div :class="{'index-content-block':true,radius:nowShow !== 1 || nowLesson.old}">
      <look-block v-if="nowLesson.type === 'text'" :contentData="nowLesson" @backList="backList" />
      <video-block
        v-if="nowLesson.type === 'video'"
        :contentData="nowLesson"
        :nowShow="nowShow"
        @backList="backList"/>
      <audio-block v-if="nowLesson.type === 'audio'" :contentData="nowLesson" @backList="backList" />
    </div>
  </div>
</template>
<script>
  import {
    subUserLessonApi,
    getUserWatchApi,
    getwechatParam,
    getCountTimeApi,
    postErrorLogApi
  } from "../../service/api";
  import { Toast } from "vant";
  import lookBlock from "./look";
  import videoBlock from "./video";
  import backUrl from "../../assets/newLesson/back.png";
  import { HP } from "../../util/imgUrl.js";
  import audioBlock from "./audio";
  import sharePage from "./share";
  export default {
    name: "index",
    data() {
      let query;
      if (this.$store.state.classQuery.periods_id) {
        query = this.$store.state.classQuery;
      } else {
        // debugger
        query = JSON.parse(sessionStorage.getItem("classQuery"));
      }
      // debugger
      return {
        backUrl: backUrl,
        periods_id: query.periods_id,
        category_id: query.category_id,
        elementId: query.elementId,
        lesson: JSON.parse(localStorage.getItem("lessonDetail")),
        nowShow: 0,
        page_id: 1,
        stillTime: 0,
        watchDetail: null,
        timeInterval: null,
        nowLesson: {
          type: "",
          content: null,
          age: 1
        },
        HP: HP,
        type: 1,
        saveTime:null,
        minute:'',
        percent:'',
        title:'',
        domTitle:''
      };
    },
    watch: {
      type() {
        this.changeTitle(this.type);
      }
    },
    components: {
      lookBlock,
      videoBlock,
      audioBlock,
      sharePage
    },
    mounted() {
      this.initPage();
    },
    /**
     * 离开页面前关闭--这个记录看课时长
     */
    beforeDestroy(){
      clearInterval(this.saveTime)
    },
    methods: {
      enableShare: function(option) {
        let that = this;
        getwechatParam({
          api_list: "onMenuShareAppMessage,onMenuShareTimeline",
          url: window.location.href.split("#")[0]
        }).then(wechatRes => {
          wx.config({
            debug: false,
            appId: wechatRes.appId,
            timestamp: parseInt(wechatRes.timestamp),
            nonceStr: wechatRes.nonceStr,
            signature: wechatRes.signature,
            jsApiList: wechatRes.jsApiList
          });
          wx.ready(function() {
            wx.onMenuShareTimeline({
              title: option.product_title, // 分享标题
              desc: option.desc, // 分享描述
              link: option.shareUrl, // 分享链接
              imgUrl:
                  option.shareIcon ||
                  "https://cdn.singsingenglish.com/singsing/recommend/logo-refer.png", // 分享图标
              success: function() {
                // debugger
                let lessonDetail = JSON.parse(
                    localStorage.getItem("lessonDetail")
                );
                let nowTime = Date.parse(new Date());
                let json = {
                  page_type: 0,
                  page_id: 6,
                  stay_time: 0
                };

                subUserLessonApi(
                    that.elementId,
                    that.category_id,
                    that.periods_id,
                    json
                ).then(res => {
                  lessonDetail.total_watch_time = res.total_watch_time;
                  lessonDetail.nowTime = nowTime;
                  lessonDetail.star_num = res.total_star_num;
                  localStorage.setItem(
                      "lessonDetail",
                      JSON.stringify(lessonDetail)
                  );
                });
              },
              cancel: function() {}
            });
            wx.onMenuShareAppMessage({
              title: option.product_title, // 分享标题
              desc: option.desc, // 分享描述
              link: option.shareUrl, // 分享链接
              imgUrl:
                  option.shareIcon ||
                  "https://cdn.singsingenglish.com/singsing/recommend/logo-refer.png", // 分享图标
              success: function() {
                let lessonDetail = JSON.parse(
                    localStorage.getItem("lessonDetail")
                );
                let nowTime = Date.parse(new Date());
                let json = {
                  page_type: 0,
                  page_id: 6,
                  stay_time: 0
                };

                subUserLessonApi(
                    that.elementId,
                    that.category_id,
                    that.periods_id,
                    json
                ).then(res => {
                  lessonDetail.total_watch_time = res.total_watch_time;
                  lessonDetail.nowTime = nowTime;
                  lessonDetail.star_num = res.total_star_num;
                  localStorage.setItem(
                      "lessonDetail",
                      JSON.stringify(lessonDetail)
                  );
                });
              },
              cancel: function() {}
            });
          });
        });
      },
      onShare(URL) {
        this.enableShare({
          product_title: `我家宝宝正在【唱唱启蒙英语】挑战童谣，已坚持${this.watchDetail.total_day}天`, // 分享标题
          desc:
              JSON.parse(localStorage.getItem("userDesc")).nickname +
              `赠您【领取超值课程】特权，来唱唱和百万家庭一起快乐启蒙英语吧！`, //
          shareIcon: "https://cdn.singsingenglish.com/logo/logo.jpg",
          shareUrl: URL
        });
      },
      backList() {
        let lessonDetail = JSON.parse(localStorage.getItem("lessonDetail"));
        let nowTime = Date.parse(new Date());
        let lookTime = (nowTime - lessonDetail.nowTime) / 1000;
        let json = {
          page_type: 0,
          page_id: this.page_id,
          stay_time: (nowTime - lessonDetail.nowTime) / 1000
        };

        subUserLessonApi(
            this.elementId,
            this.category_id,
            this.periods_id,
            json
        ).then(res => {
          lessonDetail.total_watch_time = res.total_watch_time;
          lessonDetail.nowTime = nowTime;
          lessonDetail.star_num = res.total_star_num;
          console.log(res, 'asdfasfsaf')
          localStorage.setItem("lessonDetail", JSON.stringify(lessonDetail));

          let query = {
            periods_id: this.periods_id,
            course_type: this.course_type,
            parent_category_id: this.parent_category_id,
            back_id: this.category_id
          };
          // console.log(query);
          //  debugger
          this.$router.push({ name: "map", query: query });
        });
      },
      changeTitle(type) {
        // if(type==type)
        Toast.loading({
          mask: true,
          message: ""
        });
        this.nowShow = type;
        let lessonDetail = JSON.parse(localStorage.getItem("lessonDetail"));
        let nowTime = Date.parse(new Date());
        let lookTime = (nowTime - lessonDetail.nowTime) / 1000;
        let json = {
          page_type: 0,
          page_id: this.page_id,
          stay_time: nowTime/1000 - lessonDetail.nowTime/1000
        };
        subUserLessonApi(
            this.elementId,
            this.category_id,
            this.periods_id,
            json
        ).then(res => {
          Toast.clear();
          lessonDetail.total_watch_time = res.total_watch_time;
          lessonDetail.nowTime = nowTime;
          lessonDetail.star_num = res.total_star_num;
          localStorage.setItem("lessonDetail", JSON.stringify(lessonDetail));
        });
        switch (type) {
          case 1:
            // 神策埋点 板块切换
            this.$sa.track("learnPart", {
              partName: "爸妈看一看",
              elementID: this.lesson.id.toString(),
              dayModule: this.lesson.domTitle.slice(0, 9),
              weekName: this.lesson.domTitle.slice(
                  10,
                  this.lesson.domTitle.length
              ),
              elementName:
                  this.lesson.domTitle.slice(0, 9) +
                  "-" +
                  this.lesson.domTitle.slice(10, this.lesson.domTitle.length),
              themeID: this.lesson.themeID,
              themeName: this.lesson.themeName,
              goodsID: this.lesson.goodsID,
              classID: this.lesson.classID,
              is_view_today:
                  !!new Date().setHours(0, 0, 0, 0) ===
                  new Date(this.lesson.push_time).setHours(0, 0, 0, 0)
            });
            this.page_id = 1;
            this.nowLesson = {
              type: "text",
              title: 1,
              partName: "爸妈看一看",
              content: this.lesson.content.look,
              age: this.nowLesson.age
            };
            // debugger
            break;
          case 2:
            // 神策埋点 板块切换
            this.$sa.track("learnPart", {
              partName: "宝贝玩一玩",
              elementID: this.lesson.id.toString(),
              dayModule: this.lesson.domTitle.slice(0, 9),
              weekName: this.lesson.domTitle.slice(
                  10,
                  this.lesson.domTitle.length
              ),
              elementName:
                  this.lesson.domTitle.slice(0, 9) +
                  "-" +
                  this.lesson.domTitle.slice(10, this.lesson.domTitle.length),
              themeID: this.lesson.themeID,
              themeName: this.lesson.themeName,
              goodsID: this.lesson.goodsID,
              classID: this.lesson.classID,
              is_view_today:
                  !!new Date().setHours(0, 0, 0, 0) ===
                  new Date(this.lesson.push_time).setHours(0, 0, 0, 0)
            });
            this.page_id = 2;
            if (this.lesson.content.play.type) {
              this.nowLesson = {
                type: "audio",
                title: 2,
                partName: "宝贝玩一玩",
                content: this.lesson.content.play,
                age: this.nowLesson.age
              };
            } else {
              this.nowLesson = {
                type: "video",
                title: 2,
                partName: "宝贝玩一玩",
                content: this.lesson.content.play,
                age: this.nowLesson.age
              };
            }
            break;
          case 3:
            this.$sa.track("learnPart", {
              partName: "磨磨小耳朵",
              elementID: this.lesson.id.toString(),
              dayModule: this.lesson.domTitle.slice(0, 9),
              weekName: this.lesson.domTitle.slice(
                  10,
                  this.lesson.domTitle.length
              ),
              elementName:
                  this.lesson.domTitle.slice(0, 9) +
                  "-" +
                  this.lesson.domTitle.slice(10, this.lesson.domTitle.length),
              themeID: this.lesson.themeID,
              themeName: this.lesson.themeName,
              goodsID: this.lesson.goodsID,
              classID: this.lesson.classID,
              is_view_today:
                  !!new Date().setHours(0, 0, 0, 0) ===
                  new Date(this.lesson.push_time).setHours(0, 0, 0, 0)
            });
            this.page_id = 5;
            if (this.lesson.content.fun.type) {
              this.nowLesson = {
                type: "audio",
                title: 3,
                partName: "磨磨小耳朵",
                content: this.lesson.content.fun,
                age: this.nowLesson.age
              };
            } else {
              this.nowLesson = {
                type: "video",
                partName: "磨磨小耳朵",
                title: 3,
                content: this.lesson.content.fun,
                age: this.nowLesson.age
              };
            }
            break;
        }
      },
      countTimeFn(){
        this.saveTime = setInterval(()=>{
          let lessonDetail = JSON.parse(localStorage.getItem("lessonDetail"));
          let nowTime = Date.parse(new Date());
          let lookTime = (nowTime - lessonDetail.nowTime) / 1000;
          let json = {
            page_type: 0,
            page_id: this.page_id,
            stay_time: lookTime
          };
          subUserLessonApi(
              this.elementId,
              this.category_id,
              this.periods_id,
              json
          ).then(res => {
            Toast.clear();
            lessonDetail.total_watch_time = res.total_watch_time;
            lessonDetail.nowTime = nowTime;
            lessonDetail.star_num = res.total_star_num;
            localStorage.setItem("lessonDetail", JSON.stringify(lessonDetail));
          });
        },120000)
        // debugger
        this.$store.dispatch('setTimeout',this.saveTime)
      },
      initPage() {
        Toast.loading({
          mask: true,
          message: ""
        });
        this.parent_category_id = this.$route.query.parent_category_id;
        this.course_type = this.$route.query.course_type;
        this.countTimeFn()
        this.lesson = JSON.parse(localStorage.getItem("lessonDetail"));
        // debugger
        getUserWatchApi({category_id:this.category_id}).then(res => {
          this.watchDetail = res;
          this.$store.dispatch("setWatchDetail", this.watchDetail);
          this.userDetail = JSON.parse(localStorage.getItem("userDesc"));
          this.minute = (res.stay_time / 60).toFixed();
          // this.minute = (360/60).toFixed()
          if (this.minute < 1) {
            this.minute = 1;
          }
          // this.minute<1?1:1
          if (this.minute < 8) {
            if (this.minute < 5) {
              this.percent = 75 + Math.floor(49 * Math.random()) / 10;
            } else {
              this.percent = 81 + Math.floor(89 * Math.random()) / 10;
            }
          } else if (this.minute <= 12) {
            this.percent = 91 + Math.floor(39 * Math.random()) / 10;
          } else {
            this.percent = 96 + Math.floor(39 * Math.random()) / 10;
          }
          Toast.clear();
          let obj = {
            user_id: this.userDetail.user_id,
            minute: this.minute,
            percent: this.percent,
            title: this.lesson.title,
            domTitle: this.lesson.domTitle
          };
          let URL =
              process.env.API_URL +
              "#/shareGoods?info=" +
              encodeURIComponent(JSON.stringify(obj));
          this.onShare(URL);
          // this.onShare(URL);
          this.nowShow = 1;
          document.title = `${this.lesson.domTitle}`;
          this.nowLesson = {
            type: "text",
            partName: "爸妈看一看",
            title: 1,
            content: this.lesson.content.look,
            age: this.nowLesson.age
          };
          let json = {
            page_type: 0,
            page_id: 1,
            stay_time: 1
          };
          let lessonDetail = JSON.parse(localStorage.getItem("lessonDetail"));
          let nowTime = Date.parse(new Date());
          subUserLessonApi(
              this.elementId,
              this.category_id,
              this.periods_id,
              json
          ).then(res => {
            // console.log(493,res)
            console.log(res)
            lessonDetail.total_watch_time = res.total_watch_time;
            lessonDetail.nowTime = nowTime;
            lessonDetail.star_num = res.total_star_num;
            localStorage.setItem("lessonDetail", JSON.stringify(lessonDetail));
            Toast.clear();
          });
          this.$sa.track("learnPart", {
            partName: "爸妈看一看",
            elementID: this.lesson.id.toString(),
            dayModule: this.lesson.domTitle.slice(0, 9),
            weekName: this.lesson.domTitle.slice(10, this.lesson.domTitle.length),
            elementName:
                this.lesson.domTitle.slice(0, 9) +
                "-" +
                this.lesson.domTitle.slice(10, this.lesson.domTitle.length),
            themeID: this.lesson.themeID,
            themeName: this.lesson.themeName,
            goodsID: this.lesson.goodsID,
            classID: this.lesson.classID,
            is_view_today:
                !!new Date().setHours(0, 0, 0, 0) ===
                new Date(this.lesson.push_time).setHours(0, 0, 0, 0)
          });
          if (
              this.lesson.content.play.video.length < 1 &&
              this.lesson.content.play.audio.length < 1
          ) {
            this.nowLesson.old = true;
          }
        });
      }
    }
  };
</script>

<style scoped lang="less">
  @import "../../util/public";
  .lessonHeader {
    background: url("https://static-cdn.changchangenglish.com/new-sing/static/images/lessonHeader3.png?v=2")
    no-repeat;
    background-size: 102 * @toVw 334 * @toVw;
    display: inline-block;
  }
  .header-h {
    display: none;
  }
  .home {
    height: 46 * @toVw;
    width: 46 * @toVw;
    background-position: 0 0;
  }
  .play {
    height: 48 * @toVw;
    width: 102 * @toVw;
    background-position: 0 -46 * @toVw;
  }
  .look {
    height: 48 * @toVw;
    width: 102 * @toVw;
    background-position: 0 -94 * @toVw;
  }
  .fun {
    height: 48 * @toVw;
    width: 102 * @toVw;
    background-position: 0 -142 * @toVw;
  }
  .defaultFun {
    height: 48 * @toVw;
    width: 102 * @toVw;
    background-position: 0 -190 * @toVw;
  }
  .defaultLook {
    height: 48 * @toVw;
    width: 102 * @toVw;
    background-position: 0 -238 * @toVw;
  }
  .defaultPlay {
    height: 48 * @toVw;
    width: 102 * @toVw;
    background-position: 0 -286 * @toVw;
  }
  .header {
    display: flex;
    display: -webkit-flex;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    padding: 5 * @toVw 0;
    z-index: 2;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 * @toVw 2 * @toVw 3 * @toVw 0 * @toVw rgba(0, 0, 0, 0.1);
  }
  .newLesson {
    background: #f8f8f8;
  }
  .backImg {
    position: fixed;
    bottom: 40 * @toVw;
    right: 20 * @toVw;
    z-index: 99999999;
    width: 60 * @toVw;
  }

  @media screen and (orientation: landscape) {
    @toVw: 100/667vw;
    .backImg {
      position: fixed;
      bottom: 40 * @toVw;
      right: 20 * @toVw;
      z-index: 99999999;
      width: 60 * @toVw;
    }
    .lessonHeader {
      display: none;
    }
    .header {
      display: none;
    }
    .actBanKuai {
      background-color: white;
      border: 1 * @toVw solid transparent;
      border-left-color: black;
      border-top-color: black;
      border-bottom-color: black;
      border-radius: 8 * @toVw 0 0 8 * @toVw;
    }
    .headerHP {
      background-size: 62 * @toVw 434 * @toVw;
      display: inline-block;
    }
    .home {
      height: 62 * @toVw;
      width: 62 * @toVw;
      background-position: 0 0;
    }
    .lookHP {
      height: 62 * @toVw;
      width: 62 * @toVw;
      background-position: 0 -62 * @toVw;
      .actBanKuai;
    }
    .playHP {
      height: 62 * @toVw;
      width: 62 * @toVw;
      background-position: 0 -124 * @toVw;
      .actBanKuai;
    }
    .funHP {
      height: 62 * @toVw;
      width: 62 * @toVw;
      background-position: 0 -186 * @toVw;
      .actBanKuai;
    }
    .defaultFun {
      height: 62 * @toVw;
      width: 62 * @toVw;
      background-position: 0 -248 * @toVw;
    }
    .defaultLook {
      height: 62 * @toVw;
      width: 62 * @toVw;
      background-position: 0 -310 * @toVw;
    }
    .defaultPlay {
      height: 62 * @toVw;
      width: 62 * @toVw;
      background-position: 0 -372 * @toVw;
    }
    .header-h {
      display: block;
      width: 62 * @toVw;
      position: absolute;
      left: 17.5 * @toVw;
      top: 20 * @toVw;
      z-index: 2;
      .headerHP {
        display: block;
        img {
          width: 42 * @toVw;
          margin-left: 10 * @toVw;
          margin-top: 5 * @toVw;
        }
      }
    }
    .index-content-block {
      position: absolute;
      top: 20 * @toVw;
      left: 80 * @toVw;
      right: 20 * @toVw;
      bottom: 20 * @toVw;
      background: white;
      border: 1 * @toVw solid #000;
      border-radius: 0 8 * @toVw 8 * @toVw 8 * @toVw;
      &.radius {
        border-radius: 8 * @toVw;
      }
    }
  }
  @media screen and (min-aspect-ratio: ~"20/8") {
    @toVw: 100/900vw;
    .backImg {
      position: fixed;
      bottom: 40 * @toVw;
      right: 20 * @toVw;
      z-index: 99999999;
      width: 60 * @toVw;
    }
    .lessonHeader {
      display: none;
    }
    .header {
      display: none;
    }
    .actBanKuai {
      background-color: white;
      border: 1 * @toVw solid transparent;
      border-left-color: black;
      border-top-color: black;
      border-bottom-color: black;
      border-radius: 8 * @toVw 0 0 8 * @toVw;
    }
    .headerHP {
      // background:url('https://static-cdn.changchangenglish.com/new-sing/static/images/index-h.png?v=2')  no-repeat;
      background-size: 62 * @toVw 434 * @toVw;
      display: inline-block;
      &.lookHP {
        height: 62 * @toVw;
        width: 62 * @toVw;
        background-position: 0 0;
        .actBanKuai;
      }
      &.defaultPlay {
        height: 62 * @toVw;
        width: 62 * @toVw;
        background-position: 0 -62 * @toVw;
      }
      &.playHP {
        height: 62 * @toVw;
        width: 62 * @toVw;
        background-position: 0 -124 * @toVw;
        .actBanKuai;
      }
      &.defaultLook {
        height: 62 * @toVw;
        width: 62 * @toVw;
        background-position: 0 -186 * @toVw;
      }
      &.home {
        height: 62 * @toVw;
        width: 62 * @toVw;
        background-position: 0 -248 * @toVw;
      }
      &.defaultFun {
        height: 62 * @toVw;
        width: 62 * @toVw;
        background-position: 0 -310 * @toVw;
      }
      &.funHP {
        height: 62 * @toVw;
        width: 62 * @toVw;
        background-position: 0 -372 * @toVw;
        .actBanKuai;
      }
    }

    .header-h {
      display: block;
      width: 62 * @toVw;
      position: absolute;
      left: 17.5 * @toVw;
      top: 20 * @toVw;
      z-index: 2;
      .headerHP {
        display: block;
        img {
          width: 42 * @toVw;
          margin-left: 10 * @toVw;
          margin-top: 5 * @toVw;
        }
      }
    }
    .index-content-block {
      position: absolute;
      top: 20 * @toVw;
      left: 80 * @toVw;
      right: 20 * @toVw;
      bottom: 20 * @toVw;
      background: white;
      border: 1 * @toVw solid #000;
      border-radius: 0 8 * @toVw 8 * @toVw 8 * @toVw;
      &.radius {
        border-radius: 8 * @toVw;
      }
    }
  }
</style>
