<script setup>
import { getFIX_COL } from "../constant/OperationTableColumns";
import { defineProps, computed, inject, watch } from "vue";
import {
  deleteOperationRecord
} from "@/apis/operation";
import useSearchParam from "@/hooks/useSearchParam";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { openToast, cancelToastOpen } = inject("app_toast");
const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;
const { searchParams } = useSearchParam();

const { dataSource, openModal, updateEditRecord, search, tableLoading } =
  inject("operation_table");

const columns = computed(() =>
  getFIX_COL(t)
);

const changeData = (record) => {
  console.log("changeData", record);
  updateEditRecord(record);
  openModal(record.formId);
};

const deleteItem = async (id) => {
  openToast("warning", t("msg.sure_to_delete"), "body", async () => {
    await cancelToastOpen();
    let res;
    res = await deleteOperationRecord(id);
    if (res.isSuccess) {
      search(); 
      openToast("success",  t("msg.delete_success"));
    } else {
        openToast("error", res.msg);
    }
  });
};
</script>

<template>
  <Table :loading="tableLoading" :columns="columns" :dataSource="dataSource">
    <template #bodyCell="{ record, column, index }">
      <template v-if="column.key === 'lorf'">
        <span v-if="record.lorf?.length === 0"></span>
        <template v-else>
          <span class="flex flex-wrap gap-1">
            <a
              v-for="file in record.lorf"
              :href="`${FILE_BASEURL}/upload/operation/${
                file?.save_file_name
              }.${
                file?.ori_file_name.split('.')[
                  file?.ori_file_name.split('.').length - 1
                ]
              }`"
              target="_blank"
              class="mx-1"
            >
              <img
                :src="`${FILE_BASEURL}/upload/operation/${
                  file?.save_file_name
                }.${
                  file?.ori_file_name.split('.')[
                    file?.ori_file_name.split('.').length - 1
                  ]
                }`"
                class="w-14 h-14"
              />
            </a>
          </span>
        </template>
      </template>
      <template v-if="column.key === 'operation'">
        <button
          class="btn btn-sm btn-success text-white mr-2"
          @click.stop.prevent="() => changeData(record)"
        >
          {{ $t("button.edit") }}
        </button>
        <button
          class="btn btn-sm btn-error text-white"
          @click.stop.prevent="() => deleteItem(record.id)"
        >
          {{ $t("button.delete") }}
        </button>
      </template></template
    ></Table
  >
</template>

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