<script setup>
import Table from "@/components/customUI/Table.vue";
import BuildingModal from "./BuildingModal.vue";
import { getBuildings, deleteBuildings } from "@/apis/building";
import { onMounted, ref, inject, computed } from "vue";
import { useI18n } from "vue-i18n";
import useBuildingStore from "@/stores/useBuildingStore";

const store = useBuildingStore();
const { t } = useI18n();
const { openToast, cancelToastOpen } = inject("app_toast");

const columns = computed(() => [
  {
    title: t("accountManagement.index"),
    key: "index",
  },
  {
    title: t("assetManagement.building"),
    key: "full_name",
    filter: true,
  },
  {
    title: t("accountManagement.operation"),
    key: "operation",
  },
]);

const dataSource = ref([]);
const loading = ref(false);

const getDataSource = async () => {
  loading.value = true;
  // const res = await getBuildings();
  // store.buildings = res.data;
  dataSource.value = store.buildings.map((d) => ({ ...d, key: d.building_guid }));
  loading.value = false;
};

onMounted(() => {
  getDataSource();
});

const formState = ref({
  full_name: "",
});

const openModal = (record) => {
  if (record.building_guid) {
    formState.value = { ...record };
  } else {
    formState.value = {
      full_name: "",
    };
  }
  build_modal.showModal();
};

const remove = async (building_guid) => {
  openToast("warning", t("msg.sure_to_delete"), "body", async () => {
    await cancelToastOpen();
    const res = await deleteBuildings(building_guid);
    if (res.isSuccess) {
      getDataSource();
      openToast("success", t("msg.delete_success"));
    } else {
      openToast("error", res.msg);
    }
  });
};
</script>

<template>
  <div class="flex justify-start items-center mt-10 mb-5">
    <h3 class="text-xl mr-5">{{ $t("assetManagement.building") }}</h3>
    <BuildingModal
      :formState="formState"
      :getData="getDataSource"
      :openModal="openModal"
    />
  </div>
  
  <Table :columns="columns" :dataSource="dataSource" :loading="loading">
    <template #bodyCell="{ record, column, index }">
      <template v-if="column.key === 'index'">{{ index + 1 }}</template>
      <template v-else-if="column.key === 'operation'">
        <button
          class="btn btn-sm btn-success text-white mr-2"
          @click.stop.prevent="() => openModal(record)"
        >
          {{ $t("button.edit") }}
        </button>
        <button
          class="btn btn-sm btn-error text-white"
          @click.stop.prevent="() => remove(record.building_guid)"
        >
          {{ $t("button.delete") }}
        </button>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

<style lang="css" scoped></style>
