<script setup>
import Table from "@/components/customUI/Table.vue";
import ElecTypeModal from "./ElecTypeModal.vue";
import { getElecTypeList, deleteElecTypeItem } from "@/apis/asset";
import { onMounted, ref, inject, computed } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { openToast, cancelToastOpen } = inject("app_toast");

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

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

const getDataSource = async () => {
  loading.value = true;
  const res = await getElecTypeList();
  dataSource.value = res.data.map((d) => ({ ...d, key: d.id }));
  loading.value = false;
};

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

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

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

const remove = async (id) => {
  openToast("warning", t("msg.sure_to_delete"), "body", async () => {
    await cancelToastOpen();
    const res = await deleteElecTypeItem(id);
    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("energy.electricity_classification") }}</h3>
    <ElecTypeModal
      :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.id)"
        >
          {{ $t("button.delete") }}
        </button>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

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