<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-12 col-md-3 mb-2 py-md-2 my-tabs">
        <nav class="popUp-tab__menu">
          <div
            class="nav nav-tabs flex-md-wrap flex-nowrap"
            id="nav-tab"
            role="tablist"
          >
            <a
              v-if="Boolean(!entity?.islock)"
              @click="setTab(1)"
              class="nav-item"
              :class="{ active: currentTab == 1 }"
              id="nav-myAccount-tab"
              data-bs-toggle="tab"
              href="#nav-myAccount"
              role="tab"
              aria-controls="nav-myAccount"
              aria-selected="true"
              ><span v-tooltip="'قانون اثرپذیر'" class="d-flex">
                <span class="">فهرست قوانین</span>
              </span>
            </a>
            <a
              @click="setTab(2)"
              class="nav-item"
              :class="{ active: currentTab == 2 }"
              id="nav-changepass-tab"
              data-bs-toggle="tab"
              href="#nav-changepass"
              role="tab"
              aria-controls="nav-changepass"
              aria-selected="false"
            >
              <span v-tooltip="'مشخصات تنقیح'" class="d-flex">
                <span class="">مشخصات تنقیح</span>
              </span>
            </a>
          </div>
        </nav>
      </div>
      <div class="col-12 col-md-9 main-section">
        <div v-if="currentTab == 1 && Boolean(!entity?.islock)">
          <div class="container-fluid">
            <div class="input-group">
              <div class="input-group-append">
                <span class="tavasi tavasi-Component-198--1"></span>
              </div>

              <input
                ref="search-input"
                dir="rtl"
                v-model="textSearch"
                type="search"
                class="form-control"
                id="search-query"
                placeholder="جستجو..."
                name="search-query"
                aria-label="جستجو در اسناد، عناوین و واژگان"
                aria-describedby="basic-addon1"
                size="50"
                @keyup="toggleAutocomplete()"
                @keydown="onKeyDown()"
              />
              <button
                v-if="textSearch.length"
                @click="clearSearchAndGetList"
                type="button"
                class="btn clear-search p-0"
              >
                <svg class="icon icon-Component-294--1">
                  <use xlink:href="#icon-Component-294--1"></use>
                </svg>
              </button>

              <div class="input-group-prepend">
                <span>&nbsp;&nbsp;&nbsp;</span>
              </div>
            </div>
            <div class="row">
              <div class="mb-3 me-4">
                <!-- <small v-if="searchInCurrentGroup">
                  جستجو در :
                  {{ searchInCurrentGroup?.title }}
                </small> -->
              </div>
            </div>
            <div class="row prop-list" style="overflow-y: auto; height: 16em">
              <div
                v-for="list_item in listData"
                :key="list_item._id"
                class="col-12"
                @click="onSelectLaw(list_item._source.qanon_id)"
              >
                <div>
                  <p class="me-2 py-1 text-nowrap text-truncate prop-item">
                    <span
                      v-html="getDataValue('qanon_title', list_item)"
                      class="me-2"
                    >
                    </span>
                  </p>
                </div>
              </div>
            </div>
            <div class="popUp-tab__buttons d-flex justify-content-center">
              <jahat-pagination
                class="flex-wrap compare-modal-pagination"
                :paginationInfo="pagination"
                @page-changed="pageChanged"
                @page-limit-changed="pageLimitChanged"
                @sort-changed="sortChanged"
              >
              </jahat-pagination>
            </div>
          </div>
        </div>
        <div v-if="currentTab == 2" class="form-container firefox-scrollbar">
          <form-builder
            :key="renderAgain"
            :formElements="formSchemaItems"
            :formData="getFormDataForView()"
            :displayMode="'default'"
            @saveComponentValue="onSaveComponentValue"
            @take-object="onChangeObject"
            :readOnly="Boolean(entity?.islock)"
            ref="formbuilder"
          ></form-builder>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import { mapActions, mapState } from "pinia";
import entityApi from "~/apis/entityApi";
import searchApi from "~/apis/searchApi";
import repoApi from "~/apis/repoApi";

export default {
  props: {
    numberCurrentTab: {
      default() {
        return 1;
      },
    },
    selectedLawId: {
      default() {
        return undefined;
      },
    },
    entity: {
      default() {
        return {};
      },
    },
    effectData: {
      default() {
        return {};
      },
    },
  },
  beforeMount() {
    this.httpService = useNuxtApp()["$http"];
    this.formData = this.effectData;

    this.effective_leaves = [];
    this.treeLeaves(this.effective_leaves, this.nlpTreeGetter);
  },
  mounted() {
    this.formSchemaItems = this.draftActiveStepGetter?.form_items;
    this.currentTab = this.numberCurrentTab;
    let qanon_id = this.selectedLawId;

    if (this.currentTab == 1) this.getDefaultList();
    else if (this.currentTab == 2) this.onSelectLaw(qanon_id);
  },
  data() {
    return {
      currentTab: 1,
      renderAgain: 1,
      listData: [],
      data_changed: {},
      formData: {},
      tableActions: [
        {
          showOutside: false,
          show: true,
          icon: "default",
          title: "ویرایش",
          to: { name: "undefined" },
          selected: false,
          disabled: false,
          howToOpen: "",
          href: "",
          class: "edit-btn",
          action: "togglePanel",
          can: "item-info_edit",
        },
        {
          showOutside: false,
          show: true,
          icon: "default",
          title: "حذف",
          to: { name: "undefined" },
          selected: false,
          disabled: false,
          howToOpen: "",
          href: "",
          class: "delete-btn",
          action: "delete-table-item",
          can: "item-list_delete",
        },
      ],
      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      },
      sorting: {
        sortby: "created",
        sortorder: undefined, // asc | desc | none
      },
      typingTimer: 0,
      doneTypingInterval: 500,
      textSearch: "",
      formSchemaItems: [],
      to_sections_tree: [],
      effective_leaves: [],
      to_section_title: "",
      from_section_title: "",
    };
  },
  computed: {
    ...mapState("entity", ["draftActiveStepGetter", "nlpTreeGetter"]),
  },
  methods: {
    async getEntityInfo(key, entityId) {
      if (entityId) {
        let url = repoUrl() + repoApi.public.get;

        url = url.replace("{{index_key}}", key);
        url = url.replace("{{entity_id}}", entityId);

        return await this.httpService.getRequest(url).then((res) => {
          return res;
        });
      }
    },
    getOptionsFromSections(sections) {
      let options = [];
      let parents = [];
      let prev_level = 0;

      sections?.forEach((el) => {
        let parent_path = parents.join("/");
        if (parent_path != "") parent_path += "/";
        let item_leave = {};
        item_leave["title"] = parent_path + el.full_path;
        item_leave["value"] = el.id;
        let level = item_leave["level"];
        options.push(item_leave);
        if (level > prev_level) parents.push(el.full_path);
        else {
          while (level == prev_level) {
            parents.pop();
            prev_level--;
          }
        }
      });

      return options;
    },

    treeLeaves(leaves, tree = [], byPath = true, parent_path = "") {
      tree.forEach((item) => {
        if (byPath) {
          item["title"] = parent_path + "/" + item.text;
        } else item["title"] = item.text;

        item["value"] = item.id;
        leaves.push(item);

        if (item.children.length) {
          if (byPath) {
            if (parent_path != "") parent_path += "/";
            parent_path = item.text;
          }
          this.treeLeaves(leaves, item.children, byPath, parent_path);
        }
      });
      // return leaves;
    },
    async getTreeData(qanon_id) {
      let url =
        repoUrl() +
        buildName() +
        "/" +
        entityApi.edit.treeList;
      url = url.replace("@index_key", "qasection");
      url = url.replace("@qanon_id", qanon_id);

      return await this.httpService
        .getRequest(url)
        .then((res) => {
          let sections_tree = res.data;
          sections_tree.forEach((element) => {
            element["title"] = element.text;
          });
          return sections_tree;
        })
        .finally(() => {});
    },

    onSelectLaw(id) {
      // this.effects = item._source.effects;

      this.formData["to_prev_text"] = "";
      this.formData["from_qanon_title"] = this.entity.title;
      this.formData["to_qanon_id"] = id;

      this.getTreeData(id).then((res) => {
        let to_sections_tree = res;
        if (to_sections_tree.length)
          this.formData["to_qanon_title"] = to_sections_tree[0]["qanon_title"];
        this.formSchemaItems = this.getSchemaByOptions(
          this.formSchemaItems,
          this.entity?.sections,
          to_sections_tree
        );
        this.setTab(2);
        this.renderAgain++;
      });
    },
    getSchemaByOptions(schema, from_sections, to_sections_tree) {
      if (!schema) return [];

      schema.forEach((item, index) => {
        // جزء اثر گذار
        if (item.key == "from_section_title") {
          schema[index]["options"] = this.getOptionsFromSections(from_sections);
        }
        // جزء اثر پذیر
        if (item.key == "to_section_title") {
          let options = [];
          this.treeLeaves(options, to_sections_tree, false);
          schema[index]["options"] = options;
        }
      });

      return schema;
    },
    clearSearchAndGetList() {
      this.textSearch = "";
      this.getDefaultList();
    },

    onKeyDown() {
      clearTimeout(this.typingTimer);
    },

    setTab(tab) {
      this.currentTab = tab;
      if (this.currentTab == 1 && !this.listData) this.getDefaultList();
      // else if (this.currentTab == 2) this.getEffLaw("qq" + this.effLaw.id);
    },

    getFormDataForView() {
      //edit state
      // if (this.effectData)
      {
        //بخاطر انتخاب در حالت کمبو
        this.formData["from_section_title"] = this.formData["from_section_id"];
        this.formData["to_section_title"] = this.formData["to_section_id"];
      }
      return this.formData;
    },

    getFormDataForSave() {
      if (this.from_section_title)
        this.formData["from_section_title"] = this.from_section_title;
      if (this.to_section_title)
        this.formData["to_section_title"] = this.to_section_title;

      // console.log(this.formData);

      return this.formData;
    },

    onChangeObject({ objectText, objectValue, key }) {
      if (key == "to_section_title") {
        // console.log("to_section_title")
        // console.log({ objectText, objectValue, key })

        this.to_section_title = objectText;

        let id = objectValue;
        this.getEntityInfo("qasection", id).then((res) => {
          this.$set(this.formData, "to_section_id", id);
          this.$refs.formbuilder.updateValueFormData("to_section_id", id);

          this.$set(this.formData, "to_prev_text", res?._source?.content);
          this.$refs.formbuilder.updateValueFormData(
            "to_prev_text",
            res?._source?.content
          );
          this.renderAgain++;
        });
      }
      if (key == "from_section_title") {
        // console.log("from_section_title")
        // console.log({ objectText, objectValue, key })
        let id = objectValue;
        this.$set(this.formData, "from_section_id", id);
        this.$refs.formbuilder.updateValueFormData("from_section_id", id);

        this.from_section_title = objectText;

        let item = this.entity?.sections?.find((i) => i.id == id);
        this.$set(this.formData, "from_section_text", item.content);
        this.$refs.formbuilder.updateValueFormData(
          "from_section_text",
          item.content
        );

        this.renderAgain++;
      }
    },
    onSaveComponentValue(data) {
      // console.log("data");
      // console.log(data);

      this.formData = data;
    },

    getDefaultList(sortKey = "lasttitle") {
      let url = repoUrl() + searchApi.search.default;
      url = url.replace("{{appname}}", buildName());
      url = url.replace("{{index_key}}", "qasection");
      url = url.replace("{{sortKey}}", sortKey);
      url = url.replace("{{offset}}", this.pagination.offset);
      url = url.replace("{{limit}}", this.pagination.limit);
      url = url.replace("/{{filter}}", "");

      this.httpService.getRequest(url).then((res) => {
        const total = res.hits.total.value;
        this.listData = res.hits.hits;

        let pages = Math.ceil(total / this.pagination.limit);
        pages =
          total % this.pagination.limit == 0 && totla != 0 ? pages : pages - 1;
        const pagination = {
          total: total,
          pages: pages == 0 ? 1 : pages,
        };

        this.pagination = { ...this.pagination, ...pagination };
      });
    },
    prevSearchStart() {
      this.liSelected = null;
      this.showItem = 0;
      this.searchStart(this.textSearch);
    },
    toggleAutocomplete() {
      clearTimeout(this.typingTimer);

      this.typingTimer = setTimeout(() => {
        this.prevSearchStart(this.textSearch);
      }, this.doneTypingInterval);
    },
    onKeyDown() {
      clearTimeout(this.typingTimer);
    },

    myEncodeQuery(text) {
      if (!text) return "";
      //text = JSON.stringify(text);
      let ch1 = encodeURIComponent("#");
      let ch3 = encodeURIComponent("\\");
      // let ch4 = encodeURIComponent(".");
      text = text.replaceAll("#", ch1);
      text = text.replaceAll("/", "\\");
      text = text.replaceAll("\\", ch3);
      // text = text.replaceAll(".", '%2E');
      return text;
    },
    searchStart(item = null) {
      if (item != null && item != "") {
        item = item.trim();

        this.resetOptions();
        this.getQuery();
      } else {
        this.searchingState = false;
        this.getRequestSearch();
      }
    },
    resetOptions() {
      this.page = 0;
      this.filterUrl = "";
    },
    getQuery: function (
      pageOnly = false,
      // filteronly = false,
      _sortKey = undefined
    ) {
      // ++this.rerenderChart;
      if (this.textSearch == "" || this.textSearch === undefined) return;

      var vm = this;
      this.loading = true;
      this.searchingState = false;

      const appName = buildName() + "/search/";

      let type = "qasection";
      if (!type) return;

      let query = myEncodeQuery(this.textSearch);

      this.domain_key = this.domainActiveGetter?.key;
      if (this.domain_key && this.domain_key != "all") {
        this.domain_lable = this.domainActiveGetter?.label;
        query =
          encodeURIComponent("#") +
          this.domainActiveGetter?.label +
          " " +
          query;
      }

      var suburl = repoUrl() + appName + type + "/";

      let filter = this.filterUrl;
      // if (this.textAmplify != undefined && this.textAmplify != "") {
      //   filter += "&o_am=" + this.textAmplify;
      // }

      let finalUrl = suburl;

      _sortKey = "searchsort";
      if (_sortKey != undefined) finalUrl += _sortKey;
      if (!pageOnly) {
        // this.resetPagination();
      }

      finalUrl +=
        "/" +
        this.pagination.offset +
        "/" +
        this.pagination.limit +
        "/q=" +
        query +
        filter;

      //this.addressBarUrl = "/q=" + query + filter;

      this.httpService
        .getRequest(finalUrl)
        .then((res) => {
          this.searchingState = true;
          vm.loading = false;

          vm.total_answer = res.hits.total.value;

          // vm.initNormalRespone(res, pageOnly, filteronly);

          const total = res.hits.total.value;

          vm.listData = res.hits.hits;

          let pages = Math.ceil(total / this.pagination.limit);
          pages =
            total % this.pagination.limit == 0 && totla != 0
              ? pages
              : pages - 1;
          const pagination = {
            total: total,
            pages: pages == 0 ? 1 : pages,
          };

          this.pagination = { ...this.pagination, ...pagination };

          // LogService.index(
          //   this.currentUser,
          //   vm.textSearch,
          //   vm.page,
          //   vm.filterUrl,
          //   response.data.took
          // );
        })
        .catch((error) => {
          vm.loading = false;
          this.searchingState = false;
          // vm.$alert(error);
        });
    },

    getDataValue(key, item, type = "") {
      let value = "";
      if (item) {
        if (item.highlight && item.highlight[key]) value = item.highlight[key];
        else if (item._source && item._source[key]) value = item._source[key];

        if (type == "date") value = this.dateTofarsi(value);
      }
      return value;
    },
    dateTofarsi(item) {
      var m = item;
      var d = new Date(m).toLocaleDateString("fa-IR");
      return d;
    },

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

      this.prevSearchStart();
    },
    pageChanged(paging) {
      let page = paging.pageNumber;
      page -= 1;

      this.pagination.offset = this.pagination.page * paging.limit;
      this.pagination.limit = paging.limit;
      this.pagination.page = paging.pageNumber;

      this.prevSearchStart();
    },
    sortChanged(sorting) {
      // this.resetPagination();
      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;

      this.prevSearchStart();
    },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 0,
        offset: 0,
        limit: 10,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.popUp-tab__menu a {
  display: flex;
  -webkit-box-orient: vertical !important;
  -webkit-box-direction: normal !important;
  -ms-flex-direction: column !important;
  flex-direction: column !important;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  padding-right: 10px;
  border-radius: 0;
  width: 100%;
  border: unset;
  margin: 0;
  font-size: 1rem;
  color: #444444;
  padding-top: 6px;
  padding-bottom: 6px;
  margin-bottom: 1em;
  padding-left: 10px;
  -webkit-transition: all 0.3s ease;
  transition: all 0.3s ease;
  &.active {
    background-color: #e8fcff;
  }
  &:hover {
    background-color: #e8fcff;
  }
}

.nav-tabs {
  border-bottom: unset !important;
}

.nav-item {
  white-space: nowrap;
}

.search-main {
  .search-list {
    height: 15em;
    overflow-y: auto;

    .btn {
      width: 100%;
      text-align: right;
      border-radius: 0;
      border-bottom: 1px solid #eee;

      &:hover {
        background: #eee;
      }
    }
  }
  .high-lighted {
    background-color: yellow;
    padding: 0 5px;
    font-weight: bold;
  }
}

.form-container {
  height: 27.7em;
  overflow-y: auto;
}

// // 1600px
// @media screen and (max-width: 100em) {
// }
// // 1399px
// @media screen and (max-width: 87.499em) {
// }

// // 991px
// @media screen and (max-width: 61.998em) {
// }

// // 767px
// @media screen and (max-width: 47.938em) {
//   .my-tabs {
//     border-bottom: 1px solid rgb(222, 226, 230);
//   }
// }
// @media screen and (min-width: 47.938em) {
//   .my-tabs {
//     border-left: 1px solid rgb(222, 226, 230);
//   }
// }

// // 575px
// @media screen and (max-width: 35.938em) {
//   .main-section {
//     height: 18em;
//     overflow-y: auto;
//   }
// }

// end
</style>

<style lang="scss" scoped>
.icon-upload-file {
  font-size: 2rem;
}
.compare-modal-pagination {
  margin-top: 1.5em;
  font-size: 0.8em;
  margin-right: 1em;
  display: flex;
  // flex-wrap: nowrap !important;
}
.input-group {
  border-radius: 1.6em;
  border: 1px solid #eee;
}

.input-group-append {
  .tavasi {
    display: flex;
    align-items: center;
    padding: 0.4em;
  }

  .input-group-text {
    // border-top-right-radius: 0.5em;
    // border-bottom-right-radius: 0.5em;
    // background-color: transparent;
  }
}
.input-group-prepend {
  position: relative;
  .clear-search {
    position: absolute;
    right: -3em;
    top: 0;
    bottom: 0;
    margin: auto;
    display: flex;
    align-items: center;
  }
  .input-group-text {
    // background-color: transparent;
    // border-top-left-radius: 0.5em;
    // border-bottom-left-radius: 0.5em;
  }
}
.form-control {
  height: 2.5em;
  border-color: transparent;

  &::-webkit-search-decoration,
  &::-webkit-search-cancel-button,
  &::-webkit-search-results-button,
  &::-webkit-search-results-decoration {
    -webkit-appearance: none;
  }
}
.prop-list {
  padding: 0 1em;
  .prop-item {
    margin-bottom: 1em;
    padding-bottom: 1em;
    position: relative;
    max-height: 9.5em;
    cursor: pointer;
    &:hover {
      background-color: #e8fcff;
    }

    &::before {
      content: "";

      position: absolute;
      bottom: 0;
      left: 0;
      right: 0%;
      width: 50%;
      margin: auto;
      border-bottom: 1px solid #eee;
    }

    .prop-item-label-container {
      .prop-item-label {
        border: 1px solid #e4dfd8;
        padding: 0.3em;
        font-family: "sahel-regular";
        font-size: 0.8rem;
        margin-left: 1em;
        border-radius: 0.3em;
      }
      margin-bottom: 0.8em;
    }
    .prop-item-description-container {
      padding-right: 1em;

      .prop-item-description {
        font-size: 0.8rem;
        color: #4e4e4e;
        max-height: 9.5em;
        overflow: hidden;
        color: var(--dark-gray-color);

        // @include textOverflow(7.5em);
      }
    }

    .prop-item-actions {
      position: absolute;
      left: 2em;
      top: 0.5em;

      .btn {
        padding: 0;
      }

      .icon {
        color: #bdc7d2;
      }
    }
  }
}
</style>
