<template>
  <v-data-table
    v-model="selected"
    class="elevation-1"
    hover
    no-data-text="Nenhum dado foi encontrado"
    v-bind="$attrs"
    :headers="innerHeaders"
    :items="list"
    :loading="loading"
    :height="450"
    :fixed-header="true"
    :hide-default-header="true"
  >
    <template v-slot:[`item.actionEdit`]="{ item }">
      <v-btn
        size="x-small"
        variant="outlined"
        v-if="canEdit && !onlyVisualize"
        @click="editItem(item.columns)"
        color="success"
        class="mr-0 text-none text-subtitle-2"
        prepend-icon="mdi-pencil"
      >
        Editar
      </v-btn>
    </template>

    <template v-slot:[`item.actionDelete`]="{ item }">
      <v-btn
        size="x-small"
        variant="outlined"
        @click="deleteItem(item.columns)"
        :disabled="!enableDelete(item.columns)"
        color="error"
        prepend-icon="mdi-delete"
        class="text-none text-subtitle-2"
      >
        Excluir
      </v-btn>
    </template>
    <template v-slot:bottom>
      <!-- REMOVER PAGINAÇÃO NO FOOTER -->
    </template>

    <!-- Slots passados para o componente -->
    <template v-for="(_, name) in $slots" v-slot:[name]="slotProps">
      <slot v-if="slotProps" :name="name" v-bind="slotProps" />
      <slot v-else :name="name" />
    </template>
  </v-data-table>
</template>

<script>

</script>

<script lang="ts" setup generic="T extends Item">
import { computed, onMounted, ref, watch } from "vue";
import { ZCDataTableHeader } from '../types';
//import { ZCDataTableHeader } from "~/types/vuetify/ZCDataTableHeader";
//import { useNuxtApp, useSlots } from "#app";
import { useAxios } from "../../composables/useAxios";

//const nuxtApp = useNuxtApp();
//const slots = useSlots();
const { $axios } = useAxios();

const emit = defineEmits<{
  (e: "editItem", id: number, item: any): void;
  (e: "deleteItem", id: number, item: any): void;
}>();

const props = defineProps({
  slots: {
    type: Object,
  },
  headers: {
    type: Array<ZCDataTableHeader>,
    default() {
      return [];
    },
  },
  resourceUrl: {
    type: String,
    default: "",
  },
  canEdit: {
    type: Boolean,
    default: true,
  },
  onlyVisualize: {
    type: Boolean,
    default: true,
  },
  canDelete: {
    type: Boolean,
    default: true,
  },
});

let list = ref<Object[]>([]);

const loading = ref(false);
const autoHeaders = ref([]);
const selected = ref(null);

const innerHeaders = computed<ZCDataTableHeader[]>(() => {
  if (!!props.headers && props.headers.length > 0) {
    for (let i = 0; i < props.headers.length; i++) {
      let header = props.headers[i];
      if (header.key == "id") {
        // header.width = "2%";
        break;
      }
    }
  }

  let functionsHeaders = [] as any[];

  if (props.canEdit) {
    functionsHeaders.push({
      title: "",
      sortable: false,
      // width: "2%"
    });
  }

  if (props.canDelete) {
    functionsHeaders.push({
      title: "",
      key: "actionDelete",
      value: "actionDelete",
      sortable: false,
      // width: "2%"
    });
  }

  if (autoHeaders.value.length > 0) {
    functionsHeaders.push(...autoHeaders.value);
  }

  if (functionsHeaders.length > 0 && !!props.headers) {
    functionsHeaders.push(...props.headers);
    return functionsHeaders;
  } else {
    return props.headers;
  }
});

const getId = (item: T) => {
  return item.hasOwnProperty("Id")
    ? item.Id
    : item.hasOwnProperty("id")
    ? item.id
    : 0;
};

const addItem = (item: T) => {
}

const editItem = (item: T) => {
  let id = getId(item);

  emit("editItem", id, item);
};

const deleteItem = (item: T) => {
  let id = getId(item);

  emit("deleteItem", id, item);
};

const enableDelete = (item: T) => {
  if (
    !props.canDelete ||
    (item.hasOwnProperty("enumRecordPermission") &&
      item.enumRecordPermission != 1 &&
      item.enumRecordPermission != 4)
  ) {
    return false;
  } else {
    return true;
  }
};

const enableDataState = (item: T) => {
  return item.hasOwnProperty("enumDataState");
};

const load = async () => {
  loading.value = true;

  try {
    var req = await $axios({
      url: props.resourceUrl,
      method: "GET",
    });

    if (!!req && req.data.hasOwnProperty("items")) {
      list.value = req.data.items;
    } else {
      list.value = req.data;
    }

    // emit("dataLoaded", req.data);

    // if (list[0] && !!list[0].hasOwnProperty("enumDataState")) {
    //   containsEnumDataState.value = true;
    // }
    // nextTick(() => {
    //   if (!!list && !!list.length && !props.headers.length) {
    //     for (var key in list[0]) {
    //       autoHeaders.value.push({
    //         title: key,
    //         key,
    //         sortable: true,
    //       });
    //     }
    //   }
    // });
  } catch {
  } finally {
    loading.value = false;
  }
};

watch(()=> props.resourceUrl, async () => {
  await load();
});

onMounted(async () => await load());

defineExpose({ load, addItem, list });
</script>

<style></style>
