<template>
  <div class="position-relative">
    <form class="" 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 pageSchemaItems"
              @click.prevent="setItemDropdown(item, index)"
              :key="index"
              :class="{ Active: index === activeButtonIndex }"
            >
              {{ item.title }}
            </button>
          </div>
        </div>
        <div class="search-items mb-2">
          <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('undo_report', report)"
                  title="بازگرداندن"
                  class="btn show-detail-btn px-1"
                  type="button"
                  style="font-size: 0.6rem; color: #adbec4"
                >
                  <svg class="icon icon-reset-form">
                    <use xlink:href="#icon-reset-form"></use>
                  </svg>
                </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="getContentComponent(report._source.id_key)"
                :entity="getDataComponent(report._source.data, report)"
                :entityContent="getEntityContent(report)"
                :dataItems="getDataItems(report._source.data)"
                :tableColumns="getTableColumns(report._source.id_key)"
                :showPagination="false"
                :enableDelete="false"
                :showAddBtn="false"
                :enableComments="false"
              >
              </component>
            </div>
            <hr />
          </div>
        </div>

        <div class="popUp-tab__buttons d-flex justify-content-center pt-0">
          <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 { persianDateAndTime } from "@manuals/utilities";
import { mapState } from "pinia";
import { useEntityStore } from "@search/stores/entityStore";

export default {
  props: ["entityId", "schemaItems"],
  mounted() {
    this.getReports();
    this.show = true;

    // اضافه کردن favorite و unfavorite به pageSchemaItems
    if (!this.pageSchemaItems)
      this.pageSchemaItems = structuredClone(
        this.activeEntityViewSchemaGetter.items
      );

    let favorite = "";
    let unfavorite = "";

    this.pageSchemaItems?.forEach((item, index) => {
      if (item.key == "good_bad") {
        favorite = this.pageSchemaItems[1].items[0];
        unfavorite = this.pageSchemaItems[1].items[1];
        this.pageSchemaItems.push(favorite, unfavorite);
        this.pageSchemaItems.splice(index, 1);
      }
    });
    if (
      !this.pageSchemaItems?.some((element) => {
        return (
          element.key === "all" &&
          element.modalName === undefined &&
          element.scrollTitle === "همه" &&
          element.title === "همه" &&
          element.type === undefined
        );
      })
    ) {
      this.pageSchemaItems?.push({
        key: "all",
        modalName: undefined,
        scrollTitle: "همه",
        title: "همه",
        type: undefined,
      });
    }
  },
  data() {
    return {
      sortTitle: "همه",
      activeButtonIndex: 13,
      executed: false,
      reports: [],
      pageSchemaItems: this.schemaItems,
      fetchingData: false,
      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(useEntityStore, [
      "entityViewSchemaGetter",
      "activeEntityViewSchemaGetter",
      "activeTabGetter",
    ]),
  },
  methods: {
    setItemDropdown(item, index) {
      this.sortTitle = item.title;
      this.filterKey = item.key;
      this.getReports();
      this.activeButtonIndex = index;
    },
    // برای تغییر نام کامپوننت
    getContentComponent(key) {
      if (!key) return "نامشخص";

      let schema = this.pageSchemaItems?.find((item) => item.key == key);
      if (schema) return schema.type;

      return "EntityTextContent";
    },

    getDataItems(value) {
      // let entityContent = this.pageSchemaItems.find((item) => item.key == key);
      // if (!entityContent) return undefined;

      const data = JSON.parse(value);
      return data;
    },
    getTableColumns(key) {
      let cols = [];
      if (key == "rules_logics") {
        cols = [
          { key: "rules-id", title: "شناسه حکم", width: "2" },
          { key: "text", title: "متن", width: "8" },
          { key: "main_type", title: "نوع", width: "2" },
        ];
      }
      if (key == "rules_logics_triples") {
        cols = [
          { key: "rules-id", title: "شناسه حکم", width: "2" },
          { key: "rules_logics-id", title: "شناسه گزاره", width: "2" },
          { key: "text", title: "متن", width: "8" },
        ];
      }
      return cols;
    },

    // برای فرستادن داده به کامپوننت
    getDataComponent(value, item) {
      if (item._source.data == "") return item._source.data;

      {
        const data = JSON.parse(value);
        let key = item._source.id_key;
        const newItem = {
          key: [data],
        };
        return newItem;
      }

      // else {
      //   const newItem = {
      //     [item._source.id_key]: value,
      //   };
      //   return newItem;
      // }
    },

    // فرستادن کانتنت برای کامپوننت
    getEntityContent(items) {
      let entityContent = {};

      this.pageSchemaItems?.forEach((element) => {
        if (element.key === items._source.id_key) {
          entityContent = element;
        }
      });

      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;
    },
    async getReports() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      let url = `public/log/${this.activeEntityViewSchemaGetter?.key}`;

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

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

        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;
      } catch (err) {
        return "";
      }
    },
    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: calc(100vh - 37.5em) !important;
  overflow-x: hidden;
  // 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>
