<template>
  <div class="videoList-wrap">
    <swiper :options="swiperOption">
      <!-- 幻灯内容 -->
      <swiper-slide v-for="(item, index) in videoList" :key="index">
        <div>
          <videos
            ref="videos"
            :videoList="item"
            :index="index"
            @addVideoCount="handleAddVideoCount"
          ></videos>

          <div
            class="jump-icon"
            :style="userType !== 2 ? 'justify-content: flex-end' : ''"
          >
            <i @click="jumpUpload" v-show="userType === 2"
              ><img src="../../static/imgs/upload-icon.png" alt=""
            /></i>

            <router-link to="/searchVideo"
              ><img src="../../static/imgs/search-icon.png" alt=""
            /></router-link>
          </div>
        </div>
        <info-bar
          @addLike="handleAddLike"
          @showComment="handleShowComment"
          @addAttention="handleAttention"
          @cancelLike="handleCancelLike"
          :videoList="item"
          :isAttention="item.IsFollow"
          :isLike="item.IsLike"
        ></info-bar>
      </swiper-slide>
    </swiper>
    <comment
      @submitComment="onSubmitComment"
      @closeComment="onCloseComment"
      :showComment="showComment"
      :commentList="commentList"
      :totalItemCount="totalItemCount"
    ></comment>
    <van-overlay :show="show" />
    <van-loading
      class="loading-btn"
      size=".24rpx"
      color="#fff"
      vertical
      v-show="isLoading"
      >加载中...</van-loading
    >
  </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; // 获取不同环境下不同的api路径
import {
  searchVideoList,
  addFollow,
  cancelLike,
  addLike,
  addComment,
  getCommentList,
  searchVideoListByHome,
  addPlay,
  getUserInfo,
  getDoctorInfo 
} from "../../api/ShortVideo/ShortVideo";
export default {
  data() {
    return {
      userType: "", // 用户信息
      show: false, // 遮罩层
      hasMoreVideo: true, // 是否还有更多视频
      isLoading: false, // 是否显示加载按钮
      totalItemCount: 0, // 评论数据总数
      commentList: [], // 评论列表
      commentParams: {
        pageIndex: 1,
        pageSize: 10000,
        id: "",
      }, // 评论分页数据
      videoCommentList: [], // 评论数据
      params: {
        // 视频分页参数
        pageIndex: 1,
        pageSize: 5,
        name: "",
      },
      showComment: false,
      videoList: [],
      page: 1,
      swiperOption: {
        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,
        on: {
          tap: () => {
            this.playAction(this.page - 1);
            event.stopPropagation();
          },
          // 下滑结束
          slideNextTransitionStart: () => {
            ++this.page;
            this.nextVideo(this.page - 1);
            event.stopPropagation();
          },
          // 上滑结束
          slidePrevTransitionEnd: () => {
            if (this.page > 1) {
              --this.page;
              this.preVideo(this.page - 1);
              event.stopPropagation();
            }
          },
          // 滑块结束
          slideChangeTransitionEnd: () => {
            setTimeout(() => {
              this.handleSlideChange(this.page);
              this.customShare();
            }, 100);
          },
        },
      },
    };
  },
  components: {
    Swiper,
    SwiperSlide,
    videos,
    infoBar,
    comment,
  },
  mounted() {
    this._getUserInfo();
    //使用微信访问，获取代理
    var ua = navigator.userAgent;
    var version = "000000";
    var key = "TBS/";
    var start = ua.indexOf(key);
    if (start !== -1) {
      start = start + key.length;
      version = ua.substr(start, ua.indexOf(" ", start) - start);
    }
    if (version.indexOf("000000") !== -1) {
    } else {
      this.$notify({
        message:
          "您当前播放设置已影响了视频的观看，请修正设置。点击查看修正方法>>",
        color: "#fff",
        background: "#2f2f2f",
        duration: 0,
        onClick: (_) => {
          this.$notify.clear();
          this.$router.push({ name: "Explain" });
        },
      });
    }
    this.params.pageIndex = 1;
    this.videoList = [];
    this.getList();
  },
  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 - 1].videoTitle, // 分享描述
          link: host2+`/ymallWechat/code?redirectCode=oneVideoPlayer?id=${
            that.videoList[that.page - 1].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("当前视频索引: ", this.page - 1);
      // console.log("current video id: ", this.videoList[this.page].ID, this.videoList[this.page].VideoTitle)
    },
    // 跳转上传视频页面
    jumpUpload() {
      // window.location.replace('http://ue.360lj.com/api/Home/Login?identity=2&backurl=http://ue.360lj.com/dist/uploadFile')
      // window.location.replace('http://linyi.natapp1.cc/api/Home/Login?identity=2&backurl=http://linyi.natapp1.cc/dist/uploadFile')
      // var doctorUserLoginUrl = process.env.VUE_APP_DoctorUserLoginUrl.replace(
      //   "SignUp",
      //   "uploadFile"
      // );
      // console.log("uploadUrl: ", doctorUserLoginUrl);
      // window.location.replace(doctorUserLoginUrl);
      
      this.$router.push({ name: 'UploadFile', query: {} })
    },
    // 获取用户基本信息
    _getUserInfo() {
      // getUserInfo()
      //   .then(({ data }) => {
      //     console.log("用户信息", res);
      //     if (data.IsSuccess) {
      //       const { userRoles } = data.resultObject;
      //       let findResult = userRoles.find((item) => item.UserRoleType === 1);
      //       this.userType = findResult.UserRoleType;
      //     } else {
      //       this.$toast.fail(data.ResultMsg);
      //     }
      //   })
      //   .catch((error) => {
      //     console.log(error);
      //   });
      getDoctorInfo()
      .then(res => {
        console.log('用户信息', res)
        if (res.data.success) {
          // this.userInfo = res.data.result;
          this.userType = res.data.result.checkStatus  //checkStatus: -1=>普通用户 ， 2=>医生（审核通过）
        } else {
          this.$toast(res.data.message)
        }
      })
      .catch(error => {
        console.log(error)
      })
    },
    // 新增视频播放次数
    handleAddVideoCount(e) {
      addPlay({ id: e.videoData.id })
        .then((res) => {})
        .catch((error) => {});
    },

    // 获取评论数据
    getVideoCommentList() {
      getCommentList({ ...this.commentParams })
        .then((res) => {
          console.log("评论列表", res.data);
          this.commentList = res.data.resultObject;
          this.totalItemCount = res.data.pager.totalItemCount;
        })
        .catch((error) => {});
    },
    // 加载数据
    getList() {
      if (this.hasMoreVideo) {
        this.isLoading = true;
        this.show = true;
        searchVideoListByHome({ ...this.params })
          .then((res) => {
            console.log("视频列表,", res);
            if (res.data.isSuccess) {
              if (res.data.resultObject.length === 0) {
                // 没有分页数据
                this.$notify({
                  type: "warning",  
                  message: "没有更多视频了", 
                  duration: 2000,
                });
                this.hasMoreVideo = false;
                this.isLoading = false;
                this.show = false;
                return;
              }
              this.videoList = [...this.videoList, ...res.data.resultObject];
              this.params.pageIndex++;
              this.isLoading = false;
              this.show = false;
              this.customShare();   
            } else {
              this.hasMoreVideo = false;
              this.isLoading = false;
              this.show = false;
              this.$toast.fail(res.data.resultMsg);
            }
          })
          .catch((error) => {});
      } else {
        return;
      }
    },

    // 滑块结束
    handleSlideChange(currentIndex) {
      if (currentIndex === this.videoList.length - 1) {
        // 用户滑动到倒数第一个视频,分页加载下一组视频
        this.getList();
      }
    },

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

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

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

    // 用户点击后播放或者暂停视频
    playAction(index) {
      this.$refs.videos[index].playOrStop();
    },
    // 滑动到下一个视频
    nextVideo(index) {
      this.$refs.videos[index - 1].stop();
      this.$refs.videos[index].play();
    },
    // 滑动到上一个视频
    preVideo(index) {
      this.$refs.videos[index + 1].stop();
      this.$refs.videos[index].play();
    },
    // 监听用户提交评论
    onSubmitComment(e) {
      addComment({ videoID: this.commentParams.id, content: e.content })
        .then((res) => {
          this.$notify({
            type: "success",
            message: "评论成功",
            duration: 1000,
          });
          // 关闭评论窗口
        })
        .catch((error) => {});
      // 重新请求接口获取评论
      setTimeout(() => {
        this.getVideoCommentList();
      }, 500);
    },

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

    handleShowComment(id) {
      this.commentParams.id = id.id;
      this.getVideoCommentList();
      // 显示评论界面
      this.showComment = true;
    },
  },
};
</script>

<style lang="less" scoped>
.videoList-wrap {
  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;
}

/deep/ .video-js .vjs-tech {
  height: 90%;
}

.loading-btn {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99999;
  .van-loading__text {
    color: #fff;
  }
}

.jump-icon {
  position: absolute;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0.2rem;
  width: 100%;
  top: 0;
  z-index: 9999;
  background-color: #333333;
  img {
    width: 0.64rem;
    height: 0.64rem;
  }
}
</style>
