<script setup>
import Table from "@/components/customUI/Table.vue";
import VendorModal from "./VendorModal.vue";
import { getOperationCompanyList,deleteOperationCompany } from "@/apis/operation";
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("operation.vendor"),
    key: "name",
  },
  {
    title: t("operation.contact_person"),
    key: "contact_person",
  },
  {
    title: t("operation.phone"),
    key: "phone",
  },
  {
    title: t("operation.email"),
    key: "email",
  },
  {
    title: t("operation.created_at"),
    key: "created_at",
  },
  {
    title: t("operation.operation"),
    key: "operation",
    width: 250,
  },
]);

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

const getDataSource = async () => {
  loading.value = true;
  const res = await getOperationCompanyList();
  dataSource.value = res.data;
  loading.value = false;
};

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

const formState = ref({
  contact_person: "",
  email: "",
  name: "",
  phone: "",
  remark: "",
  tax_id_number: "",
  city: "",
  address: "",
});

const openModal = (record) => {
  if (record.id) {
    formState.value = { ...record };
  } else {
    formState.value = {
      contact_person: "",
      email: "",
      name: "",
      phone: "",
      remark: "",
      tax_id_number: "",
      city: "",
      address: "",
    };
  }
  company_modal.showModal();
};

const remove = async (id) => {
  openToast("warning", t("msg.sure_to_delete"), "body", async () => {
    await cancelToastOpen();
    const res = await deleteOperationCompany(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("assetManagement.company") }}</h3>
    <VendorModal
      :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>
