<template>
  <div
    class="d-flex flex-column flex-sm-row align-items-center mb-3 line-content"
  >
    <template v-for="(itemSchema, j) in lineSchema?.items || []">
      <div
        class="d-flex align-items-center ms-2"
        v-if="isExistDataItems(itemData, itemSchema)"
        :class="itemSchema.style"
        :key="j"
      >
        <label
          class="text-nowrap ms-1"
          style="color: black; font-family: sahel-semi-bold"
          for=""
          v-if="itemSchema.label"
          >{{ itemSchema.label }}</label
        >
        <template v-if="itemSchema.link_route">
          <a
            @click.prevent="openNewPage(itemData, itemSchema)"
            @mousedown.middle.prevent="openNewPage(itemData, itemSchema)"
            class="text__15 text-content"
            v-html="getDataItems(itemData, itemSchema)"
          >
          </a>
        </template>
        <template v-else-if="itemSchema.click_prevent">
          <div
            class="text__15 text-content"
            @click.prevent="openPrevent(itemData, itemSchema)"
            v-html="getDataItems(itemData, itemSchema)"
          ></div>
        </template>
        <div
          v-else
          class="text__14 text-content"
          v-html="getDataItems(itemData, itemSchema)"
        ></div>
      </div>
    </template>
  </div>
</template>

<script>
import { mapActions } from "pinia";
import { useEntityStore } from "@search/stores/entityStore";

export default {
  props: {
    lineSchema: {
      default() {
        return [];
      },
    },
    arrayItemData: {
      default() {
        return [];
      },
    },

    itemData: {
      default() {
        return {};
      },
    },
    textSearch: {
      default: "",
    },
  },
  // beforeMount() {
  //   this.httpService = new HttpService(process.env.VUE_APP_REPO_BASE_URL);
  // },
  mounted() {
    this.page = this.pagination;
  },
  methods: {
    ...mapActions(useEntityStore, ["SET_ITEM_ENTITY", "SET_LIST_ENTITY"]),
    openPrevent(item, schema) {
      this.$emit("openPrevent", { item, schema });
    },
    isExistDataItems(item, schema) {
      let source_key = schema?.source_key;
      const keys = source_key.split(",");

      let value = "";

      // if (keys.length >= 2) {
      //   for (let i = 0; i < keys.length; i++) {
      //     let key = keys[i]?.trim();

      //     if (item?._source[key].trim() !== "") {
      //       value = item?._source[key];

      //       // break;
      //     }
      //   }

      //   // value = null;
      // } else {
      //   value = item?._source[keys];
      // }

      if (keys.length >= 2) {
        for (let key of keys) {
          if (item?._source[key]?.trim()) {
            return true;
          }
        }
        return false;
      } else {
        value = this.getSourceData(item?._source, keys[0]);
        if (value) {
          if (Array.isArray(value) && value.length == 0) return false;
          else return true;
        } else return false;
      }
    },

    getDataItems(item, schema) {
      // debugger
      let source_key = schema?.source_key;

      const keys = source_key.split(",");

      let value = "";

      let key = keys[0];
      if (keys.length > 1) {
        for (let key1 of keys) {
          if (item?._source[key1]?.trim()) {
            key = key1;
            break;
          }
        }
      }

      value = this.highlightKey2(item, key);
      if (value != "") return value;

      if (schema.key == "tags") {
        value = this.textTags(item, schema.key);
      } else {
        value = this.getSourceData(item?._source, key);
        if (typeof value === "string") {
          value = value.replaceAll("\n", " ");
          value = value.replaceAll("\t", "");
        }
        if (schema?.process) {
          if (schema.process == "convert_date") {
            let date = new Date(value);

            if (value.toString().length == 10) {
              date = new Date(value * 1000);
            }

            return date.toLocaleDateString("fa-IR");
          }
        }
      }

      if (value == "") {
        value = "--";
      }

      return value;
    },

    textTags(item, key) {
      let text = "";

      if (Array.isArray(item._source[key])) text = item._source[key].join("، ");
      else text = item._source[key];

      return text;
    },

    highlightKey2(item, key, posfix = ["fa", "ph"]) {
      var text = "";

      if (item.highlight) {
        let key_highlight = key;
        let i = 0;
        while (i < posfix.length) {
          if (key_highlight in item.highlight) break;
          key_highlight = key + "." + posfix[i];
          i++;
        }

        if (key_highlight in item.highlight) {
          let value1 = "";
          value1 = item.highlight[key_highlight];

          if (Array.isArray(value1)) text = value1.join("... ");
          else text = value1;
        }
      }
      return text;
    },

    highlightKey(item, key1, key2 = "", key3 = "") {
      var text = "";
      if (item.highlight) {
        if (item.highlight[key1]) text = item.highlight[key1].join("... ");
        else if (key2 && item.highlight[key2])
          text = item.highlight[key2].join("... ");
        else if (key3 && item.highlight[key3])
          text = item.highlight[key3].join("... ");
      }

      if (text == "") {
        if (item._source[key1]) text = item._source[key1];
        else if (key2 && item._source[key2]) text = item._source[key2];
        else if (key3 && item._source[key3]) text = item._source[key3];

        if (text.length > 500) text = text.substring(0, 500);
      }
      return text;
    },
    openNewPage(item, schema) {
      let cloneList = JSON.parse(JSON.stringify(this.arrayItemData));
      let cloneItem = JSON.parse(JSON.stringify(item));

      if (schema?.link_route.length == 0) return;
      if (schema?.link_route.url_key) {
        window.open(item._source.url, "_blank");
      } else {
        this.SET_ITEM_ENTITY(cloneItem);
        this.SET_LIST_ENTITY(cloneList);
        localStorage.setItem("myList", JSON.stringify(cloneList));
        localStorage.setItem("myItem", JSON.stringify(cloneItem));
        let key = "";
        let query_key = "";
        let query_value = "";
        let keys = "";
        let id_route = "";
        let keyName = schema?.link_route.id; // default : _id
        // ساختن query به صورت پویا
        let query = {
          searchtext: this.textSearch ?? undefined,
        };

        if (keyName in item) {
          id_route = item[keyName];
        } else {
          id_route = item?._source[keyName];
        }

        if (schema?.link_route?.query) {
          let querys = schema?.link_route.query;
          if (typeof querys === "string") {
            keys = schema?.link_route?.query.split("=");

            if (keys.length >= 2) {
              query_key = keys[0];
              query_value = keys[1];
            }
            if (query_key && query_value) {
              query[query_key] = query_value; // کلید پویا و مقدار از قسمت بالایی
            }
          } else {
            let newObject = {};
            for (const [key, value] of Object.entries(querys)) {
              if (value in item) {
                newObject[key] = item[value];
              } else {
                newObject[key] = item?._source[value];
              }
            }
            Object.assign(query, newObject);
          }
        }
        if (schema?.link_route?.key_item || schema?.link_route.key) {
          if (schema?.link_route?.key_item)
            key = this.getSourceData(item, schema?.link_route.key_item);
          else key = schema?.link_route.key;
        }
        const routeData = this.$router.resolve({
          name: schema?.link_route.name,
          params: {
            id: id_route,
            key: key,
          },

          query: query,
        });

        window.open(routeData.href, "_blank");
      }
    },
    getArrayData(itemData, collapseItem) {
      if (!collapseItem.array_key) return [itemData];
      let sourceData = this.getSourceData(itemData, collapseItem.array_key);
      if (!Array.isArray(sourceData)) return [itemData];
      return sourceData;
    },
    getSourceData(itemData, key) {
      let sourceData = itemData;
      key.split(".").forEach((k) => {
        if (sourceData && sourceData[k] !== "") {
          sourceData = sourceData[k];
        } else {
          sourceData = undefined; // یا می‌توانید هر مقدار دلخواهی قرار دهید
        }
      });

      return sourceData;
    },
  },
};
</script>

<style lang="scss" scoped>
.search-tag {
  cursor: pointer;
  color: #96a5b5;
  white-space: nowrap;
  padding: 0 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  background: #fff;
  border: 1px solid #e4dfd8;
  height: 20px;
  margin-left: 8px;
  &:hover {
    color: black;
    border-color: black;
  }
}
.search-title {
  cursor: pointer;
  color: rgb(59, 130, 246) !important;
  &:hover {
    color: rgb(59, 130, 246) !important;
    text-decoration: underline !important;
  }
}
.search-label {
  // color: #96a5b5;
  a {
    color: #00b6e3;
  }
}
.search-body {
  display: -webkit-box !important;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 25px;
  color: #000;
}
.text-content {
  text-align: justify;
}

@media (max-width: 575.98px) {
}
@media only screen and (min-width: 576px) and (max-width: 767.98px) {
}
@media only screen and (min-width: 768px) and (max-width: 900.98px) {
}
@media only screen and (min-width: 901px) and (max-width: 1049.98px) {
}
@media (min-width: 1050px) {
}
</style>