<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"
    items-per-page-text="Itens por página"
    :page-text="`1 de ${list.length}`"
    :height="480"
    :fixed-header="true"
    :fixed-footer="true"
    disable-pagination
    :hide-default-header="true"
    :hide-default-footer="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"
        prepend-icon="mdi-pencil"
      >
        Editar
      </v-btn>
    </template>
    <template v-slot:[`item.actionVisualize`]="{ item }">
      <v-btn
        size="x-small"
        variant="outlined"
        v-if="onlyVisualize || showVisualize"
        @click="visualizeItem(item.columns)"
        color="success"
        class="mr-0"
        prepend-icon="mdi-file-find"
      >
        Visualizar
      </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"
      >
        Excluir
      </v-btn>
    </template>
    <template v-if="canActive" v-slot:[`item.enumDataState`]="{ item }">
      <v-btn
        size="x-small"
        variant="outlined"
        :loading="actionLoading.changeDataStateItem[item.columns.id]"
        v-if="enableDataState(item.columns) && canActive"
        @click="changeDataStateItem(item.columns)"
        :color="item.columns.enumDataState == 1 ? 'warning' : 'success'"
        :prepend-icon="
          item.columns.enumDataState == 1 ? 'mdi-cancel' : 'mdi-check-bold'
        "
      >
        {{ item.columns.enumDataState == 1 ? "Desativar" : "Ativar" }}
      </v-btn>
    </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>

    <!-- Slots dinâmicos a partir do Header -->
    <template
      v-for="(header, index) in headersSlotTyped"
      v-slot:[getSlotName(header)]="slotProps"
    >
      <template v-if="header.type == 'date'">
        {{
          slotProps.item.raw[header.key] == null
            ? (slotProps.item.raw[header.key] = "-")
            : moment(slotProps.item.raw[header.key]).isValid()
            ? moment(slotProps.item.raw[header.key])
                .utc()
                .format("DD/MM/YYYY")
            : (slotProps.item.raw[header.key] = "-")
        }}
      </template>
      <template v-else-if="header.type == 'datetime'">
        {{
          slotProps.item.raw[header.key] == null
            ? (slotProps.item.raw[header.key] = "-")
            : moment(slotProps.item.raw[header.key]).isValid()
            ? moment(slotProps.item.raw[header.key])
                .utc()
                .format("DD/MM/YYYY HH:mm")
            : (slotProps.item.raw[header.key] = "-")
        }}
      </template>
      <template v-else-if="header.type == 'currency'">
        {{
          (Math.round(slotProps.item.raw[header.key] * 100) / 100) | currency
        }}
      </template>
      <template v-else-if="header.type == 'currency_usd'">
        {{
          (Math.round(slotProps.item.raw[header.key] * 100) / 100)
            | currency_usd
        }}
      </template>
      <template v-else-if="header.type == 'decimal'">
        {{ slotProps.item.raw[header.key] | decimal(getFormatConfig(header)) }}
      </template>
      <template v-else-if="header.type == 'percentage'">
        {{
          !!slotProps.item.raw[header.key]
            ? `${Math.round(slotProps.item.raw[header.key] * 10000) / 100}%`
            : "-"
        }}
      </template>
      <template v-else-if="header.type == 'noyes'">
        {{ slotProps.item.raw[header.key] ? "Sim" : "Não" }}
      </template>
      <template v-else-if="header.type == 'cnpj'">
        {{ cnpjMask(slotProps.item.raw[header.key]) }}
      </template>
      <div
        v-else-if="header.type == 'icontruefalse'"
        :key="`${slotProps.item.id}_${index}`"
      >
        <v-icon v-if="slotProps.item.raw[header.key]" color="success"
          >mdi-check-bold</v-icon
        >
        <v-icon
          v-else-if="slotProps.item.raw[header.key] == false"
          color="error"
          >mdi-close-thick</v-icon
        >
      </div>
      <template v-else-if="header.type == 'enableddisabled'">
        {{ slotProps.item.raw[header.key] ? "Ativo" : "Inativo" }}
      </template>
      <template v-else>
        {{ slotProps.item.raw[header.key] }}
      </template>
    </template>
  </v-data-table>
</template>

<script>

</script>

<script lang="ts" setup generic="T extends Item">
import moment from "moment";
import { computed, ref, useSlots } from "vue";
// import { ZCDataTableHeader } from "~/types/vuetify/ZCDataTableHeader";
import { ZCDataTableHeader } from '../../types';
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: "visualizeItem", id: number, item: any): void;
  (e: "deleteItem", id: number, item: any): void;
  (e: "changeDataState", id: number, item: any): void;
  (e: "dataLoaded", response: Response): void;
}>();

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

let list: Object[] = [];

const containsEnumDataState = ref(false);
const loading = ref(false);
const autoHeaders = ref([]);

const innerHeaders = computed<Array<Object>>(() => {
  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 ZCDataTableHeader[];

  if (props.showVisualize && !props.onlyVisualize) {
    functionsHeaders.push({
      title: "",
      key: "actionVisualize",
      value: "actionVisualize",
      sortable: false,
      // width: "2%"
    });
  }

  if (props.canEdit) {
    functionsHeaders.push({
      title: "",
      key: props.onlyVisualize ? "actionVisualize" : "actionEdit",
      value: props.onlyVisualize ? "actionVisualize" : "actionEdit",
      sortable: false,
      // width: "2%"
    });
  }

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

  if (containsEnumDataState && props.canActive) {
    functionsHeaders.push({
      title: "",
      key: "enumDataState",
      value: "enumDataState",
      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 headersSlotTyped = computed<Array<Object>>(() => {
  //Verificaçao para não sobrescrever SLOTS
  return !innerHeaders.value
    ? []
    : innerHeaders.value.filter(
        (header) =>
          header.type != undefined &&
          !slots.hasOwnProperty(`item.${header.key}`)
      );
});

const getSlotName = function (header) {
  return `item.${header.key}`;
};

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

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

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

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

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

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

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

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

  emit("changeDataState", 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 = req.data.items;
    } else {
      list = 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());
</script>

<style>
.v-data-table__td.v-data-table-column--align-start.v-data-table__th.v-data-table__th {
  background-color: #769fdb !important;
  color: #fff;
  font-weight: 700;
}

.v-data-table__td.v-data-table-column--align-center.v-data-table__th.v-data-table__th {
  background-color: #769fdb !important;
  color: #fff;
  font-weight: 700;
}
.v-data-table__td.v-data-table-column--align-end.v-data-table__th.v-data-table__th {
  background-color: #769fdb !important;
  color: #fff;
  font-weight: 700;
}

.v-table__wrapper::-webkit-scrollbar-thumb {
  border: solid 1px transparent !important;
  background: #769fdb50 !important;
  border-radius: 5px !important;
}

.v-table__wrapper::-webkit-scrollbar {
  width: 5px !important;
  /* width of the entire scrollbar */
}

.v-table__wrapper::-webkit-scrollbar-track {
  background: #769fdb10;
  height: 4px !important;
}

.v-table__wrapper::-webkit-scrollbar {
  height: 10px;
  border: 1px solid transparent;
}
</style>
