import HttpService from "~/services/httpService";
import repoApi from "~/apis/repoApi";
import chatApi from "~/apis/chatApi";

export const entityMixin = {
  mounted() {
    this.httpService = useNuxtApp()["$http"];
  },
  data() {
    return {
      fetchingData: false,

      showModal: false,
      errors: {},
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },
      sorting: {
        sortby: "created",
        sortorder: undefined, // asc | desc | none
      },
    };
  },
  methods: {
    async addEntity(my_entity) {
      let self = this;

      let url = repoUrl() + this.$route.meta.slug + repoApi.entity.add;
      return await this.httpService.postRequest(url, my_entity).then((res) => {
        // self.entity.id = res._id;
        // self.$emit("change", { item: self.entity, type: "entityList" });
        // self.closeModal();

        return res;
      });
    },
    async updateEntity(id, my_entity) {
      let self = this;

      let url =
        repoUrl() + this.$route.meta.slug + repoApi.entity.update + "/" + id;
      return await this.httpService.postRequest(url, my_entity).then((res) => {
        // self.entity.id = res._id;
        // self.$emit("change", { item: self.entity, type: "entityList" });
        // self.closeModal();
      });
    },

    //   return "نامعین";
    // },
    getListSpecial(_entityType, _specialType) {
      if (this.fetchingData) return;
      this.fetchingData = true;

      this.entity_type = _entityType;

      let url = repoUrl() + this.$route.meta.slug + repoApi.entity.listSpecial;
      url = url.replace("{{type}}", _entityType);
      url = url.replace("{{specialtype}}", _specialType);
      url = url + `/${this.pagination.offset}/${this.pagination.limit}`;

      // url = this.addSubjectFilters(url);
      // url = this.addCreationFilters(url);

      const subjectFilters = this.subjectFilters.size;
      const creationFilters = this.creationFilters.size;

      if (subjectFilters || creationFilters) {
        url += "/" + this.addSubjectFilters() + this.addCreationFilters();
      }

      this.httpService.getRequest(url).then((res) => {
        this.listEntity = res.hits.hits;

        const total = res.hits.total.value;
        const pages = Math.ceil(total / this.pagination.limit);
        const pagination = {
          total: total,
          pages: pages == 0 ? 1 : pages,
        };

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

        this.fetchingData = false;
      });
    },

    getList(_entityType) {
      if (this.fetchingData) return;
      this.fetchingData = true;

      this.entity_type = _entityType;

      let url =
        repoUrl() +
        this.$route.meta.slug +
        repoApi.entity.list.replace("{{type}}", _entityType) +
        `/${this.pagination.offset}/${this.pagination.limit}`;
      url += "/date_create/desc";

      const subjectFilters = this.subjectFilters.size;
      const creationFilters = this.creationFilters.size;

      if (subjectFilters || creationFilters) {
        // add subjects filters to url
        url += "/" + this.addSubjectFilters() + this.addCreationFilters();
      }

      this.httpService.getRequest(url).then((res) => {
        this.listEntity = res.hits.hits;

        const total = res.hits.total.value;
        const pages = Math.ceil(total / this.pagination.limit);
        const pagination = {
          total: total,
          pages: pages == 0 ? 1 : pages,
        };

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

        this.fetchingData = false;
      });
    },
    addSubjectFilters() {
      let url = "";
      const filterSize = this.subjectFilters.size;
      if (filterSize) {
        let query = "";
        let counter = 1;

        for (const [key, value] of this.subjectFilters.entries()) {
          query += value.id;
          query += counter++ < filterSize ? "$" : "";
        }
        url += "&f_si=" + query;
      }
      return url;
    },
    addCreationFilters() {
      let url = "";

      const filterSize = this.creationFilters.size;
      if (filterSize) {
        let query = "";
        let counter = 1;

        for (const [key, value] of this.creationFilters.entries()) {
          query += value.id;
          query += counter++ < filterSize ? "$" : "";
        }
        url += "&f_ci=" + query;
      }
      return url;
    },

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

      this.getList(this.entity_type);
    },
    pageChanged(paging) {
      let page = paging.pageNumber;
      page -= 1;
      this.pagination.offset = page * paging.limit;
      this.pagination.limit = paging.limit;
      this.pagination.page = paging.pageNumber;

      this.getList(this.entity_type);
    },
    sortChanged(sorting) {
      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;

      this.getList(this.entity_type);
    },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },
    //Creating new group when making a new answer/issue.
    addToConversation(res, data) {
      let conversation = {
        refrence_id: res._id,
        entity_type_id: this.$route.meta.entityType,
        type: data.type_id,
        desc: data.description,
        title: data.title,
      };

      this.httpService.postRequest(
        messageUrl() + chatApi.all.create,
        conversation
      );
    },
  },
  watch: {
    $route: {
      handler(to) {
        // this.httpService = new HttpService(import.meta.env.VITE_REPO_BASE_URL + to.meta.slug);
      },
      deep: true,
      // immediate: true,
    },
  },
};