<template>
  <div>
    <NuxtLayout name="default" :menu="sidbarMenu">
      <div class="container-fluid">
        <div class="row">
          <div class="col-12">
            <div v-if="canView">
              <div class="user__container">
                <div class="d-flex justify-content-between align-items-center">
                  <div>
                    <h3>
                      {{ $t("Notifications") }}
                    </h3>
                    <p class="text__light text__13">
                      شما {{ list?.length }} اعلان خوانده نشده دارید.
                    </p>
                  </div>
                  <div>
                    <button-component
                      @click="markAll()"
                      buttonText="همه را خواندم"
                      v-tooltip="'همه را خواندم'"
                      classes="btn btn-primary"
                    >
                    </button-component>
                  </div>
                </div>
                <ul class="nav nav-tabs">
                  <li class="nav-item">
                    <button
                      title="همه"
                      type="button"
                      @click.prevent="filterNotifications('all')"
                      class="btn nav-link"
                      :class="{
                        active: activeTab == 'all',
                      }"
                    >
                      <span class="badge badge-light">{{
                        counts?.data?.all?.count
                      }}</span>
                      همه
                    </button>
                  </li>
                  <li class="nav-item">
                    <button
                      title="جدید"
                      type="button"
                      @click.prevent="filterNotifications('new')"
                      class="btn nav-link"
                      :class="{
                        active: activeTab == 'new',
                      }"
                    >
                      <span class="badge badge-light">{{
                        counts?.data?.new?.count
                      }}</span>

                      جدید
                    </button>
                  </li>
                  <li class="nav-item">
                    <button
                      title="خوانده نشده ها"
                      type="button"
                      @click.prevent="filterNotifications('unseen')"
                      class="btn nav-link"
                      :class="{
                        active: activeTab == 'unseen',
                      }"
                    >
                      <span class="badge badge-light">{{
                        counts?.data?.unseen?.count
                      }}</span>

                      خوانده نشده ها
                    </button>
                  </li>

                  <li class="nav-item">
                    <button
                      title="خوانده شده ها"
                      type="button"
                      @click.prevent="filterNotifications('seen')"
                      class="btn nav-link"
                      :class="{
                        active: activeTab == 'seen',
                      }"
                    >
                      <span class="badge badge-light">{{
                        counts?.data?.seen?.count
                      }}</span>

                      خوانده شده ها
                    </button>
                  </li>
                </ul>

                <the-content-loading
                  class="absolute-positioning"
                  v-if="fetchingData"
                ></the-content-loading>

                <div v-else>
                  <div v-if="list && list.length">
                    <div class="notif-list firefox-scrollbar">
                      <notification-item
                        v-for="(item, index) in list"
                        :item="item"
                        :index="index"
                        :key="item._id"
                        @getList="getList"
                        @go-to-notification-show-page="
                          goToNotificationShowPage(item)
                        "
                      ></notification-item>
                    </div>
                    <jahat-pagination
                      v-if="pagination.total"
                      :paginationInfo="pagination"
                      @page-changed="pageChanged"
                      @page-limit-changed="pageLimitChanged"
                      @sort-changed="sortChanged"
                    >
                    </jahat-pagination>
                  </div>
                  <no-data v-else></no-data>
                </div>
              </div>
            </div>
            <no-data v-else>
              <the-content-loading v-if="fetchingData"></the-content-loading>

              <div
                v-else
                class="d-flex justify-content-center align-items-center"
              >
                <div
                  class="alert alert-warning d-flex justify-content-center align-items-center"
                >
                  <span
                    class="tavasi tavasi-warning-circle color-inherit ms-1 text__32"
                  ></span>
                  عدم دسترسی
                </div>
              </div>
            </no-data>
          </div>
        </div>
      </div>
    </NuxtLayout>
  </div>
</template>

<script lang="ts">
// import notificationMixin from "~/composables/notifications/notificationMixin";
import { mapActions, mapState } from "pinia";
import { useAuthStore } from "~/stores/authStore";
import { useCommonStore } from "~/stores/commonStore";
import type { Pagination } from "~/types/commonTypes";
import apis from "~/apis/adminApi";
import type { counts, listNotification } from "~/types/notificationTypes";

import monirMenu from "~/json/dashboard/monir/menu.json";
import majlesMenu from "~/json/dashboard/majles/menuDefault.json";

export default {

  setup() {
    definePageMeta({
      layout: false,
      // layout: "dashboard-layout",
    });
  },

  data() {
    return {
      // httpService: undefined,
      activeTab: "all",

      canView: false,
      fetchingData: false,
      listUnseen: [],
      countUnseen: undefined,
      list: [] as listNotification[],
      counts: {} as counts,
      notificationItem: undefined,
      buttonLoading: false,
      pagination: {
        total: 0,
        pages: 0,
        page: 1,
        offset: 0,
        limit: 10,
      } as Pagination,
      sorting: {},
    };
  },
  mounted() {
    if (this.isRealUser) {
      this.canView = true;
      this.getList();
      this.numberOfMark();
    }
    // else this.canView = false;
    // this.checkPermisionBeforGetList("notifications_users").then(() => {
    //   this.getList();
    // });
  },
  computed: {
    ...mapState(useAuthStore, ["isRealUser"]),

    sidbarMenu() {
      if (isMajlesBuild()) return majlesMenu;
      else return monirMenu;
    },
  },
  methods: {
    ...mapActions(useCommonStore, ["checkPermissions"]),
    filterNotifications(newTab: string) {
      this.activeTab = newTab;

      this.getList();
    },
    // async checkPermisionBeforGetList(permission) {
    //   if (this.fetchingData) return;
    //   this.fetchingData = true;

    //   return await this.checkPermissions({ permission, _this: this })
    //     .then(() => {
    //       this.canView = true;
    //       // this.fetchingData = false;
    //     })
    //     .catch(() => {
    //       this.canView = false;
    //       this.fetchingData = false;
    //     });
    // },

    // detelte item.
    // async deleteItem({ _id }) {
    //   if (this.buttonLoading) return;
    //   this.buttonLoading = true;

    //   var url = adminApi.notification.delete;
    //   url = url.replace("{{id}}", _id);
    //   url = url.replace("{{entity_type}}", "notif");

    //   return await this.httpService
    //     .postRequest(url)
    //     .then((res) => {
    //       this.mySwalToast({
    //         title: "تبریک",
    //         html: res.message,
    //         icon: "success",
    //       });
    //     })
    //     .catch((error) => {})
    //     .finally(() => {
    //       this.buttonLoading = false;
    //     });

    //     try {

    //   const { $api } = useNuxtApp();
    //   const data: resModelThree = await $api(apis.captcha, {
    //     baseURL: import.meta.env.VITE_AUTH_BASE_URL,
    //     method: "GET",
    //   });
    // } catch (err) {
    //
    // }
    // },

    // Getting notification item.
    // getNotificationItem(id) {
    //   let url = adminApi.notification.get;
    //   url = url.replace("{{id}}", id);

    //   this.httpService
    //     .getRequest(url)
    //     .then((res) => {
    //       this.notificationItem = res;
    //     })
    //     .catch(() => {})
    //     .finally(() => {
    //       this.fetchingData = false;
    //     });
    // },
    // admin
    async getList() {
      // console.log("Offset:", this.pagination.offset);
      // console.log("Limit:", this.pagination.limit);
      // this.httpService
      //   .getRequest(url)
      //   .then((res) => {
      //     this.list = res.hits.hits;
      //     this.numberOfMark();
      //     const total = res.hits.total.value;
      //     const pages = Math.ceil(total / this.pagination.limit);
      //     const pagination = {
      //       total: total,
      //       pages: pages == 0 ? 1 : pages,
      //     };

      //     this.pagination = { ...this.pagination, ...pagination };
      //   })
      //   .catch(() => {})
      //   .finally(() => {
      //     this.fetchingData = false;
      //   });
      let url =
        apis.notification[this.activeTab as keyof typeof apis.notification];
      let offset: number = this.pagination.offset;
      let limit: number = this.pagination.limit;
      url = url.replace("{{offset}}", offset as unknown as string);
      url = url.replace("{{limit}}", limit as unknown as string);

      try {
        const { $api } = useNuxtApp();
        const data: resModelThree = await $api(url, {
          baseURL: repoUrl(),
          method: "GET",
        });

        this.list = data.hits.hits;
      } catch (err) {}
    },
    //user
    // getListUnseen() {
    //   let url = adminApi.notification.listUnseen;

    //   url = url.replace("{{offset}}", this.pagination.offset);
    //   url = url.replace("{{limit}}", this.pagination.limit);

    //   this.httpService
    //     .getRequest(url)
    //     .then((res) => {
    //       this.listUnseen = res.hits.hits;

    //       const total = res.hits.total.value;
    //       const pages = Math.ceil(total / this.pagination.limit);
    //       const pagination = {
    //         total: total,
    //         pages: pages == 0 ? 1 : pages,
    //       };

    //       this.pagination = { ...this.pagination, ...pagination };
    //     })
    //     .catch(() => {})
    //     .finally(() => {
    //       this.fetchingData = false;
    //     });
    // },
    // user
    // getCountUnseen() {
    //   const url = adminApi.notification.countUnseen;

    //   this.httpService
    //     .getRequest(url)
    //     .then((res) => {
    //       this.countUnseen = res.count;
    //     })
    //     .catch(() => {})
    //     .finally(() => {});
    // },
    goToNotificationShowPage(item: object) {
      this.$router.push({
        name: "notificationsShow",
        params: {
          // id: item._id,
          id: (item as { _id: string })._id,
        },
      });
    },
    // goToNotificationPage() {
    //   this.$router.push({
    //     name: "notifications",
    //   });
    // },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },
    pageLimitChanged(paging: object) {
      this.resetPagination();
      let limit: number = this.pagination.limit;
      limit = (paging as { limit: number }).limit;

      this.getList();
    },
    pageChanged(paging: object) {
      let page = (paging as { pageNumber: number }).pageNumber;
      page -= 1;
      let offset: number = this.pagination.offset;
      let limit: number = this.pagination.limit;
      offset = page * (paging as { limit: number }).limit;
      limit = (paging as { limit: number }).limit;

      page = (paging as { pageNumber: number }).pageNumber;

      this.getList();
    },
    sortChanged(sorting: object, paging: object) {
      // keep limit status.
      // reset page and offset values.
      let page = (paging as { pageNumber: number }).pageNumber;

      page = this.pagination.offset = 0;
      this.sorting = sorting;

      this.getList();
    },
    // timeSince(timeStamp) {
    //   var date = new Date(timeStamp * 1000);
    //   var seconds = Math.floor((new Date() - date) / 1000);
    //   var interval = seconds / 31536000;
    //   if (interval > 1) {
    //     return Math.floor(interval) + " سال";
    //   }
    //   interval = seconds / 2592000;
    //   if (interval > 1) {
    //     return Math.floor(interval) + " ماه";
    //   }
    //   interval = seconds / 86400;
    //   if (interval > 1) {
    //     return Math.floor(interval) + " روز";
    //   }
    //   interval = seconds / 3600;
    //   if (interval > 1) {
    //     return Math.floor(interval) + " ساعت";
    //   }
    //   interval = seconds / 60;
    //   if (interval > 1) {
    //     return Math.floor(interval) + " دقیقه";
    //   }
    //   return Math.floor(seconds) + " ثانیه";
    // },
    async markAll() {
      // let url = adminApi.notification.markAllAsRead;

      // this.httpService
      //   .postRequest(url)
      //   .then((res) => {
      //     this.getList();
      //     this.mySwalToast({
      //       html: res?.message ?? "با موفقیت تغییر یافت.",
      //     });
      //     this.numberOfMark();
      //   })
      //   .catch(() => {})
      //   .finally(() => {});

      try {
        const { $api } = useNuxtApp();
        const data: resModelThree = await $api(
          apis.notification.markAllAsRead,
          {
            baseURL: repoUrl(),
            method: "POST",
          }
        );
      } catch (err) {}
    },
    async numberOfMark() {
      // let url = adminApi.notification.counts;
      // url = url.replace("{{data_type}}", this.data_type);

      // this.httpService
      //   .getRequest(url)
      //   .then((res) => {
      //     this.counts = res.data;
      //   })
      //   .catch(() => {})
      //   .finally(() => {});
      try {
        const { $api } = useNuxtApp();
        const data: counts = await $api(apis.notification.counts, {
          baseURL: repoUrl(),
          method: "GET",
        });

        this.counts = data;
      } catch (err) {}
    },
  },
};
</script>