<template>
  <div>
    <section class="detail section" :id="'news_' + news.id">
      <div :class="isNextNews ? 'detail__wrapper section-wrapper section-wrapper_extra inner-newspage detail__wrapper-next-news' : 'detail__wrapper section-wrapper section-wrapper_extra inner-newspage'">
        <main class="detail__main">
          <div class="detail-main">
            <div class="detail-main__wrapper">
              <div class="detail-main__topic">
                <div v-if="userPermissionGroup === 3 || userPermissionGroup === 5" class="admin-button-in-news">
                  <a class="copy" :href="'/admin/publications/' + news.id" target="_blank">Редактирование новости</a>
                  <a class="inject" @click="inject(news)">Инжект</a>
                </div>
                <ul class="detail-main__topic-list">
                  <li class="detail-main__topic-item">
                    <nuxt-link :to="{ name: 'news' }" class="detail-main__topic-link">
                      Новости
                    </nuxt-link>
                  </li>
                  <li v-for="category in breadcrumbs" :key="category.alias" class="detail-main__topic-item" >
                    <nuxt-link :to="{name: 'news-category', params: { category: category.alias }}" class="detail-main__topic-link" href="javascript:void(0)">
                      {{ category.name }}
                    </nuxt-link>
                  </li>
                </ul>
              </div>

              <div class="detail-main__top">
                <div class="detail-top">
                  <div class="detail-top__header">
                    <main class="detail-top__header-main">
                      <h1 class="detail-top__title title_h1">
                        {{ news.title }}
                      </h1>
                      <p class="article_preview">
                        {{ news.description }}
                      </p>
                      <div class="detail-top__date">
                        {{ convertDate(news.start_activity)
                        }}{{
                          news.show_author && news.author
                            ? ", " + news.author.name
                            : ""
                        }}
                      </div>
                    </main>
                    <aside class="detail-top__header-side">
                      <div class="detail-top__actions">
                        <div class="detail-top__share">
                          <div class="socials-share">
                            <ul class="socials-share__list">
                              <li class="socials-share__item">
                                <ShareNetwork
                                  network="Odnoklassniki"
                                  :url="'https://www.amic.ru' + $route.fullPath"
                                  :title="news.title"
                                  class="socials-share__link"
                                  :hashtags="
                                    news.hash_tags.length
                                      ? news.hash_tags.join(' ')
                                      : ''
                                  "
                                >
                                  <BaseIcon :name="'ok'" clear/>
                                </ShareNetwork>
                              </li>
                              <li class="socials-share__item">
                                <ShareNetwork
                                  network="twitter"
                                  :url="'https://www.amic.ru' + $route.fullPath"
                                  :title="news.title"
                                  class="socials-share__link"
                                  :hashtags="
                                    news.hash_tags.length
                                      ? news.hash_tags.join(' ')
                                      : ''
                                  "
                                >
                                  <BaseIcon :name="'tw'" clear/>
                                </ShareNetwork>
                              </li>
                              <li class="socials-share__item">
                                <ShareNetwork
                                  network="vk"
                                  :url="'https://www.amic.ru' + $route.fullPath"
                                  :title="news.title"
                                  :description="news.description"
                                  class="socials-share__link"
                                  :hashtags="
                                    news.hash_tags.length
                                      ? news.hash_tags.join(' ')
                                      : ''
                                  "
                                  >
                                  <BaseIcon :name="'vk'" clear/>
                                </ShareNetwork>
                              </li>
                            </ul>
                          </div>
                        </div>
                      </div>
                      <a
                        class="
                          detail-top__action detail-top__comments-button
                          button button_grey-dark
                        "
                        :href="hrefCommentsForm"
                      >
                        <span class="button__text">Комментировать</span>
                      </a>
                    </aside>
                  </div>
                  <div class="detail-top__footer">
                    <main class="detail-top__footer-main">
                      <div class="detail-top__gallery" v-if="news.gallery">
                        <client-only>
                          <div class="detail-top__images">
                            <VueSlickCarousel
                              ref="galleryImages"
                              :asNavFor="$refs.galleryThumbs"
                              :focusOnSelect="true"
                              :draggable="false"
                              :arrows="true"
                              @beforeChange="syncSliders"
                            >
                              <div
                                class="detail-top__image"
                                v-for="(img, i) in news.gallery"
                                :key="i"
                              >
                                <img
                                  @click="index = i"
                                  :src="img.url"
                                  :alt="img.title"
                                />
                              </div>
                              <template #prevArrow="arrowOption">
                                <button
                                  class="
                                    button
                                    button_news-slider
                                    button_news-slider-prev
                                  "
                                >
                                  <BaseIcon :name="'h-slider-prev'" clear />
                                </button>
                              </template>

                              <template #nextArrow="arrowOption">
                                <button
                                  class="
                                    button
                                    button_news-slider
                                    button_news-slider-next
                                  "
                                >
                                  <BaseIcon :name="'h-slider-next'" clear />
                                </button>
                              </template>
                            </VueSlickCarousel>
                          </div>
                          <div class="detail-top__thumbs">
                            <VueSlickCarousel
                              ref="galleryThumbs"
                              :asNavFor="$refs.galleryImages"
                              :focusOnSelect="true"
                              :draggable="false"
                              :touchThreshold="4"
                              :slidesToScroll="1"
                              :slidesToShow="4"
                              :arrows="false"
                              @beforeChange="syncSliders"
                            >
                              <div
                                class="detail-top__thumb"
                                v-for="(img, i) in news.gallery"
                                :key="i"
                              >
                                <img :src="img.url" :alt="img.title" />
                              </div>
                            </VueSlickCarousel>
                          </div>
                          <Tinybox v-model="index" :images="images" />
                        </client-only>
                      </div>
                      <div class="detail-top__figure" v-else-if="news.image">
                        <img
                          v-show="imgloaded"
                          class="detail-top__img"
                          :src="news.image ? news.image.url : ''"
                          alt=""
                          @load="ImgLoaded"
                        />
                        <v-sheet style="sheet-custom">
                          <v-progress-circular
                            v-if="!imgloaded"
                            indeterminate
                            color="primary"
                          ></v-progress-circular>
                        </v-sheet>
                      </div>
                    </main>
                    <aside class="detail-top__footer-side">
                      <div class="detail-top__author">
                        <div class="news-author news-author_article">
                          <NewsAuthor :news="news" />
                        </div>
                      </div>
                      <div class="detail-top__info">
                        <div>{{ news.image && news.image.title && news.image.title !== 'example' ? news.image.title : news.source }}</div>
                      </div>
                      <div class="detail-top__tags">
                        <ul class="detail-top__tags-list">
                          <li class="detail-top__tags-item">
                            <a
                              class="detail-top__tags-link"
                              href="javascript:void(0)"
                              v-for="tag in news.hash_tags"
                              :key="tag"
                            >
                              {{ tag }}</a
                            >
                          </li>
                        </ul>
                      </div>
                    </aside>
                  </div>
                </div>
              </div>
              <div v-if="news.video" class="detail__video">
                <iframe class="detail__iframe" :src="videoLink" frameborder="0"></iframe>
              </div>
              <NewsContent :rawHtml="news.content" :isAdvert="isAdvert()" ref="newsContent" />
              <!--<div class="detail-main__views">
                Просмотров: {{ news.views_counter }}
              </div>-->

              <div class="detail-main__files mt-5">

                <a
                  v-for="file in news.files"
                  :href="file.url"
                  :key="file.url"
                  target="_blank"
                >
                  {{ file.original_name }}
                </a>
              </div>

              <div class="detail-main__properties mt-5">
                <span
                  v-for="property in properties"
                  :key="property.id"
                  :class="property.code"
                  :ref="property.code"
                >
                  {{ property.title }}
                </span>
              </div>
              <BannersW960H90 :idMobil="news.id" />
              <div v-if="news.show_pull" :id="idForm">
                <ArticleCommentsList :pull_id="news.comment_pull_id" @commentResponse="commentResponseData" :newCommentsList="commentsList" />
                <ArticleCommentsForm :pull_id="news.comment_pull_id" :response_user_name="this.comment.response_user_name" :response_user_id="this.comment.response_user_id" @clearCommentResponse="clearCommentResponse" @commentsResponseData="commentsResponseData" />
              </div>
            </div>
          </div>
        </main>
        <aside class="detail__side lenta">
          <h2 class="news-side__title"><a href="/news">Лента новостей</a></h2>
          <ul class="news-side-list">
            <WidgetLent v-bind:params="{showad:true,showadMainPage:false}" />
          </ul>
        </aside>
        <div>
          <BannersSkyScrapperVideo v-if="!isNextNews" />
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import NewsService from '../../services/NewsService'

export default {
  components: {
    VueSlickCarousel: () => import("vue-slick-carousel").then((m) => m.default),
    Tinybox: () => import("vue-tinybox").then((m) => m.default),
  },
  props: {
    news: {
      type: Object,
    },
    isNextNews: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      userPermissionGroup: null,
      imgloaded: false,
      hrefCommentsForm: '#comment_form_' + this.news.comment_pull_id,
      comment: {
        text: "",
        response_user_id: "",
        response_user_name: "",
        pullId: this.news.comment_pull_id,
      },
      index: null,
      idForm: 'comment_form_' + this.news.comment_pull_id,
      commentsList: {},
      thisUrl: '/news/' + this.news.category.alias + '/' + this.news.alias + '/',
    };
  },
  computed: {
    videoLink() {
      if (this.news.video.match("(www.)?youtube|youtu.be")) {
        const youtubeId = this.news.video
                .split(/v\/|v=|youtu\.be\//)[1]
                .split(/[?&]/)[0];
        return `https://www.youtube.com/embed/${youtubeId}`;
      }

      return this.news.video;
    },

    properties() {
      return Object.values(this.news.properties).filter((property) =>
        Number(property.value)
      );
    },
    images() {
      return this.news.gallery.map((image) => image.url);
    },

    breadcrumbs() {
      let current = this.news.category;
      const categories = [current];

      while (current.parent) {
        current = current.parent;
        categories.push(current);
      }

      return categories.reverse();
    },
  },



  mounted () {
    if(this.$device.isMobile){
      addEventListener('scroll', this.linkUpdate, false);
    }
    if(this.$store.state.auth.user){
      this.userPermissionGroup = this.$store.state.auth.user.user_permission_group;
    }

    //Set height 5% of content for contraindications
    if (!this.$refs.contraindications) return;

    setTimeout(() => {
      let [block] = this.$refs.contraindications;
      let height = this.$refs.newsContent.$el.offsetHeight;

      if (height < 1500) height = 1500;

      block.style.minHeight = `${height * 0.05}px`;
      block.style.fontSize = `${height * 0.015}px`;
    }, 1000);
  },
  methods: {
    isAdvert() {
      let isAdvert = false
      try {
        isAdvert = Boolean(Number(this.news.properties.advertisement.value))
      } catch (e) {}
      return isAdvert
    },
    convertDate(dateTampstamp) {
      const date = new Date(dateTampstamp * 1000);
      const dateString =
        date.toLocaleString("ru", {
          day: "numeric",
          month: "long",
        }) +
        " " +
        date.getFullYear() +
        ", " +
        ("0" + date.getHours()).slice(-2) +
        ":" +
        ("0" + date.getMinutes()).slice(-2);
      return dateString;
    },
    commentsResponseData(data){
      this.commentsList = data;
      console.log(this.commentsList);
    },
    commentResponseData(data){
      this.comment.response_user_id = data.user_id;
      this.comment.response_user_name = data.user_name;
    },
    clearCommentResponse(){
      this.comment.response_user_id = "";
      this.comment.response_user_name = "";
    },
    syncSliders(currentPosition, nextPosition) {
      this.$refs.galleryThumbs.goTo(nextPosition);
      this.$refs.galleryImages.goTo(nextPosition);
    },
    ImgLoaded() {
      this.imgloaded = true
    },
    inject(item) {
      let res = "##news_" + item.id + "##";
      this.$clipboard(res);
      alert('Инжект скопирован в буфер обмена');
    },
    linkUpdate () {
      return true;
      let cont =  document.querySelector('#news_' + this.news.id);
      if(cont!==null){
        let rect =cont.getBoundingClientRect();
        let targetPosition = {
            top: window.pageYOffset + (rect.top + document.documentElement.clientHeight - 150),
            left: window.pageXOffset + rect.left,
            right: window.pageXOffset + rect.right,
            bottom: window.pageYOffset + (rect.bottom - document.documentElement.clientHeight + 200)
          },
          windowPosition = {
            top: window.pageYOffset,
            left: window.pageXOffset,
            right: window.pageXOffset + document.documentElement.clientWidth,
            bottom: window.pageYOffset + document.documentElement.clientHeight
          };
        if (targetPosition.bottom > windowPosition.top && targetPosition.top < windowPosition.bottom && targetPosition.right > windowPosition.left && targetPosition.left < windowPosition.right) {
          if(this.thisUrl !== document.location.pathname){
            history.pushState(null, this.news.title, this.thisUrl);
          }
        }
      }
    }
  },
};
</script>

<style lang="less">
.detail__wrapper-next-news{
  margin-top: -30px;
}
.sheet-custom {
  text-align: center;
}
h2{
  margin-bottom: 20px;
}
.detail{
  &__video{
    column-count: 1;
    position: relative;
    &:before{
      content: " ";
      padding-bottom: calc(100% / (16 / 9));
      float: left;
    }
  }
  &__iframe{
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
}
.article_preview {
  max-width: 810px;
  font-size: 20px;
  line-height: 140%;
  padding-bottom: 20px;
  color: #737373;
}
.news-author__figure {
  flex: none;
  width: 50px;
  height: 50px;
}
.news-author__img {
  max-width: 100%;
}
ol {
  /*вопрос-ответ*/
  margin: 40px 20px;
  li {
    padding-left: 20px;
    margin-bottom: 40px;
    strong {
      display: block;
      font-size: 22px;
      padding: 20px 0 10px;
      border-top: 2px solid #f6911f;
    }
    &::marker {
      color: #f6911f;
      text-align: right;
      font-weight: bold;
      font-size: 22px;
      content: counter(list-item) " ";
    }
  }
}
.Card-fon {
  .redLine {
    padding-left: 10px;
    margin-bottom: 40px;
    position: relative;
    .numeric {
      color: #f6911f;
      font-weight: bold;
      font-size: 22px;
      float: left;
      padding: 20px 10px 0 0;
      height: 70px;
    }
  }
  .Card-vnutr {
    display: block;
    font-size: 22px;
    padding: 18px 0 10px;
    border-top: 2px solid #f6911f;
    font-weight: bold;
  }
  .Card-text {
    clear: both;
  }
}
h5 {
  /*источник фото*/
  font-weight: normal;
  opacity: 0.6;
}
h6 {
  /* выделить цветом  - colored */
  font-weight: normal;
  background-color: rgb(247 245 238);
  padding: 20px 10px 20px 20px;
  margin: 30px 0;
  border-left: 2px solid #f6911f;
  line-height: 150%;
  font-size: 20px;
  html.dark-mode & {
    background-color: rgba(128, 128, 128, 0.3);
  }
}
blockquote {
  /* цитата */
  margin: 30px 0;
  padding: 20px 0;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  p {
    font-size: 28px;
    line-height: 140%;
  }
  @media screen and(max-width: 768px) {
    margin: 20px 0;
    padding: 10px 0;
    p{
      font-size: 22px;
    }
  }
}
.admin-button-in-news{
  margin-bottom: 30px;
  a{
    background-color: #000;
    color: #fff;
    font-size: 14px;
    padding: 8px 19px;
    cursor: pointer;
  }
  .inject{
    background-color: #1976d2;
  }
  .copy{
    background-color: #4caf50;
  }
}
.inner-newspage{
  position: relative;
  .detail{
    &__main {
      @media (min-width: 1100px) and (max-width: 1380px) {
        max-width: 65%;
      }
      @media (min-width: 900px) and (max-width: 1100px) {
        max-width: 55%;
      }
    }
  }
  .lenta{
    position: absolute;
    width: 100%;
    right: 0;
    height: 100%;
    @media (min-width: 1100px) and (max-width: 1380px) {
      max-width: 34%;
    }
    @media (min-width: 900px) and (max-width: 1100px) {
      max-width: 44%;
    }
    .news-side{
      &__list{
        height: 100%;
        width: 100%;
        overflow: scroll;
        position: absolute;
        background: white;
      }
    }

  }
}

</style>
