<script setup>
import { getGraphData, delGraphData } from "@/apis/graph";
import { inject, ref, watch, computed } from "vue";
import useSearchParams from "@/hooks/useSearchParam";
import GraphModal from "./GraphModal.vue";
import { downloadExcelByHref } from "@/util/downloadExcel";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { openToast, cancelToastOpen } = inject("app_toast");
const { sidebar_data } = inject("current_dir");
const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;

const columns = computed(() => [
  {
    title: t("graphManagement.index"),
    key: "index",
    width: 100,
  },
  {
    title: t("graphManagement.folder_path"),
    key: "folderPath",
  },
  {
    title: t("graphManagement.oriOrgName"),
    key: "oriOrgName",
  },
  {
    title: t("graphManagement.operation"),
    key: "operation",
    width: 250,
  },
]);

const dataSource = ref([]);
const { searchParams } = useSearchParams();

const getData = async (id) => {
  const res = await getGraphData(id);
  if (res.isSuccess) {
    dataSource.value = res.data.map((d) => ({ ...d, key: d.id, parentId: d.layer_id }));
  }
};

const { current_dir } = inject("current_dir");

const editRecord = ref(null);
const updateEditRecord = (data) => {
  editRecord.value = data;
};

const delRecord = async (id, hard_delete = false, recover_delete = false) => {
  if (recover_delete) {
    const res = await delGraphData(id, false, recover_delete);
    if (res.isSuccess) {
      getData(0);
    } else {
      openToast("error", res.msg);
    }
  }else{
    const confirmMessage = hard_delete
    ? t("msg.sure_to_delete_permanent")
    : t("msg.sure_to_delete");
    openToast("warning", confirmMessage, "body", async () => {
      await cancelToastOpen();
      const res = await delGraphData(id,hard_delete,false);
      if (res.isSuccess) {
        getData(parseInt(searchParams.value.id > 0 ? parseInt(searchParams.value.id) : 0));
        openToast("success", t("msg.delete_success"));
      } else {
        openToast("error", res.msg);
      }
    });
  }
};

watch(
  () => searchParams,
  (newVal) => {
    if (newVal.value.id) {
      updateEditRecord(null);
      getData(newVal.value.id > 0 ? parseInt(newVal.value.id) : 0);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

const getFolderPath = (id, nodes = sidebar_data.value) => {
  for (const node of nodes) {
    if (node.id === id) return node.remark;
    if (node.children && node.children.length > 0) {
      const childPath = getFolderPath(id, node.children);
      if (childPath) return `${childPath}`;
    }
  }
  return null;
};

const downloadFile = async (record) => {
  console.log(record);
  downloadExcelByHref(
    `${FILE_BASEURL}/upload/graph_manage/${record.oriSavName}`,
    record.oriOrgName
  );
};
</script>

<template>
  <div>
    <div class="flex items-center mb-3">
      <font-awesome-icon
        :icon="['fas', 'trash-alt']"
        class="text-rose-600 text-3xl me-4 my-2"
        v-if="searchParams.id < 0"
      /> 
      <GraphModal
        :editRecord="editRecord"
        :updateEditRecord="updateEditRecord"
        :getTableData="getData"
        v-else
      />
      <h1 class="text-xl">
        {{ searchParams.id < 0 ? $t("graphManagement.staging_area") : current_dir?.remark }}
      </h1>
    </div>
    <Table :columns="columns" :dataSource="dataSource">
      <template #bodyCell="{ record, column, index }">
        <template v-if="column.key === 'index'">{{ index + 1 }}</template>
        <template v-else-if="column.key === 'oriOrgName'">
          <a
            :href="`${FILE_BASEURL}/upload/graph_manage/${record.oriSavName}`"
            target="_blank"
            class="btn-link no-underline hover:no-underline :focus:outline-0"
          >
            {{ record.oriOrgName }}
          </a>
        </template>
        <template v-else-if="column.key == 'folderPath'" >
          {{ getFolderPath(record.parentId) || $t("graphManagement.no_path") }}
        </template>
        <template v-else-if="column.key === 'operation'">
          <button
            class="btn btn-sm btn-success text-white mr-2"
            @click.stop.prevent="() => downloadFile(record)"
            v-if="searchParams.id > 0"
          >
            {{ $t("button.download") }}
          </button>
          <button
            class="btn btn-sm btn-info text-white mr-2"
            @click.stop.prevent="
              () => {
                updateEditRecord(record);
              }
            "
            v-if="searchParams.id > 0"
          >
            {{ $t("button.edit") }}
          </button>
          <button
            class="btn btn-sm btn-info text-white mr-2"
            @click.stop.prevent="
              () => {
                delRecord(record.id, false, true);
              }
            "
            v-else
          >
            {{ $t("button.restore") }}
          </button>
          <button
            class="btn btn-sm btn-error text-white"
           @click.stop.prevent="() => delRecord(record.id, searchParams.id > 0 ? false : true)"
          >
            {{ $t("button.delete") }}
          </button>
        </template>
        <template v-else>
          {{ record[column.key] }}
          <!-- <button class="text-secondary no-underline border-0">
          </button> -->
        </template>
      </template>
    </Table>
  </div>
</template>

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