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

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

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

const loading = ref(false);

const formState = ref({
  id: 0,
  name: "",
});

const openModal = (record) => {  
  if (record.id) {
    formState.value = { ...record };
  } else {
    formState.value = {
      id: 0,
      name: "",
    };
  }
  dept_modal.showModal();
};

const remove = async (id) => {
  openToast("warning", t("msg.sure_to_delete"), "body", async () => {
    await cancelToastOpen();
    const res = await deleteDepartmentItem(id);
    if (res.isSuccess) {
      storeBuild.fetchDepartmentList();
      openToast("success", t("msg.delete_success"));
    } else {
      openToast("error", res.msg);
    }
  });
};
onMounted(() => {
  storeBuild.fetchDepartmentList();
});
</script>

<template>
  <div class="flex justify-start items-center mt-10 mb-5">
    <h3 class="text-xl mr-5">{{ $t("assetManagement.department") }}</h3>
    <DeptModal
      :formState="formState"
      :openModal="openModal"
    />
  </div>
  <Table :columns="columns" :dataSource="storeBuild.deptList" :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.id)"
        >
          {{ $t("button.delete") }}
        </button>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

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