<template>
  <div>
    <template v-if="$isAMP">
      <NewsAmp :news="newsItem"></NewsAmp>
    </template>
    <template v-else>
      <NewsArticle :news="newsItem" :data-io-article-url="this.url" />
      <section class="grid grid_mb section">
        <div class="grid__wrapper section-wrapper">
          <div class="grid__title grid__title_left">Новости партнеров</div>
          <div v-for="(ads, i) in adsList" :key="i" class="av__news">
            <div style="heght: 400px" :id="ads.ad_click_url"></div>
            <script>
              {{ ads ? ads.script.replace(/\\/g, ``) : ''}}
            </script>
          </div>
        </div>
      </section>
      <NewsArticle v-if="$device.isMobile" v-for="nextNewsItem in nextNews" :news="nextNewsItem" :isNextNews="true" />
      <div class="news-loading" v-if="loadNextNews"></div>
    </template>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import InfiniteLoading from 'vue-infinite-loading';

export default {
  amp: 'hybrid',
  ampLayout: "amp",
  components:{
    InfiniteLoading
  },
  data() {
    return {
      adsList: [],
      list: [],
      count: 0,
      loadNextNews: false,
      nextNews: [],
      newsTime: null,
      iNextNews: 0
    }
  },
  jsonld() {
    var articleDate = new Date(this.newsItem.start_activity*1000).toISOString().substr(0,19) + '+07:00',
      author = this.newsItem.show_author ? this.newsItem.author ? this.newsItem.author.name : 'ИА Амител' : 'ИА Амител';
    return {
      '@context': 'https://schema.org',
      '@type': 'NewsArticle',
      mainEntityOfPage: {
        '@type': "WebPage",
        '@id': this.url
      },
      headline: this.newsItem.title.slice(0,110),
      description: this.newsItem.description,
      image: this.newsItem.image ? this.newsItem.image.url : '',
      datePublished: articleDate,
      author: {
        '@type': 'Person',
        name: author
      },
      publisher: {
          '@type': 'Organization',
          name: 'ИА "Амител"',
          logo: {
            '@type': 'ImageObject',
            url: require('~/static/svg/symbol/amic-logo.svg')
          }
        },
    };
  },
  computed: {
    ...mapGetters({
      newsItem: "modules/news/newsItem",
      partners1: "modules/ads/partners1",
      partners2: "modules/ads/partners2",
      partners3: "modules/ads/partners3",
      partners4: "modules/ads/partners4",
      partners5: "modules/ads/partners5"
    }),
     status() {
      if (!this.ads) {
        return false;
      } else {
        return true;
      }
    },
  },
  mounted () {
    this.adsList.push(this.partners5)
    this.adsList.push(this.partners3)
    this.adsList.push(this.partners1)
    this.adsList.push(this.partners2)
    this.adsList.push(this.partners4)
    this.newsTime = this.newsItem.start_activity
    this.scroll()
    const s = document.createElement('script')
    s.innerHTML = `
      let invoked = false;
        window.addEventListener('scroll', function () {
        if (window.pageYOffset > 500 && invoked == false) {
        invoked = true;
        adfoxCallOverlay = function () {
        window.Ya.adfoxCode.hbCallbacks.push(function() {
        window.yaContextCb.push(function() {
        Ya.adfoxCode.create({
        ownerId: 359693,
        containerId: 'adfox_16709195876369765',
        params: {
        pp: 'bqeb',
        ps: 'gduo',
        p2: 'hywv'
        },
        onLoad: function(data) {
        console.log(data);
        },
        onRender: function () {
        console.log('ads rendered');
        },
        onError: function (error) {
        console.log(error);
        },
        onStub: function () {
        console.log('Server return no ad');
        }
        }, ['tablet', 'phone'], {
        tabletWidth: 1023,
        phoneWidth: 768,
        isAutoReloads: false
        });
        });
        });
        };
        makeAdfinityOverlay(adfoxCallOverlay, 5, 0, "adfox_16709195876369765", 300, 180,
        false);
        }
        });
      `
    document.body.appendChild(s)
  },
  async fetch({ store, route, redirect, error }) {
    await store.dispatch("modules/news/setNewsItem", route.params);
    await store.dispatch("modules/ads/getAds");
    const newsItem = store.getters['modules/news/newsItem'];
    if(!newsItem) error({ statusCode: 404 });
    if(newsItem.category.parent){
      if(newsItem.category.parent.alias === 'video'){
        redirect ('/video/' + newsItem.category.alias + '/' + newsItem.alias);
      }
      if (newsItem.category.parent.alias === 'slushay'){
        redirect ('/podcasts/' + newsItem.category.alias + '/' + newsItem.alias);
      }
    }
    if(newsItem && newsItem.link) redirect (newsItem.link);
  },

  async asyncData(context) {
    const host = context.req ? context.req.headers.host : window.location.origin;
    const url = host + context.route.path;
    return { url }
  },

  head() {
    return {
      title: this.newsItem.title,
      meta: [
        {
          name: "author",
          content: this.newsItem.show_author ? this.newsItem.author ? this.newsItem.author.name : 'ИА Амител' : "ИА Амител",
        },
        {
          name: "copyright",
          content: "ИА Амител",
        },
        {
          name: "publisher",
          content: "https://g.page/amitel?gm",
        },
        {
          name: "mediator_author",
          content: "ИА Амител",
        },
        {
          name: "description",
          content: this.newsItem.description ? this.newsItem.description : '',
        },
        {
          name: "keys",
          content: this.newsItem.meta.key ? this.newsItem.meta.key : '',
        },
        {
          hid: 'twitter:title',
          name: 'twitter:title',
          content: this.newsItem.title
        },
        {
          hid: 'twitter:description',
          name: 'twitter:description',
          content: this.newsItem.description
        },
        {
          hid: 'twitter:image',
          name: 'twitter:image',
          // content: this.newsItem.image ? this.newsItem.image.url : ''
        },
        {
          hid: 'twitter:image:alt',
          name: 'twitter:image:alt',
          content: this.newsItem.title
        },
        {
          hid: 'og:title',
          property: 'og:title',
          content: this.newsItem.title
        },
        {
          hid: 'og:description',
          property: 'og:description',
          content: this.newsItem.description
        },
        {
          hid: 'og:image',
          property: 'og:image',
          content: this.newsItem.image ? this.newsItem.image.url : ''
        },
        {
          hid: 'og:image:secure_url',
          property: 'og:image:secure_url',
          content: this.newsItem.image ? this.newsItem.image.url : ''
        },
        {
          hid: 'og:image:alt',
          property: 'og:image:alt',
          content: this.newsItem.title
        },
        {
          hid: 'og:type',
          property: 'og:type',
          content: 'website'
        },
        {
          hid: 'og:site_name',
          property: 'og:site_name',
          content: 'amic'
        },
        {
          hid: 'og:url',
          property: 'og:url',
          content: this.url
        },
        {
          hid: 'fb:app_id',
          property: 'fb:app_id',
          content: '4369125136471767'
        },
      ],
      link: [
        {rel: 'canonical', href: this.newsItem.category ? 'https://www.amic.ru/news/' + this.newsItem.category.alias + '/' + this.newsItem.alias : ''},
      ],

      script: [
        {
          //src: 'https://cdn.onthe.io/io.js/d7T3K6DqlqQy',
          async: true
        },
        {
          body: true,
          innerHTML: `this._io_config = this._io_config || {};
              this._io_config["0.2.0"] = this._io_config["0.2.0"] || [];
              this._io_config["0.2.0"].push({
              page_url: "${this.url}",
              page_url_canonical: "${this.url}",
              page_title: '${this.newsItem.title}',
              page_type: "article",
              page_language: "ru",
              article_authors: ["${this.newsItem.author ? this.newsItem.author.name : 'ИА Амител'}"],
              article_categories: ["${this.newsItem.category.name}"],
              article_type: "Статья",
              article_publication_date: "${ new Date(this.newsItem.start_activity*1000).toUTCString() }"
            })`
        },
        {
          src: 'https://cdn.ampproject.org/v0/amp-analytics-0.1.js',
          async: true,
          'custom-element': 'amp-analytics'
        },
      ],
      __dangerouslyDisableSanitizers: ['script']
    };
  },
  methods: {
    infiniteHandler($state) {
      console.log("handle");
      if (this.count < 4) {
        setTimeout(() => {
          this.count += 1;
          this.adsList.push(this.list[this.count]);
          $state.loaded();
        }, 1000);
      } else {
        $state.complete();
      }
    },
    scroll() {
      window.onscroll = () => {
        let isBottom = (document.documentElement.scrollTop + window.innerHeight) > document.documentElement.offsetHeight - 590;
        if (isBottom && !this.loadNextNews && this.newsTime && this.$device.isMobile && !this.$isAMP) {
          this.loadNextNews = true;
          this.$axios.$get("news/next/" + this.newsTime).then((res) => {
            if(res.success){
              this.nextNews.push(res.data);
              this.newsTime = res.data.start_activity;
              this.loadNextNews = false;
            }
          });
        }
      };
    }
  }
};
</script>

<style lang="less">
.detail-top__header {
  /*margin-bottom: 50px;*/
}
@media screen and (max-width: 900px) {
  .detail {
    &__wrapper {
      flex-direction: column-reverse;
    }
    &__side {
      margin-bottom: 20px;
      display: none;
    }
  }
  .detail-top {
    &__header {
      display: block;
    }
    &__footer {
      display: block;
    }
    &__footer-side {
      display: flex;
      margin-top: 20px;
    }
  }
  .detail-article-news__wrapper {
    display: block;
  }
}
.detail-article-news__side {
  display: flex;
  align-items: center;
}
.av__news {
  margin-bottom: 50px;
}
.news-loading{
  width: 25px;
  height: 25px;
  text-align: center;
  margin: 8px auto;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3c?xml version='1.0' encoding='UTF-8' standalone='no'?%3e%3csvg xmlns:svg='http://www.w3.org/2000/svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.0' width='64px' height='64px' viewBox='0 0 128 128' xml:space='preserve'%3e%3cg%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23000000'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23cccccc' transform='rotate(30 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23cccccc' transform='rotate(60 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23cccccc' transform='rotate(90 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23cccccc' transform='rotate(120 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23b2b2b2' transform='rotate(150 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23999999' transform='rotate(180 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%237f7f7f' transform='rotate(210 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23666666' transform='rotate(240 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%234c4c4c' transform='rotate(270 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23333333' transform='rotate(300 64 64)'/%3e%3cpath d='M59.6 0h8v40h-8V0z' fill='%23191919' transform='rotate(330 64 64)'/%3e%3canimateTransform attributeName='transform' type='rotate' values='0 64 64;30 64 64;60 64 64;90 64 64;120 64 64;150 64 64;180 64 64;210 64 64;240 64 64;270 64 64;300 64 64;330 64 64' calcMode='discrete' dur='600ms' repeatCount='indefinite'%3e%3c/animateTransform%3e%3c/g%3e%3c/svg%3e");
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100%;
  opacity: .4;
}
</style>
