<template>
  <div class="advanced-search firefox-scrollbar">
    <div class="container-fluid">
      <div class="row">
        <div class="col-12">
          <form>
            <component
              v-for="(formElement, index) in localFormElements"
              :key="index"
              :formElement="getValueToFormElement(formElement)"
              :inputClass="formElement.inputClass"
              :labelClass="formElement.labelClass"
              :is="returnComponentName(formElement.type)"
              @tribute-on-search="remoteSearch"
              @oninput="createQuery($event, index)"
              class="inside-advanced-search"
            ></component>

            <div class="d-flex justify-content-end align-items-baseline">
              <div class="bottom-close-form ms-3">
                <a @click.prevent="closeAdvancedSearch">بستن</a>
              </div>
              <div class="bottom-save-form">
                <button
                  type="submit"
                  class="btn btn-primary"
                  style="font-size: 11px; height: 3em; width: 7em"
                  @click.prevent="searchStart()"
                >
                  جستجو
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import { useResearchStore } from "../../../stores/researchStore";
import { useCommonStore } from "~/stores/commonStore";

import { mapState } from "pinia";

export default {
  data() {
    return {
      listUpdatedText: {},
      localFormElements: [],
      value: "",
    };
  },
  computed: {
    ...mapState(useCommonStore, ["searchActiveTabGetter"]),
    ...mapState(useResearchStore, ["researchSchemaGetter"]),
  },
  watch: {
    researchSchemaGetter: {
      handler: function (newSchema) {
        if (newSchema[0].advance)
          this.localFormElements = structuredClone(newSchema[0].advance);
      },
      // deep: true,
      immediate: true,
    },
  },
  beforeMount() {
    this.httpService = new HttpService(import.meta.env.VITE_BASE_URL);
  },

  mounted() {
    this.localFormElements = structuredClone(
      this.researchSchemaGetter[0].advance
    );
  },
  methods: {
    closeAdvancedSearch() {
      this.$emit("closeAdvancedSearch");
    },
    remoteSearch({ text, cb, item }) {
      // for clearing the query when user remove by keyboard backspace.
      if (text == "") this.makeSearchParams(undefined, 1);

      let url = item.completion;

      text = text.trim();
      url = url.replace("{{key}}", this.researchSchemaGetter[0].key);
      if (text == "") url = url.replace("/{{query}}", "");
      else url = url.replace("{{query}}", text);
      this.httpService.getRequest(url).then((response) => {
        cb(response.data);
      });
    },
    getValueToFormElement(elements) {
      Object.keys(elements).forEach((key, index) => {
        elements["value"] = this.researchSchemaGetter[0][elements.key];
      });
      return elements;
    },
    saveComponentValue(value, formElement) {
      // در صورت تغییر نگهداری می شود تا وقتی کلید ثبت زد، ذخیره شود
      if (this.researchSchemaGetter[0][formElement.key] != value) {
        this.listUpdatedText[formElement.key] = value;
      }
    },
    returnComponentName(type) {
      // if(!this.isEditable(searchActiveTabGetter?.key))
      //   return "LabelComponent";

      if (type == "select") return "SelectComponent";
      else if (type == "range_date") return "RangeDateComponent";
      else if (type == "completion") return "TributeComponent";
      else return "InputComponent";
    },

    // این لازم نیست و استفاده نداره!!!!!
    // saveProperty() {
    //   let id = this.$route.params.id;
    //   let key = this.$route.params.key;

    //   let formData = {
    //     id: id,
    //     meta: JSON.stringify(this.listUpdatedText),
    //   };

    //   let url = "/public/{{index_key}}/update/{{id}}";
    //   url = url.replace("{{index_key}}", key).replace("{{id}}", id);
    //   this.httpService.postRequest(url, formData).then((res) => {
    //     this.getServerItem();
    //   });
    // },
    createQuery(evt, index) {
      // evt.target.value => from input component.
      //evt => from datetime component.
      let value = evt?.target?.value ?? evt;
      this.$emit("set-query-advanced", this.makeSearchParams(value, index));
    },
    makeSearchParams(value, index) {
      if (value != undefined) this.localFormElements[index].value = value;
      else this.localFormElements[index].value = undefined;

      let query = "";

      this.localFormElements.forEach((item, rowIndex, array) => {
        if (item.value?.length)
          query += "#" + item.tag + " " + item.value + " ";
      });

      return query;
    },
    searchStart() {
      this.$emit("searchStart", this.searchStartValue());
    },
    searchStartValue() {
      let query = "";
      this.localFormElements.forEach((item, rowIndex, array) => {
        if (item.value?.length)
          query += "#" + item.tag + " " + item.value + " ";
      });
      return myEncodeQuery(query);
    },

    myEncodeQuery(text) {
      let ch1 = encodeURIComponent("#");
      let ch2 = encodeURIComponent("/");
      let ch3 = encodeURIComponent("\\");
      // let ch4 = encodeURIComponent(".");
      text = text.replaceAll("#", ch1);
      text = text.replaceAll("/", "\\");
      text = text.replaceAll("\\", ch3);
      // text = text.replaceAll(".", '%2E');
      return text;
    },
  },
};
</script>
