<template>
  <div class="video-play">
    <swiper
      :options="swiperOption"
      ref="mySwiper"
    >
      <!-- 幻灯内容 -->
      <swiper-slide
        v-for="(item, index) in videoList"
        :key="index"
      >
        <div>
          <videos
            ref="videos"
            :videoList="item"
            :index="index"
            @addVideoCount="handleAddVideoCount"
          ></videos>
        </div>
        <div class="infoBar-wrap">
          <info-bar
            @addLike="handleAddLike"
            @showComment="handleShowComment"
            @addAttention="handleAttention"
            @cancelLike="handleCancelLike"
            :videoList="item"
            :isAttention="item.isFollow"
            :isLike="item.isLike"
            :source="source"
          ></info-bar>
        </div>
      </swiper-slide>
    </swiper>
    <comment
      @submitComment="onSubmitComment"
      @closeComment="onCloseComment"
      @onReachBottom="onReachBottom"
      :showComment="showComment"
      :commentList="commentList"
      :totalItemCount="totalItemCount"
      :loadingStatus="isLoading"
      :finishedStatus="isFinished"
    ></comment>
  </div>
</template>

<script>
import { Swiper, SwiperSlide } from "vue-awesome-swiper";
import videos from "../../components/shortVideo/Videos";
import infoBar from "../../components/shortVideo/InfoBar";
import comment from "../../components/shortVideo/Comment";
var host2 = process.env.VUE_APP_Url; 

import {
  addPlay,
  searchVideoList,
  addFollow,
  cancelLike,
  addLike,
  addComment,
  getCommentList,
  getVideoById,
  getMyLikeList,
  getDoctorShortVideo,
  getDoctorProduction,
  searchVideo,
  getVideoByHomePage
} from "../../api/ShortVideo/ShortVideo";
export default {
  name: "videoPlay",
  data() {
    return {
      source: "",       // 地址来源
      isLoading: false, // vant组件加载状态
      isFinished: false, // 数据是否全部加载完
      totalItemCount: 0, // 评论数据总数
      commentList: [], // 评论列表
      commentParams: {
        // 评论分页数据
        pageIndex: 1,
        pageSize: 10000,
        id: ""
      },
      videoCommentList: [], // 评论数据
      params: {
        // 视频分页参数
        pageIndex: 1,
        pageSize: 10,
        name: ""
      },
      videoTotal: 0,    // 视频分页总数
      showComment: false,
      videoList: [],
      page: this.$route.query.currentVideoIndex === 0 ? this.$route.query.currentVideoIndex : this.$route.query.currentVideoIndex - 1,    // 当前视频索引位置
      swiperOption: {
        preventInteractionOnTransition : true,
        initialSlide: this.$route.query.currentVideoIndex,    // 设定初始化时slide的索引
        direction: "vertical",
        grabCursor: true,
        setWrapperSize: true,
        autoHeight: true, // 自动高度。设置为true时，wrapper和container会随着当前slide的高度而发生变化
        slidesPerView: 1,
        mousewheel: true,
        preventClicksPropagation: true,
        mousewheelControl: true,
        height: window.innerHeight, // 高度设置，占满设备高度
        resistanceRatio: 0,
        observeParents: true,     // 将observe应用于Swiper的父元素。当Swiper的父元素变化时，例如window.resize，Swiper更新
        on: {
          tap: () => {
            this.playAction(this.page);
          },

          // 下滑结束
          slideNextTransitionStart: () => {
            this.$nextTick(_ => {
              this.page += 1;
              this.nextVideo(this.page);
            })
          },

          // 上滑结束
          slidePrevTransitionEnd: () => {
            this.$nextTick(_ => {
              if (this.page > 0) {
                this.page -= 1;
                this.preVideo(this.page)
              }
            })
          },

          // 滑块结束
          slideChangeTransitionEnd: () => {
            this.$nextTick(_ => {
              this.handleSlideChange(this.page)
              this.customShare()
            })
          }
        }
      }
    };
  },
  components: {
    Swiper,
    SwiperSlide,
    videos,
    infoBar,
    comment
  },
  mounted() {
    console.log("transfer params: ", this.$route.query)
    this.source = this.$route.query.source;
    this.commentParams.pageIndex = 1;
    this.nextPageIndex = this.$route.query.currentPageIndex + 1;
    this.prePageIndex = this.$route.query.currentPageIndex;
    this.currentVideoIndex = this.$route.query.currentVideoIndex;
    this.videoTotal = this.$route.query.videoTotal;
    this.params.name = this.$route.query.userKey || "";
    // this.videoList = this.$route.query.currentVideoList ;
    this.videoList =JSON.parse(localStorage.getItem("currentVideoList")) 
    localStorage.removeItem("currentVideoList")
    this.params.accountid = this.$route.query.accountid || "";
    this.customShare()
  },
  methods: {
    // 自定义分享方法
    customShare() {
    /* 自定义分享部分 */
    var that = this
    wx.ready(function () {
      wx.checkJsApi({
        jsApiList: ['onMenuShareAppMessage'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
        success: function (res) {
          // 以键值对的形式返回，可用的api值true，不可用为false
          // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          console.log("weixin sdk config:", res)
        }
      });
      wx.onMenuShareAppMessage({
        title: '亮健优医', // 分享标题
        desc: that.videoList[that.page].videoTitle, // 分享描述
        link: host2+`/ymallWechat/code?redirectCode=oneVideoPlayer?id=${that.videoList[that.page].id}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: 'https://image.360lj.com/userfiles/images/202005ymall/d5d11cda-826a-42fa-a1d0-78181de4a9cd.png', // 分享图标
        type: '', // 分享类型,music、video或link，不填默认为link
        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
        success: function () {
          console.log("weixin share ok...")
        }
      });
    });
    console.log("current video id: ", this.videoList[this.page].id, this.videoList[this.page].videoTitle)
    },

    // 记录视频播放次数id
    handleAddVideoCount(e){
      addPlay({ "id": e.videoData.id })
        .then(res => {
        })
        .catch(error => {
        })
    },

    switchVaild(){
      switch (this.$route.query.source) {
        case "searchVideo":
          this.getVideoData(searchVideoList);
          break;
        case "likeVideo":
          this.getVideoData(getMyLikeList);
          break;
        case "doctorDetail":
          this.getVideoData(getDoctorShortVideo);
          break;
        case "myVideos":
          this.getVideoData(getDoctorProduction);
          break;
        case "specialist":
          this.getVideoData(getVideoByHomePage);
      }
    },
    getVideoData(f) {
      if (this.videoList.length >= this.videoTotal) {
        console.log("this.videoList.length && this.videoTotal: ", this.videoList.length, this.videoTotal);
        this.$toast('没有更多视频了')
        return;
      }
      this.isRequest();
      f(this.params)
        .then(({ data }) => {
          this.$toast.clear();
          if (data.isSuccess) {
            if (data.resultObject.length === 0) {
              this.$toast('没有更多视频了');
              return;
            }
            if (!this.page > 0) {
              // 加载上一页数据
              this.page = data.resultObject.length - 1;
              this.videoList = [...data.resultObject, ...this.videoList];
              // 强行替换追加到前面的array的src地址
              this.$nextTick(_=>{
                data.resultObject.map((item, index) => {
                  document.getElementsByClassName('vjs-tech')[index].setAttribute('src', item.videoUrl);
                  if(index===data.resultObject.length-1) {
                    this.tempVideoUrl = this.videoList[data.resultObject.length].videoUrl;
                  }
              })
              })

              // $nextTick经典应用,不加不行
              this.$nextTick(_=>{
                this.$refs.mySwiper.$swiper.slideTo(data.resultObject.length, 0);
                document.getElementsByClassName('vjs-tech')[data.resultObject.length].setAttribute('src', this.tempVideoUrl);
              })
              this.prePageIndex--;
              return;
            }
            // 加载下一页数据
            this.videoList = [...this.videoList, ...data.resultObject]
            this.nextPageIndex++;
          } else {
            this.$toast(data.resultMsg)
          }
        })
        .catch(err => { this.$toast.clear() })
    },

    handleSlideChange(currentIndex) {
    },

    nextVideo(index) {
      console.log("下滑Index: ", index);
      if (index !== 0) {
        setTimeout(() => {
          this.$refs.videos[0].stop();
          this.$refs.videos[index - 1].stop();
        }, 80);
        if (index === this.videoList.length - 1) {
          this.params.pageIndex = this.nextPageIndex;
          this.switchVaild();
        }
      }
      this.$refs.videos[index].play();
    },

    preVideo(index) {
      console.log("上滑Index: ", index);
      this.$refs.videos[index + 1].stop();
      this.$refs.videos[index].play();
      if (index === 0) {
        this.params.pageIndex = this.prePageIndex - 1;
        if (this.prePageIndex === 1) {
          console.log("this.prePageIndex: ", this.prePageIndex);
          this.$toast('没有更多视频了');
          return
        }
        this.switchVaild();
      }
    },

    onReachBottom() {
      this.getVideoCommentList();
    },

    // 获取评论数据
    getVideoCommentList() {
      getCommentList({ ...this.commentParams })
        .then(res => {
          this.isLoading = false;
          if (this.commentList.length === res.data.pager.totalItemCount) {
            /*             this.$notify({
              type: "warning",
              message: "没有数据啦"
            }) */
            this.isFinished = true;
            return;
          }
          // this.commentList = [...this.commentList, ...res.data.resultObject];
          // this.commentParams.pageIndex++;
          this.commentList = res.data.resultObject;
          this.totalItemCount = res.data.pager.totalItemCount;
        })
        .catch(error => { });
    },

    // 用户取消点赞
    handleCancelLike(id) {
      cancelLike(id)
        .then(res => { })
        .catch(error => { });
    },

    // 用户点赞
    handleAddLike(id) {
      console.log("点赞: ", id);
      addLike(id)
        .then(res => { })
        .catch(error => { });
    },

    // 关注用户
    handleAttention(e) {
      console.log(e.id);
      addFollow({ id: e.id })
        .then(res => {
          this.videoList = this.videoList.map(item => {
            if (item.doctorID === e.id) {
              item.isFollow = true
            }
            return item;
          })
        })
        .catch(error => { });
    },

    // 用户点击后播放或者暂停视频
    playAction(index) {
      this.$refs.videos[index].playOrStop();
    },

    // 监听用户提交评论
    onSubmitComment(e) {
      addComment({ videoID: this.commentParams.id, content: e.content })
        .then(res => {
          this.$notify({
            type: "success",
            message: "评论成功"
          });
        })
        .catch(error => { });
      // 重新请求接口获取评论
      setTimeout(() => {
        this.getVideoCommentList();
      }, 500);
    },

    // 监听用户关闭评论
    onCloseComment(e) {
      this.showComment = false;
      this.getVideoCommentList();
      this.videoList[this.page].commentFrequency = e.commentCount;
    },

    // 监听用户打开评论界面
    handleShowComment(id) {
      this.commentParams.id = id.id;
      this.getVideoCommentList();
      // 显示评论界面
      this.showComment = true;
    }
  }
};
</script>

<style lang="less" scoped>
.video-play {
  background-color: #1d1d1d;
}

/deep/ .vjs-custom-skin > .video-js {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  // width: 80%;
}

/deep/ .vjs-custom-skin > .video-js .vjs-big-play-button {
  font-size: 2em;
}
</style>
