<!-- eslint-disable vue/no-v-html-->
<template>
  <div class="article-detail-page" style="padding: 30px 0">
    <div class="left-content">
      <div class="top">
        <img
          v-if="!articleData.thumb"
          src="~/assets/images/article_cover.png"
          alt=""
          style="display: none"
        />
        <img
          v-else
          :src="articleData.thumb"
          :alt="articleData.title"
          style="display: none"
        />
        <h4>{{ articleData.title }}</h4>
      </div>
      <p>
        {{ articleData.hit }}&nbsp;<i class="el-icon-view"></i>&nbsp;&nbsp;{{
          articleData.published_at
        }}
      </p>
      <div v-if="showNovoTeacher" class="chatbot-audio">
        <img src="~/assets/images/chatbot_audio_feature.png" alt="" />
        <div>
          <h6>保护双眼，听小诺朗读</h6>
          <div>
            <img
              :style="{ display: audioPause ? '' : 'none' }"
              src="~/assets/images/play_chatbot_audio.png"
              alt=""
              @click="playPauseAudio"
            />
            <img
              :style="{ display: !audioPause ? '' : 'none' }"
              src="~/assets/images/pause_chatbot_audio.png"
              alt=""
              @click="playPauseAudio"
            />
            <div>
              <span :style="{ color: playTime != '00:00' ? '#3099EA' : '' }">{{
                playTime
              }}</span>
              <p><span :style="{ width: playWidth + '%' }"></span></p>
              <span>{{ allTime }}</span>
            </div>
          </div>
          <audio
            ref="chatbotAudio"
            :src="articleData.audio_url"
            @canplay="getDuration"
            @timeupdate="updateTime"
            @ended="audioEnd"
          ></audio>
        </div>
      </div>
      <div v-if="articleData.video_url" class="video-box">
        <video
          x5-video-player-type="h5"
          x5-video-player-fullscreen="true"
          x-webkit-airplay="true"
          x5-playsinline="true"
          webkit-playsinline="true"
          playsinline="true"
          width="100%"
          controls
          style="object-fit: fill"
          :poster="articleData.thumb"
          :src="articleData.video_url"
        ></video>
      </div>
      <div class="article-content" v-html="articleData.content"></div>
      <div class="bottom-box">
        <p
          v-if="!isLogin && deviceType === 'pc'"
          class="go-follow"
          @click="
            baiduStat('文章详情页', 'click', '文章详情页-未登录按钮');
            showLoginDialog(true);
          "
        >
          点击关注微信公众号，查看更多专业资讯
        </p>
        <div class="comment-box">
          <h6>
            <span>最新看法</span>
            <span @click="getCommentCorpus(1, 1)">发表你的看法</span>
          </h6>
          <div class="comment-content">
            <Barrage
              ref="barrage"
              class="barrage"
              :barrage-list="barrageList"
              :speed="deviceType === 'pc' ? 4 : 3"
              :loop="true"
              :channels="3"
              :border-color="'#ededed'"
              :background="'#fff'"
              :barrage-height="120"
              :device-type="deviceType"
            />
          </div>
          <p v-if="!barrageIsShow">还没有人发表看法</p>
        </div>
      </div>
    </div>
    <div
      class="right-content"
      :style="{ position: isFixed ? 'fixed' : 'static', right: right + 'px' }"
    >
      <h6 class="common-title">
        猜你喜欢<img src="~/assets/images/heart.png" alt="" />
      </h6>
      <div>
        <div
          v-for="item in recommendArticles"
          :key="item.id"
          @click="
            baiduStat(
              '文章详情页',
              'click',
              '文章点击猜你喜欢-' + item.id + '+' + item.title
            );
            goHref('/article/' + item.id);
          "
        >
          <img
            v-if="!item.thumb"
            src="~/assets/images/article_cover.png"
            alt=""
          />
          <img v-else :src="item.thumb" :alt="item.title" />
          <p>{{ item.title }}</p>
          <div class="bottom">
            <span
              >{{ item.hit
              }}<i class="el-icon-view" style="margin-right: 8px"></i
              >{{ item.collect }}<i class="el-icon-star-on"></i
            ></span>
          </div>
        </div>
      </div>
    </div>
    <div v-if="commentModelPopupShow" class="comment-model-popup">
      <div class="mask" @click="commentModelPopupShow = false"></div>
      <div class="content">
        <div
          ref="commentCorpus"
          :style="{ maxHeight: commentMaxHeight + 'px' }"
        >
          <div ref="commentCorpusContent">
            <div>
              <template v-for="(item, index) in commentModelList">
                <div :key="'comment' + item.id">
                  <p
                    :class="item.chosen ? 'chosen' : ''"
                    @click="chooseCorpus(item.id, index)"
                  >
                    {{ item.content }}
                  </p>
                </div>
              </template>
            </div>
            <p v-if="commentLoading" class="load-more">
              加载更多<i class="el-icon-loading"></i>
            </p>
          </div>
        </div>
        <p @click="commentArticle">立即发布</p>
      </div>
    </div>
    <BottomRightFixed
      :show-share="true"
      :show-collect="true"
      :is-login="isLogin"
      :is-collect="articleData.is_collected"
      :show-comment="true"
      @commentClick="getCommentCorpus(1, 2)"
      @collectClick="collectArticle"
    />
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex';

const { mapActions, mapGetters } = createNamespacedHelpers('user');
export default {
  name: 'ArticleDetailPage',
  layout: 'detail',

  validate({ params }) {
    return /^\d+$/.test(params.id);
  },

  async asyncData({ $axios, params, req, redirect }) {
    // if (!process.server) return;
    const data = await $axios.$get(
      '/article/detail/' + params.id,
      $axios.genSSROptions(req)
    );
    //            data.detail.articleData.audio_url = 'https://app.diabetes.com.cn/uploadfile/article/audio/8160-16395833618215.mp3';
    // console.log('dafa:', data);
    if (data.success === false) {
      redirect('/error?code=' + 404);
    }
    return { ...data.detail };
  },

  data() {
    return {
      audioPause: true,
      playTime: '00:00',
      allTime: '00:00',
      canPlayAudio: false,
      playWidth: 0,
      barrageIsShow: false,
      barrageList: [],
      commentModelPopupShow: false,
      commentModelList: [],
      inComment: false,
      commentPage: 1,
      commentLoading: false,
      commentHasMore: true,
      chosenCommentId: 0,
      inCollect: false,
      isFixed: false,
      right: 89,
      commentMaxHeight: 300
    };
  },

  head() {
    return {
      title: this.articleData.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: 'Home page description'
        }
      ]
    };
  },
  computed: {
    ...mapGetters({
      isLogin: 'isLogin'
    }),
    deviceType() {
      return this.$store.state.device.deviceType;
    },
    env() {
      return this.$store.state.device.env;
    }
  },

  mounted() {
    const that = this;
    this.getComment();
    this.$nextTick(() => {
      if (that.deviceType === 'pc') {
        window.addEventListener('scroll', function () {
          that.isFixed = true;
          const scrollLeft =
            document.documentElement.scrollLeft || document.body.scrollLeft;
          if (document.documentElement.offsetWidth < 1258) {
            that.right =
              89 - (1258 - document.documentElement.offsetWidth) + scrollLeft;
          } else {
            that.right = (document.documentElement.offsetWidth - 1080) / 2;
          }
        });
      } else {
        that.commentMaxHeight =
          (document.documentElement.clientHeight ||
            document.body.clientHeight) * 0.6;
        if (this.deviceType === 'ios') {
          if (that.env === 'wechat') {
            document.addEventListener(
              'WeixinJSBridgeReady',
              function () {
                that.$refs.chatbotAudio.play();
                that.$refs.chatbotAudio.pause();
                that.$refs.chatbotAudio.currentTime = 0;
              },
              false
            );
          } else {
            window.onload = function () {
              that.$refs.chatbotAudio.play();
              that.$refs.chatbotAudio.pause();
              that.$refs.chatbotAudio.currentTime = 0;
              if (!isNaN(that.$refs.chatbotAudio.duration)) {
                const duration = that.$refs.chatbotAudio.duration;
                let minutes = parseInt(duration / 60, 10);
                let seconds = parseInt(duration % 60);
                minutes = minutes < 10 ? '0' + minutes : minutes;
                seconds = seconds < 10 ? '0' + seconds : seconds;
                that.allTime = minutes + ':' + seconds;
                that.canPlayAudio = true;
              } else {
                that.canPlayAudio = true;
              }
            };
          }
        }
      }
    });
  },
  methods: {
    ...mapActions({
      showLoginDialog: 'showLoginDialog'
    }),
    getDuration() {
      const duration = this.$refs.chatbotAudio.duration;
      let minutes = parseInt(duration / 60, 10);
      let seconds = parseInt(duration % 60);
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      this.allTime = minutes + ':' + seconds;
      this.canPlayAudio = true;
    },
    playPauseAudio() {
      if (this.canPlayAudio) {
        if (this.audioPause) {
          this.baiduStat('文章详情页', 'click', '小诺老师语音控件');
          this.$refs.chatbotAudio.play();
        } else {
          this.$refs.chatbotAudio.pause();
        }
        this.audioPause = !this.audioPause;
      }
    },
    updateTime(e) {
      const currentTime = e.target.currentTime;
      const duration = e.target.duration;
      let minutes = parseInt(currentTime / 60, 10);
      let seconds = parseInt(currentTime % 60);
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      this.playWidth = (currentTime / duration) * 100;
      this.playTime = minutes + ':' + seconds;
    },
    audioEnd() {
      this.audioPause = true;
      this.playTime = '00:00';
      this.playWidth = 0;
    },
    async getComment() {
      const data = await this.$axios.$get(
        '/article/comment-list?aid=' + this.$route.params.id
      );
      for (const item of data.detail.commentList) {
        item.time = Math.random() * 15 + 9;
      }
      this.barrageIsShow = data.detail.commentList.length > 0;
      const _list = [];
      for (const comment of data.detail.commentList) {
        _list.push({
          content: comment.comment_content,
          color: '#939AA7',
          icon: comment.headimgurl
        });
      }
      this.barrageList = _list;
    },
    async getCommentCorpus(page, type) {
      if (!this.isLogin) {
        this.showLoginDialog(true);
      } else {
        const that = this;
        if (page === 1) {
          this.baiduStat(
            '文章详情页',
            'click',
            type === 1 ? '文章内发表你的想法-点击' : '文章内评论'
          );
          this.chosenCommentId = 0;
          this.commentModelList = [];
          this.commentPage = 1;
          this.commentHasMore = true;
          this.commentModelPopupShow = true;
          setTimeout(function () {
            that.$refs.commentCorpus.addEventListener('scroll', function () {
              // 变量scrollTop是滚动条滚动时，距离顶部的距离
              const scrollTop = that.$refs.commentCorpus.scrollTop;
              // 变量windowHeight是可视区的高度
              const contentHeight = that.$refs.commentCorpus.clientHeight;
              // 变量scrollHeight是滚动条的总高度
              const allHeight = that.$refs.commentCorpusContent.clientHeight;
              // 滚动条到底部的条件
              if (scrollTop + contentHeight > allHeight - 20) {
                // 写后台加载数据的函数 一定要用that
                that.getCommentCorpus();
              }
            });
          });
        }
        if (this.commentHasMore && !this.commentLoading) {
          this.commentLoading = true;
          const data = await this.$axios.$get(
            '/article/comment-corpus?page=' + this.commentPage
          );
          for (const item of data.detail.list) {
            item.chosen = false;
          }
          this.commentPage = this.commentPage + 1;
          this.commentModelList = this.commentModelList.concat(
            data.detail.list
          );
          this.commentHasMore = data.detail.hasMore;
          this.commentLoading = false;
        }
      }
    },
    chooseCorpus(id, index) {
      for (const item of this.commentModelList) {
        item.chosen = false;
      }
      this.chosenCommentId = id;
      this.commentModelList[index].chosen = true;
    },
    async commentArticle() {
      if (this.chosenCommentId === 0) {
        this.$message({
          message: '请选择看法模版',
          type: 'warning'
        });
      } else {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const data = await this.$axios.$post('/article/user-comment', {
          aid: this.$route.params.id,
          comment_template_id: this.chosenCommentId
        });
        if (data && data.success) {
          this.baiduStat('文章详情页', 'click', '文章内发表你的想法-发表成功');
        }
        console.log(data);
        loading.close();
        this.commentModelPopupShow = false;
        this.getComment();
      }
    },
    async collectArticle() {
      if (!this.isLogin) {
        this.showLoginDialog(true);
      } else if (this.inCollect) {
        this.$message({
          message: '您的操作太快了',
          type: 'warning'
        });
      } else {
        this.baiduStat('文章详情页', 'click', '文章内收藏');
        this.inCollect = true;
        const data = await this.$axios.$post('/article/user-collect', {
          aid: this.$route.params.id
        });
        console.log(data);
        this.articleData.is_collected = data.detail.curState;
        this.inCollect = false;
      }
    },
    goHref(url) {
      let openNew = false;
      if (this.deviceType === 'pc') {
        openNew = true;
      }
      url = this.$router.resolve({
        path: url
      });
      if (openNew) {
        window.open(url.href, '_blank');
      } else {
        window.location.href = url.href;
      }
    }
  }
};
</script>
<style lang="scss">
.article-detail-page {
  position: relative;
  .left-content {
    div.top {
      margin-bottom: 20px;
      border-bottom: 1px solid $bg-color;
      padding-bottom: 30px;
      img {
        width: 100%;
        height: 407px;
        border-radius: 4px;
      }
      h4 {
        /*margin-top: 30px;*/
        font-size: 32px;
        font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
        font-weight: bold;
        color: $font-color1;
        line-height: 44px;
      }
    }
    & > p:nth-child(2) {
      margin-bottom: 20px;
      font-size: 16px;
      font-family: Apis-Regular, Apis;
      font-weight: 400;
      color: #bac0c2;
      line-height: 28px;
    }
    .video-box {
      margin-bottom: 20px;
      video {
        width: 100%;
      }
    }
    .chatbot-audio {
      position: relative;
      margin-bottom: 20px;
      padding: 16px 16px 0 85px;
      width: 100%;
      height: 105px;
      background: $bg-color;
      border-radius: 8px;
      box-sizing: border-box;
      & > img {
        position: absolute;
        top: 12px;
        left: 12px;
        width: 57px;
        height: 87px;
      }
      & > div {
        h6 {
          font-size: 18px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
          color: #333;
          line-height: 25px;
        }
        & > div {
          position: relative;
          margin-top: 25px;
          padding-left: 48px;
          & > img {
            position: absolute;
            top: -17px;
            left: -10px;
            width: 60px;
            height: 60px;
            cursor: pointer;
          }
          div {
            display: flex;
            & > span {
              width: 38px;
              font-size: 12px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: $font-color3;
              line-height: 17px;
            }
            p {
              position: relative;
              margin-top: 7px;
              width: calc(100% - 76px);
              height: 3px;
              background: #e3e3e3;
              border-radius: 2px;
              span {
                position: absolute;
                top: 0;
                left: 0;
                height: 3px;
                background: linear-gradient(90deg, #3b97de 0%, #38b0ff 100%);
                border-radius: 2px;
              }
            }
            & > span:last-child {
              text-align: right;
            }
          }
        }
      }
    }
    .article-content {
      border-bottom: 1px solid $bg-color;
      padding: 23px 0;
      font-size: 18px;
      color: $font-color1;
      line-height: 30px;
      img {
        max-width: 100%;
        border-radius: 4px;
      }
    }
    .bottom-box {
      padding-top: 20px;
      div.comment-box {
        position: relative;
        h6 {
          height: 50px;
          span:first-child {
            font-size: 24px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: $main-blue-color;
            line-height: 50px;
          }
          span:last-child {
            float: right;
            width: 208px;
            height: 50px;
            background: #3099ea;
            border-radius: 4px;
            text-align: center;
            font-size: 18px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: $body-color;
            line-height: 50px;
            cursor: pointer;
          }
        }
        .comment-content {
          position: relative;
          margin-top: 24px;
          height: 365px;
          box-sizing: border-box;
          .baberrage-item {
            padding: 0;
            .barrage-items {
              display: inline-block;
              border: 1px solid #ededed;
              padding: 0 20px 0 10px;
              height: 60px;
              background: $body-color;
              border-radius: 30px;
              box-sizing: border-box;
              img {
                margin: 9px 10px 0 0;
                @include roundFun(40px);
              }
              span {
                font-size: 18px;
                font-family: AppleColorEmoji;
                color: $font-color3;
                line-height: 58px;
              }
            }
          }
        }
        & > p {
          position: absolute;
          top: 100px;
          width: 100%;
          font-size: 20px;
          color: $font-color1;
          text-align: center;
          line-height: 100px;
        }
      }
    }
  }
  .right-content {
    position: fixed;
    top: 116px;
    .common-title {
      padding: 0 0 8px;
      font-size: 18px;
      color: $font-color1;
      line-height: 25px;
      img {
        margin: 3px 0 0 4px;
        width: 20px;
        height: 20px;
      }
    }
    & > div {
      & > div {
        display: block;
        position: relative;
        border-bottom: 1px solid $bg-color;
        padding: 20px 0 0 124px;
        height: 120px;
        box-sizing: border-box;
        img {
          position: absolute;
          left: 0;
          width: 110px;
          height: 80px;
          border-radius: 4px;
        }
        p {
          font-size: 16px;
          color: $font-color1;
          line-height: 24px;
          @include textEllipsisMore1Line(2);
        }
        div.bottom {
          position: absolute;
          right: 0;
          bottom: 19px;
          text-align: right;
          span {
            font-size: 16px;
            font-family: Apis-Regular, Apis;
            font-weight: 400;
            color: #bac0c2;
            line-height: 28px;
            i {
              margin-left: 3px;
            }
          }
        }
      }
    }
  }
  .comment-model-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9;
    .mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    .content {
      position: absolute;
      bottom: 0;
      left: 0;
      border: 1px solid #e3e3e3;
      padding: 44px 0 42px;
      width: 100%;
      box-shadow: 0 -10px 10px 0 rgba(0, 0, 0, 0.08);
      border-radius: 4px 4px 0 0;
      background: $body-color;
      text-align: center;
      & > div {
        overflow-y: scroll;
        margin: 0 auto 39px;
        max-width: 1044px;
        max-height: 300px;
        & > div {
          & > div {
            display: flex;
            flex-wrap: wrap;
            & > div {
              padding: 0 14px;
              p {
                margin-bottom: 20px;
                border: 1px solid $bg-color;
                padding: 0 20px;
                min-width: 320px;
                height: 60px;
                box-sizing: border-box;
                background: $bg-color;
                font-size: 16px;
                font-family: AppleColorEmoji;
                color: #292b2c;
                line-height: 58px;
                @extend .text-ellipsis;
                border-radius: 30px;
                cursor: pointer;
              }
              p.chosen {
                border-color: #3099ea;
                background: rgba(48, 153, 234, 0.1);
              }
            }
          }
        }
      }
      & > p {
        margin: 0 auto;
        width: 325px;
        height: 50px;
        background: #3099ea;
        border-radius: 4px;
        font-size: 18px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: $body-color;
        line-height: 50px;
        cursor: pointer;
      }
    }
  }
}
.isMobile {
  .article-detail-page {
    padding: 11px 15px 400px !important;
    background: $body-color;
    .left-content {
      div.top {
        margin-bottom: 10px;
        padding-bottom: 10px;
        h4 {
          font-size: 24px;
          line-height: 30px;
        }
      }
      & > p:nth-child(2) {
        margin-bottom: 10px;
        font-size: 14px;
      }
      .chatbot-audio {
        margin-top: 20px;
        padding: 25px 15px 10px 70px;
        & > img {
          left: 10px;
          top: -15px;
        }
        & > div {
          & > div {
            margin-left: -55px;
            padding: 0;
            width: calc(100% + 55px);
            & > img {
              top: -62px;
              right: -13px;
              left: auto;
            }
          }
        }
      }
      .bottom-box {
        position: absolute;
        bottom: 20px;
        left: 0;
        padding: 0 15px;
        width: 100%;
        box-sizing: border-box;
        div.comment-box {
          h6 {
            height: 40px;
            span:first-child {
              display: none;
            }
            span:last-child {
              width: 150px;
              height: 40px;
              line-height: 40px;
            }
          }
          .comment-content {
            height: 290px;
            .z_barrage {
              left: -15px;
            }
          }
        }
      }
    }
    .right-content {
      float: none;
      padding-top: 10px;
      width: 100%;
      & > div {
        & > div {
          margin-bottom: 10px;
          border: none;
          padding: 15px 15px 12px;
          height: auto;
          background: #f1f1f1;
          border-radius: 10px;
          box-sizing: border-box;
          img {
            display: none;
          }
          div.bottom {
            position: unset;
            margin-top: 4px;
            text-align: left;
          }
        }
      }
    }
    .comment-model-popup {
      z-index: 10;
      .mask {
        background: rgba(0, 0, 0, 0.5);
      }
      .content {
        border: none;
        padding: 62px 15px 15px;
        box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.05);
        border-radius: 20px 20px 0 0;
        box-sizing: border-box;
        & > div {
          margin: 0;
          width: 100%;
          max-width: none;
          & > div {
            & > div {
              display: block;
              & > div {
                padding: 0;
                p {
                  margin-bottom: 10px;
                  border: none;
                  padding: 11px 15px;
                  height: auto;
                  min-width: auto;
                  background: #eef5fb;
                  border-radius: 10px;
                  box-sizing: border-box;
                  text-align: left;
                  font-size: 16px;
                  font-family: AppleColorEmoji;
                  color: $font-color1;
                  line-height: 26px;
                  &.chosen {
                    color: #3099ea;
                  }
                }
              }
            }
          }
        }
        & > p {
          position: absolute;
          top: 15px;
          right: 15px;
          width: 100px;
          height: 32px;
          line-height: 32px;
          font-size: 16px;
        }
      }
    }
  }
}
</style>
