<template>
  <div class="position-relative">
    <form action="">
      <div :class="{ remov: show === true }">
        <div
          class="dropdown me-auto text__13 sortlist mb-3"
          ref="dropdownSortlist"
        >
          <button
            class="btn dropdown-toggle"
            type="button"
            data-bs-toggle="dropdown"
            aria-expanded="false"
          >
            <span style="color: #adbec4"> مرتب سازی:&nbsp;&nbsp; </span>
            <span>{{ sortTitle }}</span>
          </button>
          <div class="dropdown-menu">
            <button
              class="dropdown-item text__13"
              v-for="(item, index) in lists"
              @click.prevent="setItemDropdown(item, index)"
              :key="index"
              :class="{ Active: index === activeButtonIndex }"
            >
              {{ item.title }}
            </button>
          </div>
        </div>
        <div class="search-items">
          <div
            class="search-items__item"
            v-for="(report, index) in reports"
            :key="index"
          >
            <div
              class="search-items__header"
              @click="goToReporShowPage(report)"
            >
              <div>
                <a class="search-items__label text__13 text__dark-gray">{{
                  cangeForLabel(report._source.type_change)
                }}</a>
              </div>
              <div>
                <div class="text__14 text__dark-gray search-items__code">
                  <span style="margin-left: 10px"
                    >کاربر : {{ report._source.username + "@" }}</span
                  >
                  <span style="margin-left: 10px"
                    >تاریخ :
                    {{ convertToPersian(report._source.time_edit) }}</span
                  >
                </div>
              </div>
            </div>
            <div class="search-items__body">
              <div class="search-item__actions">
                <span class="tavasi tavasi-more-vert"></span>
                <button
                  @click="$emit(report)"
                  title="بازگرداندن"
                  class="btn show-detail-btn  px-1"
                  type="button"
                >
                  <span class="tavasi tavasi-Component-242--1"></span>
                </button>
                <button
                  @click="$emit(report)"
                  title="مقایسه"
                  class="btn show-detail-btn  px-1"
                  type="button"
                >
                  <span class="tavasi tavasi-Component-295--1"></span>
                </button>
              </div>
              <component
                :is="getNameComponent(report._source.id_key)"
                :entity="getDataComponent(report._source.data, report)"
                :entityContent="getEntityContent(report)"
              >
              </component>
            </div>
            <hr />
          </div>
        </div>

        <div class="popUp-tab__buttons d-flex justify-content-center">
          <jahat-pagination
            class="flex-wrap "
            v-if="pagination.total"
            :paginationInfo="pagination"
            @page-changed="pageChanged"
            @page-limit-changed="pageLimitChanged"
            @sort-changed="sortChanged"
          >
          </jahat-pagination>

          <span></span>
        </div>
      </div>
    </form>
  </div>
</template>

<script>

import repoApi from "~/apis/repoApi";
import { persianDateAndTime } from "";
import { mapState } from "pinia";

export default {
  props: ["entityId"],
  beforeMount() {
    this.httpService = new HttpService(import.meta.env.VITE_REPO_BASE_URL);
  },
  mounted() {
    this.getReports();
    this.show = true;

    // اضافه کردن favorite و unfavorite به lists
    this.lists = structuredClone(this.activeSchemaGetter.items);
    let favorite = "";
    let unfavorite = "";

    this.lists.forEach((item, index) => {
      if (item.key == "good_bad") {
        favorite = this.lists[1].items[0];
        unfavorite = this.lists[1].items[1];
        this.lists.push(favorite, unfavorite);
        this.lists.splice(index, 1);
      }
    });
    if (
      !this.lists.some((element) => {
        return (
          element.key === "all" &&
          element.modalName === undefined &&
          element.scrollTitle === "همه" &&
          element.title === "همه" &&
          element.type === undefined
        );
      })
    ) {
      this.lists.push({
        key: "all",
        modalName: undefined,
        scrollTitle: "همه",
        title: "همه",
        type: undefined,
      });
    }
  },
  data() {
    return {
      sortTitle: "همه",
      lists: "",
      activeButtonIndex: 13,
      executed: false,
      reports: [],
      fetchingData: false,
      httpService: undefined,
      show: false,
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0,
        limit: 10,
      },
      sorting: {
        sortby: "created",
        sortorder: undefined, // asc | desc | none
      },
      filterKey: "all",
    };
  },
  computed: {
    ...mapState(["activeSchemaGetter"]),
  },
  methods: {
    setItemDropdown(item, index) {
      this.sortTitle = item.title;
      this.filterKey = item.key;
      this.getReports();
      this.activeButtonIndex = index;
    },
    // برای تغییر نام کامپوننت
    getNameComponent(key) {
      if (!key) return "نامشخص";
      if (key == "crition") return "EntityListContent";
      else if (key == "description") return "EntityTextContent";
      else if (key == "title") return "EntityTextContent";
      else if (key == "summary") return "EntityTextContent";
      else if (key == "text") return "EntityTextContent";
      else if (key == "method") return "EntityTextContent";
      else if (key == "target") return "EntityTextContent";
      else if (key == "files") return "EntitySliderContentTwo";
      else if (key == "necessity") return "EntitySliderContent";
      else if (key == "links") return "EntitySliderContentTwo";
      else if (key == "questions") return "EntityQustionsContent";
      else if (key == "keywords") return "EntityTextContent";
      else if (key == "unfavorite") return "EntityTextContent";
      else if (key == "favorite") return "EntityTextContent";
      else if (key == "fish") return "EntityFishContent";
      else if (key == "rules") return "EntityHorizontalListContentTwo";

      return "نامعین";
    },
    // برای فرستادن داده به کامپوننت
    getDataComponent(value, item) {
      if (item._source.data == "") return item._source.data;
      if (item._source.id_key == "crition") {
        const data = JSON.parse(value);
        const newItem = {
          crition: [data],
        };
        return newItem;
      } else if (item._source.id_key == "files") {
        const data = JSON.parse(value);
        const newItem = {
          files: [data],
        };
        return newItem;
      } else if (item._source.id_key == "necessity") {
        const data = JSON.parse(value);
        const newItem = {
          necessity: [data],
        };
        return newItem;
      } else if (item._source.id_key == "links") {
        const data = JSON.parse(value);
        const newItem = {
          links: [data],
        };
        return newItem;
      } else if (item._source.id_key == "questions") {
        const data = JSON.parse(value);
        const newItem = {
          questions: [data],
        };
        return newItem;
      } else if (item._source.id_key == "keywords") {
        const data = JSON.parse(value);
        const newItem = {
          keywords: data,
        };
        return newItem;
      } else if (item._source.id_key == "rules") {
        const data = JSON.parse(value);
        const newItem = {
          rules: [data],
        };
        return newItem;
      } else {
        const newItem = {
          [item._source.id_key]: value,
        };
        return newItem;
      }
    },
    // فرستادن کانتنت برای کامپوننت
    getEntityContent(items) {
      const entityContent = {};

      this.lists.forEach((element) => {
        if (element.key === items._source.id_key) {
          entityContent.key = element.key;
          entityContent.modalName = element.modalName;
          entityContent.title = element.title;
          entityContent.type = element.type;
        }
      });

      return entityContent;
    },

    convertToPersian(date) {
      const res = persianDateAndTime(date * 1000);
      const parsedDate = `${res.year.numeric}/${res.month.numeric}/${res.day.numeric}  ساعت: ${res.hour.numeric}:${res.minute.numeric}`;
      return parsedDate;
    },
    getReports() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      let url = "";
      if (
        this.activeSchemaGetter?.key == "issues" ||
        this.activeSchemaGetter?.key == "answers" ||
        this.activeSchemaGetter?.key == "critions"
      )
        url = "log/jahat";
      else url = `public/log/${this.activeSchemaGetter?.key}`;

      url =
        url +
        `/${this.filterKey}/${this.pagination.offset}/${this.pagination.limit}/${this.entityId}`;

      this.httpService.getRequest(url).then((res) => {
        this.reports = 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;
      });
    },
    parseData(data) {
      try {
        const parsedObject = JSON.parse(data);
        return parsedObject.summary;
      } catch (err) {
        return data;
      }
    },
    closeModal() {
      // close modal.
    },

    pageLimitChanged(paging) {
      this.resetPagination();
      this.pagination.limit = paging.limit;

      this.getReports();
    },
    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.getReports();
    },
    sortChanged(sorting) {
      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;

      this.getReports();
    },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },

    changeForTitle(item) {
      try {
        return JSON.parse(item)?.title;
      } catch (err) {
        return item;
      }
    },
    cangeForLabel(item) {
      // console.log(item);
      if (item == "add") {
        return "اضافه";
      } else if (item == "edit") {
        return "ویرایش";
      } else if (item == "delete") {
        return "حذف";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.search-items {
  // height: 50vh;
  // overflow: auto;
  .search-items__item {
    position: relative;
    padding: 1em;

    &:not(:last-child) {
      margin-bottom: 30px;
    }

    &:hover,
    &.active {
      background-color: #e8fcff;

      .search-item__actions {
        width: 4.5em;
        transition: all 0.5s;

        .tavasi-more-vert {
          transition: all 0.2s;
          display: none;
        }
      }
    }
  }

  .search-item__actions {
    position: absolute;
    left: 0;
    width: 1.6em;
    top: 1em;
    overflow: hidden;
    transition: all 0.5s;
    display: flex;
    align-items: center;

    .btn {
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        filter: brightness(0.8);
      }

      .tavasi {
        color: #adbec4;
      }
    }
  }
}
.search-items__item {
  display: grid;
  grid-template-rows: 0fr 0fr;
}
.search-items__item::after {
  content: "";
  display: block;
  border-top: 1px solid #f1f1f1; /* یک خط افقی 1 پیکسلی با رنگ مشخص */
  margin: 0px auto; /* فضای بالا و پایین از خط افقی */
  width: 80%;
  position: relative;
  top: 20px;
}
</style>
<style lang="scss">
.Active {
  color: #17a2b8 !important;
}
.remov {
  .tavasi-Component-242--1 {
    display: none;
  }
  .tavasi-Component-133--1 {
    display: none;
  }
  .tavasi-Component-112--1 {
    display: none;
  }
  .problem-section {
    margin-top: 0px;
  }
}
</style>
