import { defineStore } from "pinia";
import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";

import { useCounterMixin } from "@/stores/mixin";

import type { ResLog } from "@/modules/03_logs/interface/response/Main";
const $q = useQuasar();
import { ref } from "vue";

const mixin = useCounterMixin();
const {
  dialogRemove,
  messageError,
  showLoader,
  hideLoader,
  success,
  dialogConfirm,
} = mixin;

export const useDataStore = defineStore("logStore", () => {
  const size = ref<number>(30);
  const logData = ref<ResLog[]>([]);
  const systemName = ref<string>();
  const searchAfter = ref<number | undefined>(undefined);
  const date = ref<[Date, Date]>([new Date(), new Date()]);
  async function fetchLog(
    opts?: {
      size?: number;
      search?: string;
      searchAfter?: number;
      systemName?: string;
      date?: Date;
      sort?: string;
      startDate?: Date;
      endDate?: Date;
      searchStatus?: string;
      rootId?: string;
    },
    isBottom?: boolean
  ) {
    const params = new URLSearchParams();

    for (const [k, v] of Object.entries(opts || {})) {
      if (v !== undefined)
        if (v instanceof Date) {
          params.append(k, v.toISOString());
        } else {
          params.append(k, v.toString());
        }
    }

    const query = params.toString();
    showLoader();
    await http
      .get(config.API.log + `${(params && "?".concat(query)) || ""}`)
      .then((res) => {
        const data = res.data;
        if (isBottom) {
          const test = data.map((item: any) => ({
            ...item._source,
            id: item._id,
          }));
          logData.value.push(...test);
        } else {
          logData.value = data.map((item: any) => ({
            ...item._source,
            id: item._id,
          }));
        }
        if (data.length > 0) {
          const lastDataSort = data[data.length - 1].sort;
          if (lastDataSort) {
            searchAfter.value = lastDataSort[0];
          }
        }
      })
      .finally(() => {
        hideLoader();
      });
  }

  return {
    size,
    logData,
    searchAfter,
    systemName,
    date,
    fetchLog,
  };
});
