import { mapActions, mapState } from "pinia";
import { useCommonStore } from "~/stores/commonStore";
import { useAuthStore } from "~/stores/authStore";
import adminApi from "~/apis/adminApi";

export default {
  data() {
    return {
      activeTab: "all",

      canView: false,
      fetchingData: false,
      listUnseen: [],
      countUnseen: undefined,
      list: [],
      counts: "",
      notificationItem: undefined,
      buttonLoading: false,
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0,
        limit: 5,
      },
    };
  },
  computed: {
    ...mapState(useAuthStore, ["currentUser", "isGuest"]),
  },

  methods: {
    ...mapActions(useCommonStore, ["checkPermissions"]),
    filterNotifications(newTab) {
      this.activeTab = newTab;
      this.list = [];
      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");

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          method: "POST",
          baseURL: repoUrl(),
        });
        this.mySwalToast({
          title: "تبریک",
          html: res.message,
          icon: "success",
        });
        return res;
      } catch (err) {
        this.fetchingData = false;
      }

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

    // Getting notification item.
    async 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;
      //   });

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          method: "get",
          baseURL: repoUrl(),
        });
        this.notificationItem = res;
      } catch (err) {
        this.fetchingData = false;
      }
    },
    // admin
    async getList() {
      let url = adminApi.notification[this.activeTab];
      url = url.replace("{{offset}}", this.pagination.offset);
      url = url.replace("{{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;
      //   });

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          method: "get",
          baseURL: repoUrl(),
        });
        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 (err) {
        this.fetchingData = false;
      }
    },
    //user
    async 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;
      //   });

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          method: "get",
          baseURL: repoUrl(),
        });
        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 };
        this.fetchingData = false;
      } catch (err) {
        this.fetchingData = false;
      }
    },
    // user
    async getCountUnseen() {
      const url = adminApi.notification.countUnseen;

      // this.httpService
      //   .getRequest(url)
      //   .then((res) => {
      //     this.countUnseen = res.count;
      //   })
      //   .catch(() => {})
      //   .finally(() => {});

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          method: "get",
          baseURL: repoUrl(),
        });

        this.countUnseen = res.data.count;
      } catch (err) {}
    },
    goToNotificationShowPage(item) {
      this.$router.push({
        name: "notificationsShow",
        params: {
          id: item._id,
        },
      });
    },
    goToNotificationPage() {
      this.$router.push({
        name: "notifications",
      });
    },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },
    pageLimitChanged(paging) {
      this.resetPagination();
      this.pagination.limit = paging.limit;

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

      this.getList();
    },
    sortChanged(sorting) {
      // keep limit status.
      // reset page and offset values.

      this.pagination.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 res = await $api(url, {
          method: "get",
          baseURL: repoUrl(),
        });
        this.getList();
        this.mySwalToast({
          html: res?.message ?? "با موفقیت تغییر یافت.",
        });
        this.numberOfMark();
      } 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 res = await $api(url, {
          method: "get",
          baseURL: repoUrl(),
        });
        this.counts = res.data;
      } catch (err) {}
    },
  },
};
