<template>
  <div class="news_details">
    <section class="s1">
      <div class="container">
        <div class="row">
          <main class="col-12 col-lg-9 ol">
            <div class="menu-right-details">
              <p>{{ fullData.news.summaryTitle }}</p>
              <h1 class="mb-2">{{ fullData.news.title }}</h1>
              <div class="s1-view-time">

                <!--                <nuxt-link :to="{name: 'portal-category-details',params: {portal: currentPortal ,-->
                <!--                details: fullData.news.catId.title},query: {type: 'news',page: 1, id: fullData.news._id}}" class="s1-cat">{{ fullData.news.catId.title }}-->
                <!--                </nuxt-link>-->
                <div>
                  <p class="userName">توسط {{ fullData.news._creator.firstName + ' ' + fullData.news._creator.lastName }} </p>
                  <p class="time">{{ jData(fullData.news.customDate) }}</p>
                </div>
              </div>
              <div class="d-flex justify-content-between">
                <div class="sharableLinks">
                  <p>به اشتراک بگذارید:</p>
                  <ul>
                    <li>
                      <el-popover
                          placement="top-end"
                          title=""
                          trigger="manual"
                          width="100"
                          content="آدرس کپی شد"
                          :value="popup"
                      >
                        <i @click="copyToClipboard(pageURL)" slot="reference" class="fas fa-share-alt" title="آدرس را کپی کنید"></i>
                      </el-popover>
                    </li>
                    <li>
                      <ShareNetwork
                          network="email"
                          :url="pageURL"
                          :title="fullData.news.title"
                          :description="fullData.news.shortSummaryTitle"
                      >
                        <i class="fas fa-envelope" title="ایمیل"></i>
                      </ShareNetwork>
                    </li>
                    <li>
                      <ShareNetwork
                          network="facebook"
                          :url="pageURL"
                          :title="fullData.news.title"
                          :description="fullData.news.shortSummaryTitle"
                          :hashtags="fullData.news.keywords"
                      >
                        <i class="fab fa-facebook-f" title="فیسبوک"></i>
                      </ShareNetwork>
                    </li>
                    <li>
                      <ShareNetwork
                          network="telegram"
                          :url="pageURL"
                          :title="fullData.news.title"
                          :description="fullData.news.shortSummaryTitle"
                      >
                        <i class="fab fa-telegram-plane" title="تلگرام"></i>
                      </ShareNetwork>
                    </li>
                    <li>
                      <ShareNetwork
                          network="WhatsApp"
                          :url="pageURL"
                          :title="fullData.news.title"
                          :description="fullData.news.shortSummaryTitle"
                      >
                        <i class="fab fa-whatsapp" title="واتس اپ"></i>
                      </ShareNetwork>
                    </li>
                    <li>
                      <ShareNetwork
                          network="LinkedIn"
                          :url="pageURL"
                          :title="fullData.news.title"
                          :description="fullData.news.shortSummaryTitle"
                      >
                        <i class="fab fa-linkedin-in" title="لینکد این"></i>
                      </ShareNetwork>
                    </li>
                  </ul>
                </div>
<!--                <div class="d-flex">-->
<!--                  <span><i class="far fa-eye"></i></span>-->
<!--                  <span style="margin-right: 8px; font-family: 'sansNum', sans-serif">{{fullData.news.userViews}}</span>-->
<!--                </div>-->
              </div>
              <img style="width: 100%" :src="fullData.news.cover" alt="">
              <p class="mt-2 mb-3 leadTitle">{{ fullData.news.leadTitle }}</p>
              <div class="sk-editor-field ck-content" v-html="fullData.news.pageContent"></div>
            </div>
            <div v-if="fullData.news.attachments.length">
              <el-divider></el-divider>
              <div class="row">
                <div class="col-12 view-page-terms" v-for="item in fullData.news.attachments" :key="item._id">
                  <div class="view-item-terms">
                    <div class="view-title-terms">
                      <i class="far fa-folder-open"></i>
                      <h3 :title="item.title">{{ item.title }}</h3>
                    </div>
                    <div>
                      <a class="btn btn-primary" :href="item.file" target="_blank">مطالعه کنید</a>
                      <a class="btn btn-primary" :href="item.file" target="_blank" download>دانلود</a>
                    </div>
                  </div>

                </div>
              </div>
              <el-divider></el-divider>
            </div>
            <div class="menu-right-comment" v-if="fullData.news.allowComment">
              <LineTxt label="افزودن نظر"/>

              <form @submit.prevent="post">
                <div class="row">
                  <div class="col-12 col-md-6 formRow" :class="validation.name ? 'err' : null">
                    <input v-model="message.name" class="input" name="name" type="text"
                           placeholder="نام و نام خانوادگی خود را وارد کنید"/>
                    <p v-if="validation.name">{{ validation.name.msg }}</p>
                  </div>
                  <div class="col-12 col-md-6 formRow" :class="validation.email ? 'err' : null">
                    <input v-model="message.email" class="input" name="email" type="text" placeholder="ایمیل خود را وارد کنید"/>
                    <p v-if="validation.email">{{ validation.email.msg }}</p>
                  </div>
                </div>
                <div class="formRow" :class="validation.description ? 'err' : null">
                  <textarea v-model="message.description" name="description" class="input" rows="4" placeholder="توضیحات خود را وارد کنید"></textarea>
                  <p v-if="validation.description">{{ validation.description.msg }}</p>
                </div>

                <div class="row view-captcha">
                  <div class="col-12 col-md-4 formRow" :class="validation.captcha ? 'err' : null">
                    <input v-model="message.captcha" class="input" name="captcha" type="text" placeholder="متن داخل عکس را وارد کنید"/>
                    <p class="err-captcha" v-if="validation.captcha">{{ validation.captcha.msg }}</p>
                  </div>

                  <div class="col-12 col-md-4 new-captcha">
                    <div class="captcha" v-html="captcha"></div>
                    <button @click="reloadCaptcha" type="button" class="btn btn-primary">
                      <i class="fas fa-sync-alt"></i>
                    </button>
                  </div>
                  <div class="col-12 col-md-4 btnSub">
                    <button class="btn-link" type="submit">ارسال</button>
                    <!-- <nuxt-link >SUBMIT NOW</nuxt-link> -->
                  </div>
                </div>
              </form>

              <div class="view-comment" v-if="fullData.comments.length">
                <LineTxt label="نظرات"/>
                <div class="container">
                  <div class="row view-comment-item" v-for="item in fullData.comments" :key="item._id">
                    <div class="col-6 title">
                      <h4>{{ item.name }}</h4>
                    </div>
                    <div class="col-6 date" style="text-align: left">
                      <span>{{ jData3(item.customDate) }}</span>
                    </div>
                    <div class="col-6 desc">
                      <h3>{{ item.description }}</h3>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </main>
          <aside class="col-lg-3 d-none d-lg-block">
            <div class="newests">
              <SideBarLineTxt label="جدیدترین ها"/>

              <div class="sectionStyle">
                <nuxt-link
                    v-if="newNews.docs.length"
                    v-for="item in newNews.docs"
                    :key="item._id"
                    :to="{name: 'portal-news-details', params: {portal: currentPortal,details: item._id}}"
                    v-slot="{href,navigate}"
                    custom
                >
                  <div class="news-box" :title="item.title" @click="navigate">
                    <a :href="href">
                      <h4 class="title">{{ item.title }}</h4>
                    </a>
                    <p :title="item.summaryTitle">{{ item.summaryTitle }}</p>
                    <div class="view-date-menu-left">
                      <span class="date-jalali">{{ jData2(item.customDate) }}</span>
                      <span class="date-jalali">{{ jData3(item.customDate) }}</span>
                    </div>
                  </div>
                </nuxt-link>
              </div>

            </div>

            <div class="betweenNewsPickUp mt-3">
              <SideBarLineTxt label="از میان خبر ها"/>
              <div class="sectionStyle">
                <div v-if="randomNews.length" v-for="item in randomNews" :title="item.title" class="news-with-img">
                  <nuxt-link :to="{name: 'portal-news-details', params: {portal: currentPortal,details : item._id}}">
                    <img :src="item.cover" :alt="item.title">
                    <p class="title">{{ item.title }}</p>
                    <span class="date-jalali">{{ jData2(item.customDate) }}</span>
                    <span class="date-jalali">{{ jData3(item.customDate) }}</span>
                  </nuxt-link>
                </div>
              </div>
            </div>

            <div class="mostViewed mt-3">
              <SideBarLineTxt label="پر بازدید ترین"/>
              <div class="sectionStyle">
                <nuxt-link v-if="mostViewed.docs.length" v-for="(item , index) in mostViewed.docs" :key="item._id" class="red-num-txt-box"
                           :to="{name: 'portal-news-details',params: {portal: currentPortal,details: item._id}}" :title="item.title">
                  <span class="enum">{{ index + 1 }}</span>
                  <p>{{ item.title }}</p>
                  <div class="gray-line"></div>
                </nuxt-link>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </section>

    <section class="s2">
      <div class="container">
        <LineTxt label="مطالب مرتبط"/>
        <div class="row">
          <div class="col-12 col-md-4 mb-5" v-for="item in relatedNews" :key="item._id">
            <nuxt-link
                :to="{name: 'portal-news-details',params: {portal: currentPortal,details: item._id}}"
                v-slot="{navigate,href}"
                custom
            >
              <div class="img-overlay-text" @click="navigate" :title="item.title">
                <img :src="item.thumbCover" :alt="item.title">
                <div class="txt-holder">
                  <div class="gray-back">
                    <a :href="href">{{ item.title }}</a>
                  </div>
                </div>
              </div>
            </nuxt-link>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import moment from 'moment-jalaali'

export default {
  data() {
    return {
      fullData: null,
      newNews: null,
      randomNews: null,
      mostViewed: null,
      relatedNews: null,
      message: {
        name: '',
        email: '',
        description: '',
        captcha: '',
        modelName: 'news',
        modelId: ''
      },
      validation: {},
      popup: false,
      captcha: null
    }
  },
  computed: {
    currentPortal() {
      return this.$route.params.portal
    },
    pageURL() {
      return process.client ? window.location.href : ''
    }
  },
  methods: {
    jData(data) {
      return moment(data).locale('fa').format('a h:mm - jYYYY/jMM/jDD')
    },
    jData2(data) {
      return moment(data).locale('fa').fromNow()
    },
    jData3(data) {
      return moment(data).locale('fa').format('jYYYY/jMM/jDD')
    },
    copyToClipboard(str) {
      this.popup = true
      setTimeout(() => this.popup = false, 3000)
      // Create new element
      let el = document.createElement('textarea');
      // Set value (string to be copied)
      el.value = str;
      // Set non-editable to avoid focus and move outside of view
      el.setAttribute('readonly', '');
      el.style = {position: 'absolute', left: '-9999px'};
      document.body.appendChild(el);
      // Select text inside element
      el.select();
      // Copy text to clipboard
      document.execCommand('copy');
      // Remove temporary element
      document.body.removeChild(el);


      // Show Message
      // let popup = document.getElementById("myPopup");
      // popup.classList.toggle("show");
    },
    post() {
      this.validation = {}
      this.$axios.post('/api/public/addComment', {...this.message, modelId: this.fullData.news._id})
          .then(res => {
            this.reloadCaptcha()
            this.$message({
              type: 'success',
              message: 'پیام شما با موفقیت ارسال شد'
            })
            this.message = {
              name: '',
              email: '',
              description: '',
              captcha: '',
              modelName: 'news',
              modelId: ''
            }
          })
          .catch(e => {
            this.reloadCaptcha()
            if (e.response.status === 422) this.validation = e.response.data.validation
            else console.log(e)
          })
    },
    reloadCaptcha() {
      this.$axios.get('/api/public/getCaptcha').then(res => {
        this.captcha = res.data
      })
    }
  },
  head() {
    return {
      title: 'جزئیات خبر',
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.fullData.news.summaryTitle
        },
        {
          hid: 'keywords',
          name: 'keywords',
          content: this.fullData.news.keywords
        }
      ]
    }
  },
  async asyncData({$axios, error, params}) {
    const portal = params.portal
    try {
      const request = [
        // news details
        $axios.get(`/api/public/viewNews/${encodeURIComponent(params.details)}`),
        // new news
        $axios.get('/api/public/getnews', {
          params: {
            flag: "new",
            portal: portal
          }
        }),
        // random news
        $axios.get('/api/public/getnews', {
          params: {
            flag: "random",
            portal: portal
          }
        }),
        // most viewed news
        $axios.get("/api/public/getnews", {
          params: {
            flag: "popular",
            portal: portal
          }
        }),
        // related news
        $axios.get('/api/public/getRelatedNews', {
          params: {
            portal: portal,
            title: params.details
          }
        }),
        // get captcha
        $axios.get('/api/public/getCaptcha')
      ]

      const fetch = await Promise.all(request)
      const [res, NewNews, RandomNews, mostViewed, relatedNews, captcha] = fetch
      return {
        fullData: res.data,
        newNews: NewNews.data,
        randomNews: RandomNews.data,
        mostViewed: mostViewed.data,
        relatedNews: relatedNews.data,
        captcha: captcha.data
      }
    } catch (e) {
      error({status: 404, message: 'مشکلی پیش آمده است!'})
    }
  },

}
</script>
