<template>
  <div>
    <div>
      <v-tabs>
        <v-tab link to="publications/create"> Создать новость </v-tab>
        <v-tab link to="publications/create-category">
          Создать категорию
        </v-tab>
        <v-tab link to="publications/categories"> Категории </v-tab>
        <v-tab link to="publications/create-container"> Создать модуль </v-tab>
        <v-tab link to="publications/containers"> Модули </v-tab>
        <v-tab link to="publications/search"> Поиск </v-tab>
      </v-tabs>

      <v-btn class="my-5" @click="$modal.show('admin-filter-modal')">
        Открыть фильтр
      </v-btn>

      <v-btn class="my-5" @click="clearFilter"> Очистить фильтр </v-btn>

      <v-progress-linear
        v-if="load"
        indeterminate
        color="green"
      ></v-progress-linear>

      <v-expansion-panels multiple v-if="newsList.news">
        <v-expansion-panel v-for="news in newsList.news" :key="news.id">
          <div v-bind:class="!news.is_show ? 'disable_item_list' : ''">
            <div :class="news.news_timing">
              <v-expansion-panel-header>
                <v-col cols="1">
                  <img
                          class="catalog-item__img"
                          :src="
                    news.preview_image_for_admin
                      ? news.preview_image_for_admin.url
                      : ''
                  "
                  />
                </v-col>
                <v-col cols="5">
                  <div>
                    <b v-html="news.title"></b>
                  </div>
                  <div
                          class="mt-2 text-uppercase caption primary--text"
                          v-if="getContainerTitle(news)"
                  >
                    {{ getContainerTitle(news) }}
                  </div>
                  <div class="list-editors" v-html="news.news_user_editors"></div>
                </v-col>
                <v-col cols="1">
                  <v-list-item-subtitle>
                    <!--Категория:-->
                    {{
                    news.category_for_admin ? news.category_for_admin.title : ""
                    }}
                  </v-list-item-subtitle>
                </v-col>
                <v-col cols="2">
                  <span> </span>
                  <span> </span>
                  <v-divider vertical></v-divider>
                  <!--Время:-->
                  {{ news.start_activity }}
                </v-col>
                <v-col cols="2" @click.stop="">
                  <v-btn
                          link
                          tile
                          color="success"
                          :to="{
                    name: 'admin-publications-id',
                    params: { id: news.id },
                  }"
                  >
                    <v-icon left> mdi-pencil </v-icon>
                    <!--изменить-->
                  </v-btn>
                  <v-btn
                          tile
                          color="error"
                          @click="deleteNews(news.id)"
                          v-if="user_groups == 5"
                  >
                    <v-icon left> mdi-delete-outline </v-icon>
                    <!--удалить-->
                  </v-btn>
                  <v-btn tile color="primary" @click="copy(news)">
                    <v-icon left> mdi-content-copy </v-icon>
                    Инжект
                  </v-btn>
                </v-col>
                <v-col cols="1" @click.stop="">
                  <div class="d-flex align-center">
                    <v-switch
                            @change="changeActivity(news, $event)"
                            v-model="news.activity"
                            class="mt-0"
                            hide-details
                            inset>
                    </v-switch>
                    <v-icon v-if="news.verified" left color="green">mdi-checkbox-marked</v-icon>
                  </div>
                </v-col>
              </v-expansion-panel-header>

              <v-expansion-panel-content>
                <!--Превью новости-->
                <v-col cols="3">
                  <div v-html="news.text" class="text"></div>
                </v-col>
              </v-expansion-panel-content>
            </div>
          </div>
        </v-expansion-panel>
      </v-expansion-panels>

      <v-pagination
        v-if="newsList.news"
        v-model="counter"
        :length="newsList.total_pages"
        @input="loadNewsFilter"
        :next-icon="'>'"
        :prev-icon="'<'"
        total-visible="10"
      ></v-pagination>

      <modal adaptive height="auto" name="admin-filter-modal">
        <div class="publications-filter">
          <h3>Фильтр</h3>
          <v-row>
            <v-col>
              <v-select
                :items="categoriesList"
                item-text="title"
                item-value="id"
                v-model="filterCategory"
                label="Категория"
                clearable
              ></v-select>

              <v-date-picker
                range
                :first-day-of-week="0"
                locale="ru"
                v-model="filterActivity"
                no-title
                scrollable
                full-width
                multiple
              >
              </v-date-picker>

              <v-btn class="ml-auto success mr-0" @click="filterNews">
                Фильтровать
              </v-btn>
            </v-col>
          </v-row>
        </div>
      </modal>
    </div>
  </div>
</template>

<script>
export default {
  layout: "admin",
  data() {
    return {
      counter: 1,
      newsList: [],
      categories: [],
      filterCategory: "",
      filterActivity: [],
      load: true,
      filter: false,
      user_groups: null,
    };
  },
  async mounted() {
    await this.getCategory();
    await this.loadNews();
    this.user_groups = this.$store.state.auth.user.user_permission_group;
  },
  computed: {
    categoriesList() {
      if (!this.categories) return [];
      return this.categories;
    },
  },
  methods: {
    async getCategory() {
      this.categories = await this.$axios
        .$get("/admin/categories")
        .then((res) => res.data);
    },

    async loadNews() {
      this.newsList = await this.$axios
        .$get(`/admin/news/list?page=${this.counter}`)
        .then((res) => res.data)
        .catch((err) => console.log(err));
      this.load = false;
    },

    async loadNewsFilter() {
      this.filterActivity.sort();
      const [start = "", end = ""] = this.filterActivity;

      const category = this.filterCategory ? `/${this.filterCategory}` : "";
      const url = `/admin/news/list${category}?page=${this.counter}`;
      const urlWithFilter = `${url}&filter[date_start]=${start}&filter[date_end]=${end}`;

      this.newsList = await this.$axios
        .$get(urlWithFilter)
        .then((res) => res.data)
        .catch((err) => console.log(err));

      this.load = false;
    },

    async deleteNews(id) {
      const result = await this.$swal.fire({
        title: "Вы уверены, что хотите удалить новость?",
        showCancelButton: true,
        confirmButtonText: "Удалить",
        icon: "error",
        cancelButtonText: `Не удалять`,
        confirmButtonColor: `#ab003c`,
        denyButtonColor: `#2196f3`,
      });

      if (result.isConfirmed) {
        await this.$axios
          .post("/admin/news/remove", { id: id })
          .then((res) => res.data);

        await this.loadNews();
        this.$swal.fire("Удалено!", "", "error");
      } else if (result.isDenied) {
        this.$swal.fire("Отмена удаления", "", "info");
      }
    },

    copy(item) {
      let res = "##news_" + item.id + "##";
      this.$clipboard(res);
    },

    async filterNews() {
      this.counter = 1;
      this.load = true;
      this.$modal.hide("admin-filter-modal");
      await this.loadNewsFilter();
    },

    async clearFilter() {
      this.counter = 1;
      this.filterCategory = "";
      this.filterActivity = [];
      this.load = true;
      await this.loadNews();
    },

    async changeActivity(item, $event) {
      await this.$axios.post("admin/news/update", {
        ...item, activity: $event
      });
    },

    getContainerTitle(item) {
      return item.container_news_site ? item.container_news_site.container.name : '';
    }
  },
};
</script>

<style>
.text {
  display: block;
}
.tree-select {
  margin-bottom: 15px;
}

.publications-filter {
  padding: 20px;
}
.v-tabs-slider-wrapper {
  display: none;
}
.disable_item_list {
  opacity: 0.5;
}
.yesterday, .today, .tomorrow{
  position: relative;
}
.yesterday::before, .today::before, .tomorrow::before{
  content: " ";
  position: absolute;
  width: 10px;
  height: 100%;
  top: 0;
  left: 0;
}
.yesterday::before{
  background-color: purple;
}
.today::before{
  background-color: #4caf50;
}
.tomorrow::before{
  background-color: orange;
}
.list-editors{
  color: #999;
  margin-top: 11px;
}
</style>
