<template>
  <div>
    <NuxtLayout name="default" :menu="sidbarMenu">
      <div class="container-fluid">
        <div class="row">
          <div class="col-xl-6 mb-5 mb-xl-10">
            <div class="card card-flush h-xl-100">
              <div class="card-header pt-7">
                <h3 class="card-title align-items-start flex-column">
                  <span class="card-label fw-bold text-dark"
                    >جستجوهای کاربران</span
                  >

                  <span class="text-gray-400 pt-2 fw-semibold fs-6"
                    >آخرین عبارات جستجو</span
                  >
                </h3>

                <div class="dropdown" v-if="false">
                  <button
                    class="btn btn-sm btn-light dropdown-toggle"
                    type="button"
                    id="dropdownMenuButton"
                    data-bs-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                  >
                    PDF Report
                  </button>

                  <div
                    class="dropdown-menu menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-600 menu-state-bg-light-primary fw-semibold w-100px py-4"
                    data-kt-menu="true"
                  >
                    <div class="menu-item px-3">
                      <a href="#" class="menu-link px-3"> Remove </a>
                    </div>

                    <div class="menu-item px-3">
                      <a href="#" class="menu-link px-3"> Mute </a>
                    </div>

                    <div class="menu-item px-3">
                      <a href="#" class="menu-link px-3"> Settings </a>
                    </div>
                  </div>
                </div>
              </div>

              <div class="card-body pt-5">
                <div
                  id="kt_charts_widget_15_chart"
                  class="min-h-auto ps-4 pe-6 mb-3 h-300px"
                >
                  <!-- <pie
                        :dataChart="listLastSearchText"
                        style="height: 100%; position: relative"
                      ></pie> -->
                  <WordCloud
                    :key="chartRender"
                    width="100%"
                    :data="listLastSearchText"
                    gridSize="10"
                    class="h-100 position-relative"
                  ></WordCloud>
                </div>
              </div>
            </div>
          </div>

          <div class="col-xl-6 mb-5 mb-xl-10">
            <div class="card card-flush h-xl-100">
              <div class="card-header pt-7">
                <h3 class="card-title align-items-start flex-column">
                  <span class="card-label fw-bold text-dark"
                    >جستجوهای کاربران</span
                  >

                  <span class="text-gray-400 pt-2 fw-semibold fs-6"
                    >بر حسب بیشترین تکرار جستجو</span
                  >
                </h3>

                <div class="dropdown" v-if="false">
                  <button
                    class="btn btn-sm btn-light dropdown-toggle"
                    type="button"
                    id="dropdownMenuButton"
                    data-bs-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                  >
                    PDF Report
                  </button>

                  <div
                    class="dropdown-menu menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-600 menu-state-bg-light-primary fw-semibold w-100px py-4"
                    data-kt-menu="true"
                  >
                    <div class="menu-item px-3">
                      <a href="#" class="menu-link px-3"> Remove </a>
                    </div>

                    <div class="menu-item px-3">
                      <a href="#" class="menu-link px-3"> Mute </a>
                    </div>

                    <div class="menu-item px-3">
                      <a href="#" class="menu-link px-3"> Settings </a>
                    </div>
                  </div>
                </div>
              </div>

              <div class="card-body pt-5">
                <!--begin::Chart container-->
                <div
                  id="kt_charts_widget_15_chart"
                  class="min-h-auto ps-6 pe-6 mb-3 h-300px"
                  dir="ltr"
                  style="direction: ltr"
                >
                  <WordCloud
                    :key="chartRender2"
                    width="100%"
                    gridSize="10"
                    :data="listMaxSearchText"
                    class="h-100 position-relative"
                  ></WordCloud>

                  <!-- <pie-chart
                        :data="pieData"
                        class="h-100 position-relative"
                      ></pie-chart> -->
                </div>
                <!--end::Chart container-->
              </div>
            </div>
          </div>

          <div class="col-xl-6 mb-5 mb-xl-10">
            <div class="card card-flush h-xl-100">
              <div class="card-header pt-7">
                <h3 class="card-title align-items-start flex-column">
                  <span class="card-label fw-bold text-dark"
                    >مراجعات کاربران</span
                  >

                  <span class="text-gray-400 pt-2 fw-semibold fs-6"
                    >عناوین پرتکرار اسنادی که کاربران متن آن را مشاهده
                    کردند</span
                  >
                </h3>

                <div class="dropdown">
                  <button
                    class="btn btn-sm btn-light dropdown-toggle"
                    type="button"
                    id="dropdownMenuButton"
                    data-bs-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                  >
                    {{ selectedDropdownFavorite }}
                  </button>

                  <div
                    class="dropdown-menu menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-600 menu-state-bg-light-primary fw-semibold w-100px py-4"
                    data-kt-menu="true"
                  >
                    <div
                      class="menu-item px-3"
                      v-for="(item, index) in dateFilterList"
                      :key="index"
                    >
                      <button-component
                        @click="getFavoriteData(item.key)"
                        :title="item.title"
                        class="menu-link px-3"
                        :classes="{
                          active: favoriteActiveItem == item.key,
                        }"
                        :buttonText="item.title"
                      ></button-component>
                    </div>
                  </div>
                </div>
              </div>

              <div class="card-body pt-5">
                <div
                  id="kt_charts_widget_15_chart"
                  class="min-h-auto ps-4 pe-6 mb-3 h-300px"
                >
                  <!-- <pie-donut
                        :dataPie="favoriteData"
                        :PieOptions="PieOptions"
                        style="height: 100%; position: relative"
                      ></pie-donut> -->
                  <WordCloud
                    :key="favoriteRender"
                    width="100%"
                    :data="favoriteData"
                    gridSize="10"
                    class="h-100 position-relative"
                  ></WordCloud>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xl-6 mb-5 mb-xl-10">
            <div class="card card-flush h-xl-100">
              <div class="card-header pt-7">
                <h3 class="card-title align-items-start flex-column">
                  <span class="card-label fw-bold text-dark"
                    >علامت گذاری کاربران</span
                  >

                  <span class="text-gray-400 pt-2 fw-semibold fs-6"
                    >عناوین پرتکرار اسنادی که کاربران متن آن را علامتگذاری
                    کردند</span
                  >
                </h3>

                <div class="dropdown">
                  <button
                    class="btn btn-sm btn-light dropdown-toggle"
                    type="button"
                    id="dropdownMenuButton"
                    data-bs-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                  >
                    {{ selectedDropdownBookMark }}
                  </button>

                  <div
                    class="dropdown-menu menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-600 menu-state-bg-light-primary fw-semibold w-100px py-4"
                    data-kt-menu="true"
                  >
                    <div
                      class="menu-item px-3"
                      v-for="(item, index) in dateFilterList"
                      :key="index"
                    >
                      <button-component
                        @click="getBookMarkData(item.key)"
                        :title="item.title"
                        class="menu-link px-3"
                        :buttonText="item.title"
                        :classes="{
                          active: bookMarkActiveItem == item.key,
                        }"
                      ></button-component>
                    </div>
                  </div>
                </div>
              </div>

              <div class="card-body pt-5">
                <div
                  id="kt_charts_widget_15_chart"
                  class="min-h-auto ps-4 pe-6 mb-3 h-300px"
                >
                  <!-- <Bar
                        :dataChart="bookMarkData"
                        style="height: 100%; position: relative"
                      ></Bar> -->
                  <WordCloud
                    :key="bookMarkRender"
                    width="100%"
                    :data="bookMarkData"
                    gridSize="10"
                    class="h-100 position-relative"
                  ></WordCloud>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </NuxtLayout>
  </div>
</template>
<script>
import adminMenu from "~/json/admin/json/menu.json";
import { useCommonStore } from "~/stores/commonStore";
import { mapState } from "pinia";
import reportExtension from "~/extensions/reportExtension";
// import HttpService from "@services/httpService";
import adminApi from "~/apis/adminApi";

export default {
  // name: "admin",
  setup() {
    definePageMeta({
      layout: false,
      // name: "admin",
    });
  },

  extends: reportExtension,
  beforeMount() {
    this.httpService = useNuxtApp()["$http"];
  },
  beforeCreate() {
    // ApiService.init(process.env.VUE_APP_REPO_BASE_URL);
    // this.permitHttpService = new HttpService();
  },
  mounted() {
    const vm = this;
    // ,vm.getData("nokeys")
    Promise.allSettled([vm.getData("last", 20), vm.getData("count", 100)]).then(
      function (results) {
        results.forEach((result, index) => {
          if (result.status === "fulfilled" && result.value?.length)
            result.value?.forEach((element) => {
              if (index == 0) {
                let splittedTitles = element.key.split(" ");

                if (splittedTitles.length > 4) {
                  let title = "";
                  for (let i = 0; i < 4; i++)
                    title += splittedTitles[i] + (i == 3 ? "..." : " ");

                  element.key = title;
                }

                vm.listLastSearchText.push({
                  category: element.key,
                  value: element.doc_count,
                  name: element.key,
                  weight: element.doc_count,
                });
              } else if (index == 1)
                vm.listMaxSearchText.push({
                  // for list
                  category: element.key,
                  value: element.doc_count,
                  // for cload chart
                  name: element.key,
                  weight: element.doc_count,
                });
              // else if (index == 1)
              //   vm.noKeysData.push({
              //     category: element.key,
              //     value: element.doc_count,
              //   });
            });
        });

        vm.showCharts = true;
      }
    );
    setTimeout(() => {
      this.chartRender++;
      this.chartRender2++;
    }, 1000);

    this.getFavoriteData();
    this.getBookMarkData();
  },
  data() {
    return {
      selectedDropdownFavorite: "",
      selectedDropdownBookMark: "",
      PieOptions: {
        radius: ["40%", "70%"],
        selectedMode: "single",
      },
      menu: adminMenu,
      bookMarkActiveItem: "all",
      favoriteActiveItem: "all",
      favoriteRender: 0,
      bookMarkRender: 0,
      chartRender: 0,
      chartRender2: 0,
      dateFilterList: [
        {
          title: "تا یک روز ",
          key: "day",
        },
        {
          title: "تا یک هفته ",
          key: "week",
        },
        {
          title: "تا یک ماه",
          key: "month",
        },
        {
          title: "تا شش ماه",
          key: "month6",
        },
        {
          title: "تا یک سال",
          key: "year",
        },
        {
          title: "همه",
          key: "all",
        },
      ],

      lastSearchInListMode: true,
      topRepeatInListMode: true,
      systems: [],
      db: undefined,
      // permitHttpService: undefined,
      listLastSearchText: [],
      noKeysData: [],
      listMaxSearchText: [],
      bookMarkData: [],
      favoriteData: [],
      showCharts: false,
    };
  },
  computed: {
    ...mapState(useCommonStore, ["isSidebarCollapsed"]),
    sidbarMenu() {
      return adminMenu;
    },
  },
  methods: {
    getFavoriteData(timeKey = "all") {
      this.favoriteActiveItem = timeKey;
      this.selectedDropdownFavorite =
        this.dateFilterList.find((item) => item.key === timeKey)?.title ||
        "انتخاب تاریخ";

      // if (this.fetchingData) return;
      // this.fetchingData = true;
      let url = adminApi.favorite.favoriteList;
      // url = url.replace("{{@data_type}}", "favorite");
      url = url.replace("@data_type", "history");
      url = url.replace("@time_key", timeKey);
      return this.httpService
        .getRequest(url)
        .then((response) => {
          let res = response.aggregations.result.buckets;
          let chartData = [];
          res.forEach((element) => {
            let splittedTitles = element.key.split(" ");
            if (splittedTitles.length > 4) {
              let title = "";
              for (let i = 1; i < 4; i++)
                title += splittedTitles[i] + (i == 3 ? "..." : " ");
              element.key = title;
            }
            chartData.push({
              category: element.key,
              value: element.doc_count,
              name: element.key,
              weight: element.doc_count,
            });
          });
          this.favoriteData = chartData;
          this.favoriteRender++;
          // vm.fetchingData = false;
        })
        .catch((error) => {
          // vm.fetchingData = false;
          // vm.$alert(error);
        });
    },
    getBookMarkData(timeKey = "all") {
      this.bookMarkActiveItem = timeKey;
      this.selectedDropdownBookMark =
        this.dateFilterList.find((item) => item.key === timeKey)?.title ||
        "انتخاب تاریخ";
      // if (this.fetchingData) return;
      // this.fetchingData = true;
      let url = adminApi.favorite.bookmarkList;
      // url = url.replace("@data_type", "favorite");
      url = url.replace("@data_type", "bookmark");
      url = url.replace("@time_key", timeKey);
      return this.httpService
        .getRequest(url)
        .then((response) => {
          let res = response.aggregations.result.buckets;
          let chartData = [];
          res.forEach((element) => {
            chartData.push({
              category: element.key,
              value: element.doc_count,
              name: element.key,
              weight: element.doc_count,
            });
          });
          this.bookMarkData = chartData;
          this.bookMarkRender++;
          console.log("🟢 ~ .then ~ bookMarkData:", bookMarkData);
          // vm.fetchingData = false;
        })
        .catch((error) => {
          // vm.fetchingData = false;
          // vm.$alert(error);
        });
    },
  },

  components: {
    // WordCloud: () => import("@components/charts/WordCloud.vue"),
    // Pie: () => import("@components/charts/Pie.vue"),
    // PieDonut: () => import("@components/charts/PieDonut.vue"),
    // Bar: () => import("@components/charts/Bar.vue"),
  },
};
</script>

<style lang="scss" scoped>
.pages-content-container {
  overflow-y: auto;
}
.text-dark {
  color: var(--bs-text-dark) !important;
}
.pt-7 {
  padding-top: 1.75rem !important;
}
.fw-bold {
  font-weight: 600 !important;
}
.text-dark {
  color: var(--bs-text-dark) !important;
}

.fw-semibold {
  font-weight: 500 !important;
}
.fs-6 {
  font-size: 1.075rem !important;
}
.text-gray-400 {
  color: var(--bs-text-gray-400) !important;
}
.min-h-auto {
  min-height: auto !important;
}
.ps-4 {
  padding-left: 1rem !important;
}
.pe-6 {
  padding-right: 1.5rem !important;
}
.h-300px {
  // height: 300px !important;
  height: 30em !important;
}
.card {
  --bs-text-gray-400: #b5b5c3;
  --bs-body-bg: #fff;
  --bs-box-shadow: 0 0.5rem 1.5rem 0.5rem rgba(0, 0, 0, 0.075);
  --bs-menu-dropdown-box-shadow: 0px 0px 50px 0px rgba(82, 63, 105, 0.15);
  --bs-menu-dropdown-bg-color: var(--bs-body-bg);

  --bs-card-spacer-y: 1rem;
  --bs-card-spacer-x: 1rem;
  --bs-card-title-spacer-y: 0.5rem;
  --bs-card-title-color: ;
  --bs-card-subtitle-color: ;
  --bs-card-border-width: 1px;
  --bs-card-border-color: var(--bs-border-color);
  --bs-card-border-radius: 0.625rem;
  --bs-card-box-shadow: 0px 0px 20px 0px rgba(76, 87, 125, 0.02);

  --bs-card-bg: #f8f9fa;

  position: relative;
  display: flex;
  flex-direction: column;
  min-width: 0;
  height: var(--bs-card-height);
  word-wrap: break-word;
  background-color: var(--bs-card-bg);
  background-clip: border-box;
  border: var(--bs-card-border-width) solid var(--bs-card-border-color);
  border-radius: var(--bs-card-border-radius);
  box-shadow: var(--bs-card-box-shadow);
  border: 0;

  &.card-flush > .card-header {
    border-bottom: 0 !important;
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: stretch;
    flex-wrap: wrap;
    min-height: 70px;
    padding: 0 2.25rem;
    color: var(--bs-card-cap-color);
    background-color: var(--bs-card-cap-bg);
    border-bottom: 1px solid var(--bs-card-border-color);

    .card-title {
      display: flex;
      align-items: center;
      margin: 0.5rem;
      margin-left: 0;

      font-weight: 500;
      font-size: 1rem;
      color: var(--bs-text-dark);

      &.flex-column {
        align-items: flex-start;
        justify-content: center;
      }

      .card-label {
        margin: 0 0.75rem 0 0;
        flex-wrap: wrap;
        font-weight: 500;
        font-size: 1rem;
        color: var(--bs-text-dark);
      }
    }

    .card-toolbar {
      display: flex;
      align-items: center;
      margin: 0.5rem 0;
      flex-wrap: wrap;
    }
  }

  .card-body {
    padding: 2rem 2.25rem;
    color: var(--bs-card-color);
    flex: 1 1 auto;
    padding: var(--bs-card-spacer-y) var(--bs-card-spacer-x);
    color: var(--bs-card-color);
  }
}

.menu-sub-dropdown {
  border-radius: 0.475rem;
  background-color: var(--bs-menu-dropdown-bg-color);
  box-shadow: var(--bs-menu-dropdown-box-shadow);
  z-index: 107;
  text-align: right;

  .menu-item {
    .menu-link {
      &.active,
      &:hover {
        background-color: var(--primary-color);
      }
    }
  }
}
.card-flush {
  box-shadow: 0 0.4688rem 2.1875rem rgba(4, 9, 20, 0.03),
    0 0.9375rem 1.4063rem rgba(4, 9, 20, 0.03),
    0 0.25rem 0.5313rem rgba(4, 9, 20, 0.03),
    0 0.125rem 0.1875rem rgba(4, 9, 20, 0.03);
}
.dropdown-toggle {
  border: 1px solid var(--primary-color);
}
</style>
../../apis/adminApi
