<!-- 健康视频课程详情 -->
<template>
  <main class="main-wrapper">
    <!-- 视频发布者信息 -->
    <div class="videoReleaseInfo" v-if="infoObject.DoctorID">
      <van-image
        :src="require('@/assets/images/doctor.png')"
        width="0.7rem"
        height="0.7rem"
        fit="cover"
        class="desc-img"
        round
        @click="$router.push(`/doctorDetail?id=${infoObject.DoctorID}`)"
      ></van-image>
      <div class="doctorInfo" @click="$router.push(`/doctorDetail?id=${infoObject.DoctorID}`)">
        <div class="name">{{ infoObject.TeacherName }}</div>
        <div class="hospital">{{ infoObject.AffiliatedHospital }}</div>
      </div>
      <div
        class="attention"
        :class="infoObject.IsFollow ? 'followed' : 'default'"
        @click="handleFollow"
      >
        <span>{{ infoObject.IsFollow ? "取消关注" : "+关注" }}</span>
      </div>
    </div>
    <!-- 视频控件 -->
    <van-sticky>
      <ljPlayer
        height="4.2rem"
        :options="options"
        @play="play"
        @ended="ended"
        @pause="pause"
        @fullscreen="fullscreen"
        @fullscreen_cancel="fullscreen_cancel"
      ></ljPlayer>
    </van-sticky>

    <!-- 视频课程信息 -->
    <div class="courseInfo">
      <div class="title">{{ infoObject.CurriculumName }}</div>
      <div class="desc">{{ infoObject.CurriculumDescribe }}</div>
      <div class="flex-center infoStatus" v-if="infoObject.IsCharge">
        <span>
          <del>
            <i>¥</i>
            {{ infoObject.OriginalPrice | getPrice }}
          </del>
          <span class="price" v-if="infoObject.IsShopping">
            <i>¥</i>
            {{ infoObject.FixedPrice | getPrice }}
          </span>
          <span class="price" v-else>
            <i>¥</i>
            {{ infoObject.Price | getPrice }}
          </span>
        </span>
        <span>已{{ infoObject.PurchasesSum + infoObject.OrderSum }}人开通</span>
      </div>
      <div class="flex-center infoStatus" v-else>
        <span></span>
        <span style="color:red">免费</span>
      </div>
    </div>
    <div class="grayBlock"></div>
    <!-- 视频详细 -->
    <div class="videoInfo">
      <van-tabs v-model="tabActive" animated swipeable title-active-color="#0691f9" color="#0691f9">
        <van-tab title="视频介绍" v-if="infoObject.IsCharge" name="a">
          <div class="introduce-wrapper" v-html="infoObject.Introduce"></div>
        </van-tab>
        <van-tab title="视频目录" v-if="!(infoObject.IsCharge && videoList.length == 1)" name="b">
          <div class="video-diversity">
            <div
              class="diversity-item"
              :class="{ 'active-item': index == activeIndex }"
              :style="index == activeIndex ? activeStyle : {}"
              v-for="(item, index) in videoList"
              :key="index"
              @click="watchVideo(item, index)"
            >
              <h3 class="left">
                <div>{{ index + 1 }}</div>
                <van-icon name="volume" v-if="index == activeIndex" />
              </h3>
              <div class="center ellips">
                <div class="title ellips">{{ item.VideoTitle }}</div>
                <div class="item-info">
                  <!-- 时长 -->
                  <div class="duration">
                    <van-icon name="play-circle-o" />
                    <van-count-down
                      ref="countDown"
                      :time="item.Duration * 1000"
                      :auto-start="false"
                      format="mm:ss"
                    />
                  </div>
                  <!-- 观看人数 -->
                  <div class="watch" v-if="false">
                    <!-- 播放次数 -->
                    <van-icon name="browsing-history-o" />
                    {{ item.PlayCount }}
                  </div>
                  <!-- 单集价格  是否收费&&!是否购买 -->
                  <div
                    class="one-price"
                    v-if="item.IsCharge && !item.IsShopping"
                  >￥{{ item.ChargeAmount | getPrice }}</div>
                </div>
              </div>
              <div
                class="right"
                v-if="infoObject.IsCharge || !(infoObject.IsCharge && infoObject.IsShopping)"
              >
                <div v-if="infoObject.IsCharge && !item.IsCharge" class="free-watch">免费试看</div>
                <div v-else-if="!item.IsShopping">
                  <img :src="iconLock" class="lock" />
                </div>
              </div>
            </div>
          </div>
        </van-tab>
      </van-tabs>
    </div>
    <!-- 收藏购买  IsCollection => 是否收藏 -->
    <div class="collection-buy">
      <div class="collection flex-center" @click="handleCollection">
        <van-icon name="like" v-if="infoObject.IsCollection" color="red" />
        <van-icon name="like-o" v-else />
        {{ infoObject.IsCollection ? "已收藏" : "收藏" }}
      </div>
      <div class="buy" v-if="infoObject.IsCharge">
        <div v-if="!infoObject.IsShopping">
          <div v-if="videoList.length == 1" @click="buyAllVideo('是否确认购买当前视频?')">立即开通</div>
          <div v-else @click="buyAllVideo('是否确认购买全套视频?')">
            开通全套视频
            <i>￥{{ infoObject.Price | getPrice }}</i>
          </div>
        </div>
        <div v-else>已开通</div>
      </div>
      <div class="buy free" v-else>免费视频</div>
    </div>

    <!-- 单集和全套购买提示 -->
    <van-popup v-model="popupShow">
      <div class="pop-up-box">
        <!-- 关闭按钮 -->
        <p>开通单集不享受优惠，开通全套视频更优惠喔！</p>
        <div class="button-close" @click="popupShow = false"></div>
        <div
          class="lj_button button-left"
          @click="VideoAddOrder(2, activeVideo.ID)"
          v-if="videoList.length > 1"
        >
          开通单集
          <span>￥{{ activeVideo.ChargeAmount | getPrice }}</span>
        </div>
        <div
          class="lj_button button-right"
          @click="VideoAddOrder(1, '')"
          v-if="videoList.length > 1"
        >
          开通全套
          <span>￥{{ infoObject.Price | getPrice }}</span>
        </div>
        <div
          class="lj_button button-center"
          @click="VideoAddOrder(1, '')"
          v-if="videoList.length == 1"
        >
          立即开通
          <span>￥{{ infoObject.Price | getPrice }}</span>
        </div>
      </div>
    </van-popup>
  </main>
</template>
<script>
import { wxMethod } from "@/assets/js/weixinShare.js";
// 判断wifi环境
import { isWifi } from "@/assets/js/utils.js";
// icon图标
import { iconLock } from "@/assets/js/icon.js";
// 视频组件
import ljPlayer from "@/components/video/LjVideo";
export default {
  name: "healthCourse",
  data() {
    return {
      activeIndex: 0, //当前播放集数
      tabActive: "a", //tab切换
      iconLock, //图标锁
      isFullscreen: false, //是否全屏
      options: {}, //视频组件需要的参数信息
      infoObject: {}, //课程信息
      videoList: [], //视频每集信息
      activeVideo: {}, //当前视频信息
      isCollect: false, //是否收藏
      popupShow: false, //单集和全套购买提示是否显示
      id: "", //课程视频id
      activeStyle: {
        background: "#8e9096b2"
      }
    };
  },
  components: {
    ljPlayer
  },
  created() {
    if (!this.$route.query.id) {
      return this.$router.back();
    }
    this.id = this.$route.query.id;

    this.VideoGetDTO();
  },
  methods: {
    // 开始播放事件
    play() {
      this.AddFrequencyOfPlay(_ => {
        this.isFullscreen ? location.reload() : "";
      });
      // 未购买提示弹窗
      let tmpVideo = this.videoList[this.activeIndex];
      if (tmpVideo.IsCharge && !tmpVideo.IsShopping) {
        setTimeout(() => {
          // 设置当前选中视频  支付金额需要使用  this.activeVideo
          this.activeVideo = tmpVideo;
          // 弹窗提示
          this.popupShow = true;
        }, 100);
      }
    },
    // 播放结束事件
    ended() {},
    // 暂停事件
    pause() {},
    // 进入全屏播放
    fullscreen() {
      console.log("全屏");
      this.isFullscreen = true;
      // 开始播放
      try {
        document.querySelector(".main-wrapper video").play();
      } catch (error) {}
    },
    // 退出全屏播放
    fullscreen_cancel() {
      console.log("退出全屏");
      this.isFullscreen = false;
    },
    // loading动画  需要 this.$toast.clear(); 关闭
    loadingStart() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0
      });
    },
    // 试看视频
    watchVideo(obj, index) {
      // 是否收费
      if (obj.IsCharge) {
        // 是否购买
        if (obj.IsShopping) {
          if (index !== this.activeIndex) {
            // 设置视频源
            this.setOptions(obj);
            this.activeIndex = index;
          }
        } else {
          // 弹窗提示
          setTimeout(() => {
            this.activeVideo = obj;
            this.popupShow = true;
          }, 100);
        }
      } else {
        if (index !== this.activeIndex) {
          // 设置视频源
          this.setOptions(obj);
          this.activeIndex = index;
        }
      }

      // 播放视频
      // setTimeout(_ => {
      //     document.querySelector(".main-wrapper video").play();
      // }, 1000);
    },
    // 购买全部视频
    buyAllVideo(title) {
      this.$dialog
        .confirm({
          title
        })
        .then(() => {
          // 购买全套视频
          this.VideoAddOrder();
        })
        .catch(() => {
          // on cancel
        });
    },
    // 设置视频信息
    setOptions(obj) {
      this.options = {
        autoplay: !obj.IsCharge || (obj.IsCharge && obj.IsShopping),
        video: {
          pic: obj.CoverPhoto,
          url: obj.VideoUrl
        }
      };
    },
    // 获取视频详情
    VideoGetDTO() {
      let self = this;
      this.loadingStart();
      this.$http
        .VideoGetDTO(this.id)
        .then(res => {
          this.$toast.clear();

          // 非wifi环境判断提示
          try {
            wxMethod(() => {
              wx.getNetworkType({
                success: function(res) {
                  var networkType = res.networkType; // 返回网络类型2g，3g，4g，wifi
                  if (networkType !== "wifi") {
                    self.$toast("当前为非wifi环境，请注意流量消耗！");
                  }
                }
              });
            });
          } catch (error) {}

          if (res.data.IsSuccess) {
            let { VideoList, ...infoObject } = res.data.ResultObject;
            // 设置课程信息
            this.infoObject = infoObject;
            // 设置分集信息
            this.videoList = VideoList; //视频集数

            if (!this.videoList.length) {
              this.$toast("视频源失效");
              setTimeout(_ => {
                this.$router.back();
              }, 2000);
            } else {
              // 设置视频播放地址
              let flag = false;
              for (let i = 0; i < VideoList.length; i++) {
                // 视频url有值 设置视频播放地址
                if (VideoList[i]["VideoUrl"]) {
                  this.setOptions(VideoList[i]);
                  this.activeVideo = VideoList[i];
                  this.activeIndex = i; // 当前播放集索引
                  flag = true;
                  break;
                }
              }

              if (!flag) {
                // 设置第一个视频
                this.setOptions(VideoList[0]);
                this.activeIndex = 0;
                this.activeVideo = VideoList[0];
              }
            }

            // 设置默认tab为课程目录
            this.$nextTick(_ => {
              this.tabActive = "a";
              setTimeout(_ => {
                this.tabActive = "b";
              }, 100);
            });
          } else {
            this.$toast(res.data.ResultMsg);
          }
        })
        .catch(err => {
          this.$toast.clear();
          this.$toast("网络错误,请刷新重试！");
        });
    },
    /**
     * 新增视频订单
     * @param {number} type 1 课程购买 2 单集购买
     * @param {string} videoId  视频单集id
     */
    VideoAddOrder(type = 1, videoId = "") {
      console.log(type);
      this.loadingStart();
      // 如果单集价格比全套的优惠价格高  改为全套购买
      if (type == 2 && this.activeVideo.ChargeAmount >= this.infoObject.Price) {
        type = 1;
      }
      this.$http
        .VideoAddOrder({
          curriCulumId: this.id, //(string, optional): 课程的id ,
          videoId: videoId, //(string, optional): 视频的id 单集购买的时候需要 ,
          type: type //(integer, optional): 1，课程购买 2单集购买
        })
        .then(res => {
          this.$toast.clear();
          if (res.data.IsSuccess) {
            // 跳转到支付页面
            this.$router.push({
              name: "confirmPay",
              query: {
                ordercode: res.data.ResultObject.ID, //订单编号
                price: res.data.ResultObject.Price, //价格
                type: 3, // 视频支付
                videoId: this.id //课程视频id
              }
            });
          } else {
            this.$toast(res.data.ResultMsg);
          }
        })
        .catch(err => {
          this.$toast.clear();
          this.$toast("网络错误,请刷新重试！");
        });
    },
    // 处理关注医生
    handleFollow() {
      if (this.infoObject.IsFollow) {
        this.VideoCancelFollow();
      } else {
        this.VideoAddFollow();
      }
    },
    // 用户新增关注
    VideoAddFollow() {
      this.loadingStart();
      this.$http
        .VideoAddFollow(this.infoObject.DoctorID)
        .then(res => {
          this.$toast.clear();
          if (res.data.IsSuccess) {
            this.$toast("关注成功");
            this.infoObject.IsFollow = true;
          } else {
            this.$toast(res.data.ResultMsg);
          }
        })
        .catch(err => {
          this.$toast.clear();
          this.$toast("网络错误,请刷新重试！");
        });
    },
    //用户取消医生关注
    VideoCancelFollow() {
      this.loadingStart();
      this.$http
        .VideoCancelFollow(this.infoObject.DoctorID)
        .then(res => {
          this.$toast.clear();
          if (res.data.IsSuccess) {
            this.$toast("取消关注成功");
            this.infoObject.IsFollow = false;
          } else {
            this.$toast(res.data.ResultMsg);
          }
        })
        .catch(err => {
          this.$toast.clear();
          this.$toast("网络错误,请刷新重试！");
        });
    },
    // 处理视频收藏
    handleCollection() {
      if (this.infoObject.IsCollection) {
        this.VideoCancelCollection();
      } else {
        this.VideoAddCollection();
      }
    },
    //用户新增视频收藏
    VideoAddCollection() {
      this.loadingStart();
      this.$http
        .VideoAddCollection(this.id) //课程id
        .then(res => {
          this.$toast.clear();
          if (res.data.IsSuccess) {
            this.$toast("收藏成功");
            this.infoObject.IsCollection = true;
          } else {
            this.$toast(res.data.ResultMsg);
          }
        })
        .catch(err => {
          this.$toast.clear();
          this.$toast("网络错误,请刷新重试！");
        });
    },
    //用户取消视频收藏
    VideoCancelCollection() {
      this.loadingStart();
      this.$http
        .VideoCancelCollection(this.id) //课程id
        .then(res => {
          this.$toast.clear();
          if (res.data.IsSuccess) {
            this.$toast("取消收藏成功");
            this.infoObject.IsCollection = false;
          } else {
            this.$toast(res.data.ResultMsg);
          }
        })
        .catch(err => {
          this.$toast.clear();
          this.$toast("网络错误,请刷新重试！");
        });
    },
    // 添加播放次数
    AddFrequencyOfPlay(callback = () => {}) {
      this.$http.AddFrequencyOfPlay(this.activeVideo.ID).then(res => {
        if (res.data.IsSuccess) {
          callback && callback();
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.grayBlock {
  height: 0.2rem;
  background-color: #f8f8f8;
}
.main-wrapper {
  padding-bottom: 1.1rem;

  /* 视频发布者信息 */
  .videoReleaseInfo {
    display: flex;
    align-items: center;
    // height: 1rem;
    padding: 0.15rem 0.2rem;

    .doctorInfo {
      flex: 1;
      text-align: left;
      margin-left: 0.2rem;
      .name {
        font-size: 0.28rem;
        color: #333333;
        margin-bottom: 0.1rem;
      }
      .hospital {
        font-size: 0.24rem;
        color: #999999;
      }
    }
    .attention {
      width: 1.4rem;
      height: 0.5rem;
      line-height: 0.5rem;
      border-radius: 0.25rem;
      font-size: 0.28rem;
      //  未关注
      &.default {
        border: solid 0.01rem #ff0031;
        color: #ff0031;
      }
      // 已关注
      &.followed {
        border: solid 0.01rem #999;
        color: #999;
      }
    }
  }

  /** 视频课程信息 */

  .courseInfo {
    padding: 0.3rem 0.2rem;
    font-size: 0.28rem;
    color: #999999;
    text-align: left;
    .title {
      color: #333333;
      font-size: 0.36rem;
    }
    .desc {
      font-size: 0.28rem;
      color: #999999;
      margin: 0.3rem 0;
    }
    .infoStatus {
      color: #999999;
      del {
        font-size: 0.28rem;
        margin-right: 0.2rem;
      }
      i {
        font-style: normal;
        font-size: 0.22rem;
      }
      .price {
        font-size: 0.36rem;
        color: red;
      }
    }
  }

  .videoInfo {
    // 课程介绍
    .introduce-wrapper {
      padding: 0.1rem;
      /deep/ img {
        display: block !important;
        width: 100% !important;
      }
      // 更改文本标签样式
      // /deep/ h1 {
      //     font-size: 2em;
      //     margin: 0.67em 0;
      // }
      // /deep/ h2 {
      //     font-size: 1.5em;
      //     margin: 0.75em 0;
      // }
      // /deep/ h3 {
      //     font-size: 1.17em;
      //     margin: 0.83em 0;
      // }
      // /deep/ h4,
      // p,
      // blockquote,
      // ul,
      // fieldset,
      // form,
      // ol,
      // dl,
      // dir,
      // menu {
      //     margin: 1.12em 0;
      // }
      // /deep/ h5 {
      //     font-size: 0.83em;
      //     margin: 1.5em 0;
      // }
      // /deep/ h6 {
      //     font-size: 0.75em;
      //     margin: 1.67em 0;
      // }
      /deep/ h1,
      h2,
      h3,
      h4,
      h5,
      h6,
      b,
      strong {
        font-weight: bolder;
      }
    }
  }
  // 课程目录
  .video-diversity {
    .diversity-item {
      background-color: #fff;
      padding: 0.2rem 0.1rem 0.2rem 0;
      display: flex;

      .left {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        font-size: 0.24rem;
        flex-shrink: 0;
        width: 0.8rem;
        .van-icon {
          color: #00a4ff;
          font-size: 0.3rem;
        }
      }
      .center {
        text-align: left;
        flex: 1;

        .title {
          font-size: 0.3rem;
          padding-bottom: 0.2rem;
        }
        .item-info {
          display: flex;
          justify-content: flex-start;
          font-size: 0.26rem;
          padding-right: 0.4rem;
          > div {
            display: flex;
            align-items: center;
            margin-right: 0.6rem;
          }
          .duration {
            // margin-right: 0.2rem;
          }
          .one-price {
            font-size: 0.36rem;
            color: #fe0000;
          }
        }
      }
      .right {
        flex-shrink: 0;
        width: 1.4rem;
        .free-watch {
          height: 0.5rem;
          line-height: 0.5rem;
          font-size: 0.24rem;
          color: #00a4ff;
          border: #00a4ff 0.01rem solid;
          border-radius: 0.25rem;
          &:active {
            background: #00a4ff;
            color: #fff;
          }
        }
        .lock {
          width: 0.45rem;
        }
      }
    }

    .active-item {
      background-color: #8e9096b2 !important;
    }
  }

  // 收藏购买
  .collection-buy {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 1rem;
    box-shadow: 0rem 0rem 0.21rem 0rem rgba(136, 192, 255, 0.24);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 0.2rem;
    background: #fff;

    .collection {
      flex: 1;
      justify-content: center;

      font-size: 0.26rem;
      .van-icon {
        font-size: 0.4rem;
        margin-right: 0.05rem;
      }
    }
    .buy {
      width: 5.33rem;
      height: 0.7rem;
      line-height: 0.7rem;
      border-radius: 0.4rem;
      background: #00a4ff;
      color: #fff;
      font-size: 0.26rem;
      &.free {
        background: #ededed;
        color: #000;
      }
      i {
        font-size: 0.3rem;
        font-style: normal;
        color: red;
      }
    }
  }
}

// 弹出提示框
.van-popup {
  background: transparent;
  .pop-up-box {
    position: relative;
    width: 6.6rem;
    height: 2.8rem;
    left: -0.2rem;
    background: url("~@/assets/images/video/toast.png") no-repeat center/90%;
    padding: 0.6rem 1rem 0.2rem 1.6rem;

    p {
      font-size: 0.32rem;
      line-height: 1.5;
      color: #ffffff;
    }

    .button-close {
      position: absolute;
      top: 0;
      right: 0;
      width: 0.8rem;
      height: 0.8rem;
    }

    .lj_button {
      position: absolute;
      bottom: 0;
      height: 0.7rem;
      line-height: 0.7rem;
      font-size: 0.24rem;
      background-image: linear-gradient(0deg, #ffef95 0%, #ffffff 100%);
      border-radius: 0.35rem;
      padding: 0 0.15rem;
      span {
        color: red;
      }
      &.button-left {
        left: 1.2rem;
      }
      &.button-right {
        right: 0.6rem;
      }
      &.button-center {
        left: 50%;
        transform: translateX(-32%);
      }
    }
  }
}
</style>
