<script setup>
import { getSideBar, getGraphData } from "@/apis/graph";
import { ref, computed, inject, watch, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import Menu from "@/components/customUI/Menu.vue";
const { t } = useI18n();
const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;
const { formState } = inject("asset_table_modal_form");
const columns = computed(() => [
  {
    title: t("assetManagement.index"),
    key: "index",
    width: 150,
  },
  {
    title: t("graphManagement.oriOrgName"),
    key: "oriOrgName",
  },
]);

const graphData = ref([]);
const menuData = ref([]);
const selectedId = ref(null);
const dataSource = ref([]);

const getMenuData = async () => {
  const res = await getSideBar();
  graphData.value = res.data;
  console.log(" graphData", graphData.value);
};

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

const buildMenuTree = (data) => {
  const map = new Map();
  const menu = [];

  data.forEach((item) => {
    map.set(item.id, { ...item, children: [] });
  });

  data.forEach((item) => {
    const parent = map.get(item.parent_id);
    if (item.parent_id === 0) {
      menu.push(map.get(item.id));
    } else {
      if (parent) {
        parent.children.push(map.get(item.id));
      }
    }
  });

  return menu;
};

const openModal = () => {
  asset_add_graph_item.showModal();
};

const onOk = () => {
  formState.value.graph_tree_id = selectedId.value;
  onCancel();
};

const onCancel = () => {
  selectedId.value = null;
  asset_add_graph_item.close();
};

const menuCheck = (id) => {
  selectedId.value = id;
};

watch(selectedId, (newId) => {
  if (newId) {
    getData(newId);
  } else {
    getData(formState.value.graph_tree_id);
  }
});

watch(
  formState,
  (newValue) => {
    if (newValue?.graph_tree_id) {
      selectedId.value = newValue?.graph_tree_id;
    } else {
      selectedId.value = null;
      dataSource.value = [];
    }
  },
  {
    immediate: true,
  }
);

onMounted(async () => {
  await getMenuData();
  menuData.value = buildMenuTree(graphData.value);
});
</script>

<template>
  <div class="flex flex-col mt-8 col-span-2">
    <div class="flex justify-between items-center">
      <span class="label-text-alt text-lg">{{
        $t("graphManagement.title")
      }}</span>
      <button
        type="button"
        class="btn btn-sm btn-success"
        @click.stop.prevent="openModal"
      >
        {{ $t("assetManagement.choose") }}
      </button>
    </div>
    <Table :columns="columns" :dataSource="dataSource" :withStyle="false">
      <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>
    </Table>
  </div>
  <Modal
    id="asset_add_graph_item"
    :title="t('graphManagement.title')"
    :onCancel="onCancel"
    :width="500"
  >
    <template #modalContent>
      <ul class="menu bg-base-200 rounded-box text-lg w-full mt-3">
        <li v-for="(item, index) in menuData" :key="index">
          <Menu
            :item="item"
            :selectedId="selectedId"
            :menuCheck="menuCheck"
          ></Menu>
        </li>
      </ul>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        {{ $t("button.cancel") }}
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        {{ $t("button.submit") }}
      </button>
    </template></Modal
  >
</template>

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