<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-auto" style="background-color: #eee">
        <div class="nav flex-column py-3" id="nav-tab" role="tablist">
          <a
            @click="setTab(1)"
            class="nav-item nav-link"
            :class="{ active: currentTab == 1 }"
            id="nav-myAccount-tab"
            data-bs-toggle="tab"
            href="#nav-myAccount"
            role="tab"
            aria-controls="nav-myAccount"
            aria-selected="true"
            >تک کلمه ای</a
          >
          <a
            @click="setTab(2)"
            class="nav-item nav-link"
            :class="{ active: currentTab == 2 }"
            id="nav-changepass-tab"
            data-bs-toggle="tab"
            href="#nav-changepass"
            role="tab"
            aria-controls="nav-changepass"
            aria-selected="false"
            >دو کلمه ای</a
          >
          <a
            @click="setTab(3)"
            class="nav-item nav-link"
            :class="{ active: currentTab == 3 }"
            id="nav-changepass-tab"
            data-bs-toggle="tab"
            href="#nav-changepass"
            role="tab"
            aria-controls="nav-changepass"
            aria-selected="false"
            >سه کلمه ای</a
          >
          <a
            @click="setTab(4)"
            class="nav-item nav-link"
            :class="{ active: currentTab == 4 }"
            id="nav-changepass-tab"
            data-bs-toggle="tab"
            href="#nav-changepass"
            role="tab"
            aria-controls="nav-changepass"
            aria-selected="false"
            >کلمات کم وزن</a
          >
          <a
            @click="setTab(5)"
            class="nav-item nav-link"
            :class="{ active: currentTab == 5 }"
            id="nav-changepass-tab"
            data-bs-toggle="tab"
            href="#nav-changepass"
            role="tab"
            aria-controls="nav-changepass"
            aria-selected="false"
            >افزودن موضوع</a
          >
        </div>
      </div>

      <div class="col">
        <div class="container-fluid">
          <div class="row" v-if="currentTab < 4">
            <div class="col-auto ms-3">
              <h6 class="mb-4">تعداد تکرار</h6>

              <div
                v-if="currentTab == 1"
                @scroll="loadMore1($event)"
                class="overlay-plugin firefox-scrollbar"
                id="overlay-plugin2"
              >
                <ul class="list-group list-group-flush-action" id="stop-words">
                  <li
                    v-for="(key, index) of oneWordArray1"
                    :class="{
                      m1: currentTab == 1,
                    }"
                    :key="index"
                    :ref="'index' + index"
                    class="list-group-item d-flex justify-content-between align-items-center p-0 px-2"
                    :id="'id-' + index"
                  >
                    <div class="context-menu">
                      <context-menu
                        class="width-auto"
                        :parentComponent="'subject-modal'"
                        :contextMenu="stopWordContextMenu"
                        @remove-item="removeItem(key[0], index)"
                        @import="removeInStopWords(key[0])"
                      >
                      </context-menu>
                    </div>
                    <button
                      class="btn btn-block text-end pe-0 repeat-btn"
                      type="button"
                      :class="{ change: validationText }"
                    >
                      <span>{{ key[0] }}</span>
                      <span class="badge badge-pill"> ( {{ key[1] }} ) </span>
                    </button>

                    <span class="d-flex align-items-center">
                      <span
                        v-if="index == 0"
                        class="tavasi tavasi-arrow-down"
                      ></span>
                    </span>
                  </li>
                </ul>
              </div>

              <div
                v-if="currentTab == 2"
                @scroll="loadMore2($event)"
                class="overlay-plugin firefox-scrollbar"
                id="overlay-plugin2"
              >
                <ul class="list-group list-group-flush-action" id="stop-words">
                  <li
                    v-for="(key, index) of oneWordArray2"
                    :class="{
                      m2: currentTab == 2,
                    }"
                    :key="index"
                    :ref="'index' + index"
                    class="list-group-item d-flex justify-content-between align-items-center p-0 px-2"
                    :id="'id-' + index"
                  >
                    <div class="context-menu">
                      <context-menu
                        class="width-auto"
                        :parentComponent="'subject-modal'"
                        :contextMenu="stopWordContextMenu"
                        @remove-item="removeItem(key[0], index)"
                        @import="removeInStopWords(key[0])"
                      >
                      </context-menu>
                    </div>
                    <button
                      class="btn btn-block text-end pe-0 repeat-btn"
                      type="button"
                      :class="{ change: validationText }"
                    >
                      <span>{{ key[0] }}</span>
                      <span class="badge badge-pill"> ( {{ key[1] }} ) </span>
                    </button>

                    <span class="d-flex align-items-center">
                      <span
                        v-if="index == 0"
                        class="tavasi tavasi-arrow-down"
                      ></span>
                    </span>
                  </li>
                </ul>
              </div>

              <div
                @scroll="loadMore3($event)"
                v-if="currentTab == 3"
                class="overlay-plugin firefox-scrollbar"
                id="overlay-plugin2"
              >
                <ul class="list-group list-group-flush-action" id="stop-words">
                  <li
                    v-for="(key, index) of oneWordArray3"
                    :class="{
                      m3: currentTab == 3,
                    }"
                    :key="index"
                    :ref="'index' + index"
                    class="list-group-item d-flex justify-content-between align-items-center p-0 px-2"
                    :id="'id-' + index"
                  >
                    <div class="context-menu">
                      <context-menu
                        class="width-auto"
                        :parentComponent="'subject-modal'"
                        :contextMenu="stopWordContextMenu"
                        @remove-item="removeItem(key[0], index)"
                        @import="removeInStopWords(key[0])"
                      >
                      </context-menu>
                    </div>
                    <button
                      class="btn btn-block text-end pe-0 repeat-btn"
                      type="button"
                      :class="{ change: validationText }"
                    >
                      <span>{{ key[0] }}</span>
                      <span class="badge badge-pill"> ( {{ key[1] }} ) </span>
                    </button>

                    <span class="d-flex align-items-center">
                      <span
                        v-if="index == 0"
                        class="tavasi tavasi-arrow-down"
                      ></span>
                    </span>
                  </li>
                </ul>
              </div>
            </div>

            <div class="col">
              <h6 class="mb-4">انتخاب عنوان با استفاده از موضوعات پیشنهادی</h6>
              <search-accordion></search-accordion>
            </div>
          </div>

          <div class="row" v-if="currentTab == 5">
            <div class="col">
              <!-- <div class="selected_word_subject">
                <select class="text__14 form-control">
                  <option
                    class="select_word"
                    v-for="(selectedWord, index) of selectedWords"
                    :key="index"
                  >
                    {{ selectedWord }}
                  </option>
                </select>
              </div> -->
              <!-- <div class="subject"> -->
              <subject-form
                @update-list="updateList"
                @delete-item="deleteItem"
              ></subject-form>
              <!-- </div> -->
            </div>
          </div>

          <div class="row" v-if="currentTab == 4">
            <div class="col">
              <div
                class="overlay-plugin firefox-scrollbar"
                id="overlay-plugin1"
              >
                <form>
                  <div class="form-group">
                    <textarea
                      class="form-control textarea-form"
                      v-model="stopWords"
                      id="stop-words"
                      rows="10"
                    ></textarea>
                  </div>

                  <!-- <button-component
                          type="submit"
                          classes="btn-primary"
                          :buttonText="saveButtonText"
                        >
                        </button-component> -->

                  <!-- <P>{{ stopWords }}</P> -->
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="row mt-3">
      <div class="col text-start" v-if="currentTab < 4">
        <button-component
          classes="btn"
          @click="closeModal()"
          buttonText="انصراف"
          :buttonLoading="buttonLoading"
          id="button-component"
        ></button-component>

        <button-component
          classes="btn btn-primary me-2"
          @click="savedata()"
          buttonText="بازسازی"
          :buttonLoading="buttonLoading"
          id="button-component"
        ></button-component>

        <!-- <button type="button" class="" @click="savedata()">بازسازی</button> -->
      </div>
      <div class="col text-start" v-if="currentTab == 4">
        <button-component
          classes="btn btn-default popUp-tab__clear button_giveup"
          @click="ReturnToInitialSettings()"
          buttonText="تنظیم به پیشفرض"
          :buttonLoading="buttonLoading"
          data-dismiss="modal"
          id="button-component"
        ></button-component>
        <button type="button" class="btn btn-primary" @click="save()">
          ذخیره
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { repetitionWordsMixin } from "~/search/mixins/repetitionWordsMixin.js";

import apis from "~/apis/searchApi";
import adminApi from "~/apis/adminApi";
import settingsApi from "~/apis/settingsApi.js";
import { mapState, mapActions } from "pinia";
import stopWordContextMenu from "~/json/search/stopWordContextMenu.json";

export default {
  mixins: [repetitionWordsMixin],
  props: ["selectedItem"],
  emits: ["update-list", "close-modal", "delete-item"],

  mounted() {
    this.httpService = new HttpService(import.meta.env.VITE_REPO_BASE_URL);
    this.entity = this.selectedItem;
    // console.log(this.selectedItem);
    this.getWordsWeight();
    //this.getStopWordsData();
  },
  data() {
    return {
      counter: 0,
      number: 5,
      ret: [],
      buttonLoading: false,
      showButton: true,
      currentTab: 1,
      currentPage: 1,
      fetchingData: false,
      stopWords: "",
      words1: [],
      words2: [],
      words3: [],
      stopWordContextMenu: stopWordContextMenu,
      buttonLoading: false,
      fetchingData: false,
      validationText: false,
      busy: false,
      startIndex: "",
      showtext: true,
      endIndex: "",
      selectedWords: ["اقتصاد", "فرهنگ", "فرهنگی"],
      repeats: [
        {
          id: 1,
          title: "اقتصاد",
          count: 4,
        },
        {
          id: 2,
          title: "اقتصاد 2",
          count: 2,
        },
        {
          id: 3,
          title: "اقتصاد 3",
          count: 10,
        },
        {
          id: 4,
          title: "اقتصاد 4",
          count: 8,
        },
        {
          id: 5,
          title: "اقتصاد 5",
          count: 0,
        },
      ],
      limit: 50,
      indexWord: [0, 0, 0],
      lenWords: [0, 0, 0],
      oneWordArray1: [],
      oneWordArray2: [],
      oneWordArray3: [],
      busy: false,
      httpService: undefined,
      entity: undefined,
    };
  },
  computed: {
    ...mapState("entity", ["selectedItemEntityGetter", "listEntityGetter"]),
    ...mapState(["currentUser", "activeSchemaGetter"]),
    buttonText() {
      return this.selectedItem?.id || this.selectedItem?.guid
        ? "بروزرسانی"
        : "ثبت";
    },
  },
  watch: {
    selectedItemEntityGetter(newVal) {
      this.entity = newVal;
      this.selectedItem = newVal;
      this.getWordsWeight();
      //this.getStopWordsData();
    },
    stopWords(newQuestion, oldQuestion) {
      if (newQuestion.includes("?")) {
        this.getWordsWeight();
      }
    },
  },
  methods: {
    ...mapActions("entity", ["SET_REPEATED_WORDS"]),
    mehdiTest() {},
    // new
    getPosts(ngram, wordsList) {
      let index = ngram - 1;
      if (this.indexWord[index] >= wordsList.length) return [];
      let count =
        this.indexWord[index] + this.limit >= wordsList.length
          ? wordsList.length - this.indexWord[index]
          : this.limit;
      let slicedArrray = wordsList.slice(
        this.indexWord[index],
        this.indexWord[index] + count
      );
      this.indexWord[index] += count;
      this.busy = false;
      return slicedArrray;
    },

    loadMore(index, $event) {
      // const listElm = document.querySelector("#overlay-plugin2");
      const listElm = $event.target;
      const vm = this;
      if (vm.busy) return;

      if (
        Math.ceil(listElm.scrollTop) + listElm.clientHeight >=
        listElm.scrollHeight
      ) {
        this.busy = true;

        if (this.lenWords[index] > this.indexWord[index]) {
          setTimeout(() => {
            if (index == 1)
              this.oneWordArray1 = [
                ...this.oneWordArray1,
                ...this.getPosts(index, this.words1),
              ];
            else if (index == 2)
              this.oneWordArray2 = [
                ...this.oneWordArray2,
                ...this.getPosts(index, this.words2),
              ];
            else if (index == 3)
              this.oneWordArray3 = [
                ...this.oneWordArray3,
                ...this.getPosts(index, this.words3),
              ];
          }, 1000);
        } else {
          vm.mySwalToast({
            title: "کاربر محترم",

            html: "دیگر رکوردی جهت بارگزاری وجود ندارد.",
            icon: "info",
            position: "bottom-start",
          });
          vm.busy = false;
        }
      } else vm.busy = false;
    },

    // new
    setListWords() {
      let words = structuredClone(this.repeats);
      this.words1 = Object.entries(words.word1);
      this.words2 = Object.entries(words.word2);
      this.words3 = Object.entries(words.word3);

      this.indexWord = [0, 0, 0];
      this.lenWords = [
        this.words1.length,
        this.words2.length,
        this.words3.length,
      ];
      this.oneWordArray1 = this.getPosts(1, this.words1);
      this.oneWordArray2 = this.getPosts(2, this.words2);
      this.oneWordArray3 = this.getPosts(3, this.words3);

      this.counter++;
    },
    removeInStopWords(key) {
      var vm = this;
      this.fetchingData = true;
      let url = settingsApi.user.remove_stopword;
      url += this.currentUser.user_id + "/" + key;
      this.httpService
        .postRequest(url)
        .then((response) => {})
        .catch((error) => {})
        .finally(() => {
          vm.fetchingData = false;
          this.removactiveCurrent();
        });
    },
    removeItem(key, index) {
      this.appendStopWords(key);
      this.activeCurrent("id-" + index);
    },
    appendStopWords(key) {
      var vm = this;
      this.fetchingData = true;
      let url = settingsApi.user.append_stopword;
      url += this.currentUser.user_id + "/" + key;

      // this.httpService.post('setting/stop_words/append/'+this.currentUser.user_id+'/'+text)
      this.httpService
        .postRequest(url)
        .then((response) => {
          // if (response.hits.hits.length) {
          //   this.stopWords = response.hits.hits[0]._source.value;
          //   this.data = response.hits.hits[0]._source;
          // } else {
          this.getAdminData();
          // }
        })
        .catch((error) => {})
        .finally(() => {
          vm.fetchingData = false;
          // this.save();
        });
    },
    activeCurrent(tagId) {
      if ((this.currentTab = 1)) {
        const listGroupItem = document.getElementsByClassName("m1");
        listGroupItem.forEach((item) => {
          item.classList.remove("active");
        });
        const target = document.getElementById(tagId);
        target.classList.add("change-active");
      } else if ((this.currentTab = 2)) {
        const listGroupItem = document.getElementsByClassName("m2");
        listGroupItem.forEach((item) => {
          item.classList.remove("active");
        });
        const target = document.getElementById(tagId);
        target.classList.add("change-active");
      } else if ((this.currentTab = 3)) {
        const listGroupItem = document.getElementsByClassNam("m3");
        listGroupItem.forEach((item) => {
          item.classList.remove("active");
        });
        const target = document.getElementById(tagId);
        target.classList.add("change-active");
      }
    },
    savedata() {
      this.removactiveCurrent(); //حذف استایل
      this.getWordsWeight(); //1to3
      //this.getStopWordsData(); // words_stop_148
      //  this.save(); //indexnew
    },
    removactiveCurrent() {
      const listGroupItem = document.querySelectorAll(".list-group-item");
      listGroupItem.forEach((item) => {
        item.classList.remove("change-active");
      });
    },
    getWordsWeight() {
      let payload = {
        stopwords: this.stopWords,
        userId: this.currentUser.user_id,
        id: this.selectedItem._id,
        indexname: this.selectedItem._index,
      };

      let url = apis.wordSWeight.list;
      if (this.activeSchemaGetter?.key) {
        if (
          this.activeSchemaGetter.key == "qasection" ||
          this.activeSchemaGetter.key == "rgsection"
        )
          payload.qanon_id = this.selectedItem.qanon_id;

        url = url.replace("{{index_key}}", this.activeSchemaGetter?.key);
      } else url = url.replace("{{index_key}}/", "");

      this.httpService
        .postRequest(url, payload)

        .then((data) => {
          this.repeats = data;
          this.setListWords();
          // this.repeats["word4"] =this.stopWords
        })
        .finally(() => {
          // this.removactiveCurrent();
          // this.save();
        });
    },
    getStopWordsData() {
      var vm = this;
      this.fetchingData = true;

      let url = adminApi.admin.get.replace(
        "{{system}}",
        this.$route.meta.apiKey
      );
      url += "_" + this.currentUser.user_id;

      this.httpService
        .getRequest(url)
        .then((response) => {
          if (response.hits.hits.length) {
            this.stopWords = response.hits.hits[0]._source.value;
            this.data = response.hits.hits[0]._source;
            vm.fetchingData = false;
          } else {
            this.getAdminData();
            // this.getWordsWeight()1;
          }
        })
        .catch((error) => {})
        .finally(() => {
          this.getWordsWeight();
          // با این کار کلماتی که در حذفی هست از لیست خارج می شود
        });
    },
    getAdminData() {
      var vm = this;
      let url = adminApi.admin.get.replace(
        "{{system}}",
        this.$route.meta.apiKey
      );

      this.httpService
        .getRequest(url)
        .then((response) => {
          this.stopWords = response.hits.hits[0]._source.value;
          this.data = response.hits.hits[0]._source;
        })
        .catch((error) => {})
        .finally(() => {
          vm.fetchingData = false;
        });
    },
    save() {
      var vm = this;
      this.fetchingData = true;

      // const payload = {
      //   ...this.dataStopWords,
      //   ...{
      //     value: this.stopWords,
      //     user_id: this.currentUser.user_id,
      //     username: "",
      //   },
      // };

      // var url = adminApi.admin.save;

      let payload = {
        words_stop: this.stopWords,
      };
      let url = repoUrl() + settingsApi.user.setKey;

      this.httpService
        .postRequest(url, payload)
        .then((response) => {
          vm.fetchingData = false;
        })
        .catch((error) => {})
        .finally(() => {
          vm.fetchingData = false;
        });
    },

    ReturnToInitialSettings() {
      this.getAdminData();
    },
    showButtonRemove() {},

    closeModal() {
      this.$emit("close-modal");
    },
    updateList() {
      this.$emit("update-list");
    },
    deleteItem() {
      this.$emit("delete-item");
    },
    setTab(tab) {
      this.currentTab = tab;
      this.counter++;

      if (tab === 4) {
        this.getStopWordsData();
      }
      this.prepareAndGetChartData();
    },
    prepareAndGetChartData() {
      const chartData = [];
      let count = 0;
      this["words" + this.currentTab]?.forEach((element) => {
        count++;
        if (count < 100)
          chartData.push({
            name: element[0],
            weight: element[1],
          });
      });

      // this.$emit('on-chart-data-ready',chartData)
      return chartData;
    },
  },
};
</script>

<style scoped lang="scss">
.list-group-item {
  &.active,
  &:hover {
    background-color: #e8fcff;
  }
}
.nav-item.nav-link {
  &.active,
  &:hover {
    background-color: #e8fcff;
  }
}
// .change{
//   background-color: red;
// }

.context-menu {
  position: absolute;
  left: 18px;
}

// .user-modal {
//   width: 53em;
//   height: 30em;
//   // display: none;
// }

// .repeat-btn {
//   color: #9f9f9f;
// }

// .form-control-textarea {
//   position: absolute;
//   height: 300px !important;
//   width: 550px;
//   overflow-y: scroll;
// }

// #overlay-plugin1 {
//   position: absolute;
//   width: 560px;
//   height: 360px;
// }
.overlay-plugin {
  // position: absolute;
  min-width: 15em;
  height: 20em;
  overflow-y: auto;
}
// .button-form {
//   position: absolute;
//   bottom: 10px;
//   left: 10px;
// }
// .modal-footer {
//   height: 60px;
// }
// .button_giveup {
// position: absolute;
// bottom: 10px;
// left: 70px;
// }
// .textarea-form {
// position: relative;
// width: 560px !important;
// height: 310px !important;
// overflow-y: scroll !important;
// }
.change-active {
  text-decoration: line-through;
}
.change-active span {
  color: brown !important;
}
.parent_select {
  position: relative;
  // background-color: yellow;
  width: 650px;
  height: auto;
  padding: 60px;
  left: 50px;
  top: 0px;
}
// .subject {
//   position: relative;

//   // background-color: red !important;
//   top: -50px;
//   width: 650px !important;
//   height: auto;
//   // padding-right: 70px;
//   // padding-left: 70px;
//   right: -60px;
// }
// .selected_word_subject {
//   // background-color: green;
//   position: relative;
//   right: 150px;
//   top: -55px;
//   width: 150px;
// }
.selected_word_subject select {
  width: 150px !important;

  color: #00b6e3;
}
.select_word {
  border-radius: 20px;
  border: 2px solid #00b6e3;
  font-size: 14px;

  color: #00b6e3;
}
</style>

<style lang="scss">
.context-menu-dropdown {
  &.width-auto {
    .dropdown .dropdown-menu {
      width: 188px !important;
    }
  }
}
</style>
