<script setup lang="ts">
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconInfoBtn from "@/components/atoms/button/IconInfoBtn.vue";
import { onMounted, onBeforeUnmount, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { storage } from "@/utils/storage";
import ViewComponent from "@/components/templates/run/executions/ViewComponent.vue";
import ExperimentCreateDialog from "@/components/atoms/organisms/ExperimentCreateDialog.vue";
import { KubeflowService } from "@/components/service/management/KubeflowService";
import { commonStore } from "@/stores/commonStore";
import { KubeflowRunService } from "@/components/service/management/KubeflowRunService";
import IconDownloadBtn from "@/components/atoms/button/IconDownloadBtn.vue";
import { WorkflowService } from "@/components/service/management/WorkflowService";

const store = commonStore();
const route = useRoute();
const router = useRouter();

const openView = ref(false);
const execSelected = ref<any>(null);
/** runId 쿼리로 열기 처리 완료 여부 (재처리 방지) */
const openedRunIdFromQuery = ref<string | null>(null);
const username = ref<string>("");
const experimentNameMap = ref<Record<string, string>>({});
const pipelineNameMap = ref<Record<string, string>>({});

const tableHeader = [
  { label: "No", width: "5%", style: "word-break: keep-all;" },
  { label: "Execution Name", width: "20%", style: "word-break: keep-all;" },
  { label: "Status", width: "10%", style: "word-break: keep-all;" },
  { label: "Duration", width: "10%", style: "word-break: keep-all;" },
  { label: "Experiment", width: "15%", style: "word-break: keep-all;" },
  { label: "Workflow", width: "15%", style: "word-break: keep-all;" },
  { label: "Start Time", width: "15%", style: "word-break: keep-all;" },
  { label: "Registry Status", width: "10%", style: "word-break: keep-all;" },
  { label: "Action", width: "10%", style: "word-break: keep-all;" },
];

type SearchType = "전체" | "제목";
const searchOptions = [
  { label: "전체", value: "전체" as SearchType },
  { label: "제목", value: "제목" as SearchType },
];
const SEARCH_TYPE_MAP: Record<SearchType | "", "ALL" | "TITLE"> = {
  "": "ALL",
  전체: "ALL",
  제목: "TITLE",
};

const pageSizeOptions = [
  { text: "10 페이지", value: 10 },
  { text: "50 페이지", value: 50 },
  { text: "100 페이지", value: 100 },
];

const data = ref({
  params: {
    pageNum: 1,
    pageSize: 10,
    searchType: "전체" as SearchType,
    searchText: "",
    experimentId: "",
  },
  results: [] as any[],
  totalElements: 0,
  pageLength: 0,
  modalMode: "" as "create" | "edit" | "",
  selectedData: null as any,
  isCreateVisible: false,
});

// ---------- NEW: 상태/시간 표준화 유틸 ----------
function pick<T = any>(obj: any, keys: string[]): T | undefined {
  for (const k of keys) {
    const v = obj?.[k];
    if (v !== undefined && v !== null && v !== "") return v as T;
  }
  return undefined;
}
function normTime(v: any): string | undefined {
  if (!v) return undefined;
  const d = new Date(v);
  return isNaN(d.getTime()) ? undefined : d.toISOString();
}
function normalizeRun(raw: any) {
  const stateRaw =
    pick<string>(raw, [
      "state",
      "status",
      "lifecycle_state",
      "lifecycleState",
      "lifecycleStage", // MLflow
      "phase", // K8s 스타일
    ]) ?? "";

  const createdAt =
    normTime(
      pick(raw, ["createdAt", "startTime", "startedAt", "start_time"]),
    ) ?? undefined;

  const finishedAt =
    normTime(
      pick(raw, [
        "finishedAt",
        "finished_at",
        "endTime",
        "end_time",
        "completedAt",
        "completed_at",
        "terminateTime",
      ]),
    ) ?? undefined;

  return { stateRaw, createdAt, finishedAt };
}

function toUiStatusByRaw(
  raw: any,
): "Succeeded" | "Failed" | "Running" | "Pending" {
  const { stateRaw, finishedAt } = normalizeRun(raw);
  const s = String(stateRaw || "").toUpperCase();

  if (
    s.includes("SUCCEED") ||
    s.includes("SUCCESS") ||
    s.includes("FINISH") || // FINISHED
    s.includes("COMPLETE") || // COMPLETED
    s === "DONE" ||
    s === "OK"
  )
    return "Succeeded";

  if (
    s.includes("FAIL") ||
    s.includes("ERROR") ||
    s.includes("CANCEL") ||
    s.includes("KILL") ||
    s.includes("TERMINAT") ||
    s.includes("ABORT")
  )
    return "Failed";

  if (s.includes("RUN") || s.includes("ACTIVE") || s.includes("EXECUT"))
    return "Running";

  if (!s && finishedAt) return "Succeeded";

  if (s.includes("PEND") || s.includes("QUEUE") || s.includes("SCHED"))
    return "Pending";

  return "Pending";
}
// -------------------------------------------------

async function resolveExperimentNamesWithApi(ids: Array<string | number>) {
  const targets = Array.from(
    new Set(
      (ids || [])
        .map((x) => String(x))
        .filter((id) => id && experimentNameMap.value[id] == null),
    ),
  );
  if (!targets.length) return;

  await Promise.all(
    targets.map(async (id) => {
      try {
        const res = await KubeflowService.experimentData(id);
        const body = res?.data ?? res ?? {};
        const name =
          body.display_name ?? body.name ?? body.experiment_name ?? String(id);
        experimentNameMap.value[id] = name;
      } catch {
        experimentNameMap.value[id] = String(id);
      }
    }),
  );
}

async function resolvePipelineNamesWithApi(ids: Array<string | number>) {
  const targets = Array.from(
    new Set(
      (ids || [])
        .map((x) => String(x))
        .filter((id) => id && pipelineNameMap.value[id] == null),
    ),
  );
  if (!targets.length) return;

  await Promise.all(
    targets.map(async (id) => {
      try {
        const res = await WorkflowService.pipelineIdName(id);
        const body = res?.data ?? res ?? {};
        const name =
          body.displayName ?? body.display_name ?? body.name ?? String(id);
        pipelineNameMap.value[id] = name;
      } catch {
        pipelineNameMap.value[id] = String(id);
      }
    }),
  );
}

function readUsernameFromStorage(): string {
  try {
    const raw =
      storage?.get?.("autoflow-auth") ??
      storage?.getAuth?.() ??
      localStorage.getItem("autoflow-auth") ??
      null;
    const auth = typeof raw === "string" ? JSON.parse(raw) : raw;
    const u1 = auth?.userInfo?.username;
    const u2 = auth?.username;
    const u3 = auth?.userInfo?.userName;
    const u4 = auth?.userInfo?.email?.split?.("@")?.[0];
    return (u1 || u2 || u3 || u4 || "").toString();
  } catch {
    return "";
  }
}
const getProjectId = (): number => {
  const v = Number(localStorage.getItem("projectId"));
  return Number.isFinite(v) ? v : 0;
};

const toRow = (r: any, no: number) => {
  const expId = r.experimentId ?? r.experiment_id ?? r.experiment?.id;
  const expName =
    (expId && experimentNameMap.value[String(expId)]) ??
    r.experiment?.displayName ??
    r.experiment?.name ??
    "-";

  const pipelineId =
    r.pipelineId ?? r.pipelineVersionId ?? r.pipeline?.id ?? r.pipeline_id;
  const wfName =
    (pipelineId && pipelineNameMap.value[String(pipelineId)]) ??
    r.pipeline?.displayName ??
    r.pipeline?.name ??
    "-";

  const { createdAt: createdIso, finishedAt: finishedIso } = normalizeRun(r);

  const fmt = (iso?: string) => {
    if (!iso) return "-";
    const d = new Date(iso);
    const yyyy = d.getFullYear();
    const MM = String(d.getMonth() + 1).padStart(2, "0");
    const dd = String(d.getDate()).padStart(2, "0");
    const hh = String(d.getHours()).padStart(2, "0");
    const mi = String(d.getMinutes()).padStart(2, "0");
    return `${yyyy}-${MM}-${dd} ${hh}:${mi}`;
  };

  const fmtDuration = (startIso?: string, endIso?: string) => {
    if (!startIso || !endIso) return "-";
    const ms = new Date(endIso).getTime() - new Date(startIso).getTime();
    if (!isFinite(ms) || ms < 0) return "-";
    const s = Math.floor(ms / 1000);
    const h = Math.floor(s / 3600);
    const m = Math.floor((s % 3600) / 60);
    const sec = s % 60;
    const pad = (n: number) => String(n).padStart(2, "0");
    return `${h}:${pad(m)}:${pad(sec)}`;
  };

  return {
    no,
    name: r.displayName ?? r.name ?? r.runId ?? "(no name)",
    status: toUiStatusByRaw(r),
    duration: fmtDuration(createdIso, finishedIso),
    expName,
    workflow: wfName,
    startTime: fmt(createdIso),
    registryStatus: r.storageState ?? "-",
    run_id: r.runId ?? r.run_id,
    raw: r,
  };
};

// --- [추가] 로컬 매칭 유틸: 제목/작성자/전체 ---
function includes(hay: any, needle: string) {
  if (!hay) return false;
  return String(hay).toLowerCase().includes(needle.toLowerCase());
}
function matchBySearchType(rowRaw: any, mapped: "ALL" | "TITLE", kw: string) {
  if (!kw) return true;

  // 제목 후보들
  const titleFields = [
    rowRaw.displayName,
    rowRaw.name,
    rowRaw.runName,
    rowRaw.title,
    rowRaw.pipeline?.displayName,
    rowRaw.pipeline?.name,
  ];

  if (mapped === "TITLE") {
    return titleFields.some((v) => includes(v, kw));
  }

  // ALL: 제목/작성자 + 기타 설명, 태그까지 포괄
  const extraFields = [
    rowRaw.description,
    rowRaw.desc,
    rowRaw.tags,
    rowRaw.tagString,
  ];
  return [...titleFields, ...extraFields].some((v) => includes(v, kw));
}

async function fetchList() {
  const { pageNum, pageSize, searchType, searchText } = data.value.params;
  const mapped = SEARCH_TYPE_MAP[searchType] || "ALL";
  const keyword = (searchText || "").trim();

  // ✅ 여러 서버 구현과 호환되도록 alias를 같이 보냄
  const payload: any = {
    projectId: getProjectId(),
    page: pageNum - 1, // 0-based
    size: pageSize,
    sortField: "createdAt",
    sortDirection: "DESC",

    // --- keyword aliases ---
    keyword,
    searchKeyword: keyword,
    query: keyword,
    q: keyword,
    search_text: keyword,
    searchText: keyword,

    // --- type aliases ---
    searchType: mapped,
    type: mapped,
    filterType: mapped,
  };

  try {
    const res = await KubeflowRunService.search(payload);
    const result = res?.data ?? res;

    let list: any[] = [];
    let totalElements: number | undefined;
    let totalPages: number | undefined;
    let isServerPaged = false;

    if (Array.isArray(result)) list = result;
    else if (Array.isArray(result?.data)) list = result.data;
    else if (Array.isArray(result?.content)) {
      list = result.content;
      totalElements = result.totalElements;
      totalPages = result.totalPages;
      isServerPaged = true;
    } else if (Array.isArray(result?.runs)) list = result.runs;

    // 💡 서버가 검색을 안 해줬을 경우 대비: 클라이언트 필터
    if (keyword) {
      list = list.filter((raw) => matchBySearchType(raw, mapped, keyword));
      // 서버가 totalElements를 내려줬더라도, 클라이언트에서 다시 줄였으므로 덮어씌움
      totalElements = list.length;
      totalPages = Math.ceil(list.length / pageSize);
      isServerPaged = false;
    }

    // 최신순 정렬 (서버 미적용 대비)
    list.sort((a, b) => {
      const ta = new Date(
        a.createdAt ||
          a.lastUpdateTime ||
          a.scheduledAt ||
          a.finishedAt ||
          a.startTime ||
          0,
      ).getTime();
      const tb = new Date(
        b.createdAt ||
          b.lastUpdateTime ||
          b.scheduledAt ||
          b.finishedAt ||
          b.startTime ||
          0,
      ).getTime();

      if (tb !== ta) return tb - ta;
      const aid = a.id ?? a.runId ?? a.run_id ?? a.name ?? "";
      const bid = b.id ?? b.runId ?? b.run_id ?? b.name ?? "";
      return String(bid).localeCompare(String(aid));
    });

    // 이름 매핑 미리 채우기
    const expIds = list
      .map((r) => r.experimentId ?? r.experiment_id ?? r.experiment?.id)
      .filter(Boolean);
    await resolveExperimentNamesWithApi(expIds);

    const pipeIds = list
      .map(
        (r) =>
          r.pipelineId ??
          r.pipelineVersionId ??
          r.pipeline?.id ??
          r.pipeline_id,
      )
      .filter(Boolean);
    await resolvePipelineNamesWithApi(pipeIds);

    // 페이지닝 (No: 1부터가 아닌 전체 기준 역순 번호, 삭제 후에도 중복 없이 유일하게 매김)
    if (!isServerPaged) {
      const total =
        typeof totalElements === "number" ? totalElements : list.length;
      const pages = Math.max(1, Math.ceil(total / pageSize));
      const safePage = Math.min(Math.max(1, pageNum), pages);
      const start = (safePage - 1) * pageSize;
      const slice = list.slice(start, start + pageSize);

      const rawStartNo = total - (safePage - 1) * pageSize;
      const startNo = Math.max(rawStartNo, slice.length);
      data.value.results = slice.map((r, i) =>
        toRow(r, Math.max(startNo - i, 1)),
      );
      data.value.totalElements = total;
      data.value.pageLength = pages;
    } else {
      const te =
        typeof totalElements === "number" ? totalElements : list.length;
      const rawStartNo = te - (pageNum - 1) * pageSize;
      const startNo = Math.max(rawStartNo, list.length);
      data.value.results = list.map((r, i) =>
        toRow(r, Math.max(startNo - i, 1)),
      );
      data.value.totalElements = te;
      data.value.pageLength =
        typeof totalPages === "number"
          ? Math.max(1, totalPages)
          : Math.max(1, Math.ceil((te || 0) / pageSize));
    }
  } catch (err) {
    console.error("[Executions] 조회 에러:", err);
    data.value.results = [];
    data.value.totalElements = 0;
    data.value.pageLength = 1;
  }

  // 상세 모달이 열려 있으면 선택된 실행의 최신 상태로 experimentInfo 갱신 (상태 표시 반영)
  if (openView.value && execSelected.value) {
    const runId =
      execSelected.value.run_id ??
      execSelected.value.raw?.runId ??
      execSelected.value.raw?.id;
    if (runId != null) {
      const fresh = data.value.results.find(
        (row: any) =>
          (row.run_id ?? row.raw?.runId ?? row.raw?.id) === runId,
      );
      if (fresh) execSelected.value = fresh;
    }
  }

  // Workflow Run 실행 후 runId 쿼리로 이동한 경우: 해당 실행 상세(Compare 등)를 바로 열기
  const runIdFromQuery = route.query.runId as string | undefined;
  if (runIdFromQuery && openedRunIdFromQuery.value !== runIdFromQuery) {
    void tryOpenRunFromQuery();
  }
}

/** 쿼리 runId가 있으면 해당 Run을 목록에서 찾아 상세 뷰로 열거나, 단건 조회로 열기 */
async function tryOpenRunFromQuery() {
  const runId = route.query.runId as string | undefined;
  if (!runId || openedRunIdFromQuery.value === runId) return;

  const row = data.value.results.find(
    (r: any) => (r.run_id ?? r.raw?.runId ?? r.raw?.id) === runId,
  );
  if (row) {
    openedRunIdFromQuery.value = runId;
    execSelected.value = row;
    openView.value = true;
    router.replace({ name: "Executions", query: {} });
    return;
  }
  try {
    const res = await KubeflowRunService.singleData(runId);
    const entity = res?.data ?? res;
    if (!entity?.runId && !entity?.run_id) return;
    await resolveExperimentNamesWithApi(
      [entity.experimentId ?? entity.experiment_id].filter(Boolean),
    );
    await resolvePipelineNamesWithApi(
      [entity.pipelineId ?? entity.pipeline_id].filter(Boolean),
    );
    const built = toRow(entity, 1);
    openedRunIdFromQuery.value = runId;
    execSelected.value = built;
    openView.value = true;
    router.replace({ name: "Executions", query: {} });
  } catch {
    // Run이 아직 DB에 없을 수 있음; 1페이지에 최신 목록이 보인 상태로 둠
  }
}

// 검색/페이지 조작
const doSearch = () => {
  data.value.params.pageNum = 1;
  fetchList();
};
const changePageNum = (page: number) => {
  data.value.params.pageNum = page;
  fetchList();
};
const changePageSize = (size: number) => {
  data.value.params.pageSize = size;
  data.value.params.pageNum = 1;
  fetchList();
};

// 삭제 (백엔드 DELETE /api/kubeflow/runs/{runId} 호출, Workflows 삭제와 동일 방식)
const removeData = (value: Array<{ deviceKey: string | number }>) => {
  const runIds = (value || []).map((x) => String(x.deviceKey));
  if (runIds.length === 0) return;

  const removeOne = (runId: string) =>
    KubeflowRunService.delete(runId).then((res) => {
      if (res.status < 200 || res.status >= 300) return Promise.reject(res);
    });

  const after = () => {
    if (
      runIds.length >= data.value.results.length &&
      data.value.params.pageNum > 1
    )
      data.value.params.pageNum -= 1;
    fetchList();
  };

  if (runIds.length === 1) {
    removeOne(runIds[0])
      .then(() =>
        store.setSnackbarMsg({
          color: "success",
          text: "삭제되었습니다.",
          result: 200,
        }),
      )
      .catch((err) => {
        console.error("삭제 실패:", err);
        store.setSnackbarMsg({
          color: "warning",
          text: "삭제 실패",
          result: 500,
        });
      })
      .finally(after);
  } else {
    Promise.all(runIds.map(removeOne))
      .then(() =>
        store.setSnackbarMsg({
          color: "success",
          text: "모두 삭제되었습니다.",
          result: 200,
        }),
      )
      .catch((err) => {
        console.error("일부 삭제 실패:", err);
        store.setSnackbarMsg({
          color: "warning",
          text: "일부 삭제 실패",
          result: 500,
        });
      })
      .finally(after);
  }
};

// 상세 모달
const openInfoModal = (item: any) => {
  execSelected.value = item;
  openView.value = true;
};
const closeView = () => {
  openView.value = false;
};
const onSaved = () => fetchList();
const openCreateModal = () => {
  data.value.modalMode = "create";
  data.value.selectedData = {
    username: username.value,
    projectId: getProjectId(),
  };
  data.value.isCreateVisible = true;
};
const closeModal = () => {
  data.value.isCreateVisible = false;
  data.value.selectedData = null;
};

const POLL_INTERVAL_MS = 10 * 1000;
let listPollTimerId: ReturnType<typeof setInterval> | null = null;
function startListPolling() {
  if (listPollTimerId != null) return;
  listPollTimerId = setInterval(() => fetchList(), POLL_INTERVAL_MS);
}
function stopListPolling() {
  if (listPollTimerId != null) {
    clearInterval(listPollTimerId);
    listPollTimerId = null;
  }
}

onMounted(() => {
  username.value = readUsernameFromStorage();
  if (route.query.runId) {
    data.value.params.pageNum = 1;
  }
  fetchList();
  startListPolling();
});
onBeforeUnmount(() => stopListPolling());
</script>

<template>
  <div class="w-100" v-if="!openView">
    <v-container fluid class="h-100 pa-5 d-flex flex-column align-center">
      <v-card
        flat
        class="bg-shades-transparent d-flex flex-column align-center justify-center w-100"
      >
        <v-card flat class="bg-shades-transparent w-100">
          <v-card-item class="text-h5 font-weight-bold pt-0 pa-5 pl-0">
            <div class="d-flex flex-row justify-start align-center">
              <div>Executions</div>
            </div>
          </v-card-item>
        </v-card>

        <v-card flat class="bg-shades-transparent w-100">
          <!-- 검색 -->
          <v-card flat class="bg-shades-transparent mb-4">
            <div class="d-flex justify-center flex-wrap align-center">
              <v-responsive
                max-width="180"
                min-width="180"
                class="mr-3 mt-3 mb-3"
              >
                <v-select
                  v-model="data.params.searchType"
                  label="검색조건"
                  density="compact"
                  :items="searchOptions"
                  item-title="label"
                  item-value="value"
                  hide-details
                />
              </v-responsive>

              <v-responsive min-width="540" max-width="540">
                <v-text-field
                  v-model="data.params.searchText"
                  label="검색어"
                  density="compact"
                  clearable
                  required
                  class="mt-3 mb-3"
                  hide-details
                  @keyup.enter="doSearch"
                />
              </v-responsive>

              <div class="ml-3">
                <v-btn
                  size="large"
                  color="primary"
                  :rounded="5"
                  @click="doSearch"
                >
                  <v-icon>mdi-magnify</v-icon>
                </v-btn>
              </div>
            </div>
          </v-card>

          <!-- 상단 툴바 -->
          <v-sheet
            class="bg-shades-transparent d-flex flex-wrap align-center mb-2"
          >
            <v-sheet class="d-flex flex-wrap me-auto bg-shades-transparent">
              <v-sheet
                class="d-flex align-center mr-3 mb-2 bg-shades-transparent"
              >
                <v-chip color="primary"
                  >총 {{ data.totalElements.toLocaleString() }}개</v-chip
                >
              </v-sheet>
              <v-sheet class="bg-shades-transparent">
                <v-responsive max-width="140" min-width="140" class="mb-2">
                  <v-select
                    v-model="data.params.pageSize"
                    density="compact"
                    :items="pageSizeOptions"
                    item-title="text"
                    item-value="value"
                    variant="outlined"
                    color="primary"
                    hide-details
                    @update:model-value="changePageSize"
                  />
                </v-responsive>
              </v-sheet>
            </v-sheet>
          </v-sheet>

          <!-- 목록 -->
          <v-card class="rounded-lg pa-8">
            <v-col cols="12">
              <v-sheet>
                <v-table
                  density="comfortable"
                  fixed-header
                  height="625"
                  overflow-x-auto
                >
                  <colgroup>
                    <col
                      v-for="(item, i) in tableHeader"
                      :key="i"
                      :style="`width:${item.width}`"
                    />
                  </colgroup>
                  <thead>
                    <tr>
                      <th
                        v-for="(item, i) in tableHeader"
                        :key="i"
                        class="text-center font-weight-bold"
                        :style="item.style"
                      >
                        {{ item.label }}
                      </th>
                    </tr>
                  </thead>
                  <tbody class="text-body-2">
                    <tr
                      v-for="(item, i) in data.results"
                      :key="i"
                      class="text-center"
                    >
                      <td>{{ item.no }}</td>
                      <td
                        class="text-truncate text-primary execution-name-link"
                        @click="openInfoModal(item)"
                      >
                        {{ item.name }}
                      </td>
                      <td>
                        <v-icon v-if="item.status === 'Succeeded'" color="green"
                          >mdi-check-circle</v-icon
                        >
                        <v-icon v-else-if="item.status === 'Failed'" color="red"
                          >mdi-close-circle</v-icon
                        >
                        <v-progress-circular
                          v-else-if="item.status === 'Running'"
                          indeterminate
                          size="18"
                          width="2"
                          color="info"
                        />
                        <v-icon
                          v-else-if="item.status === 'Pending'"
                          color="grey"
                          class="mdi-spin"
                        >
                          mdi-loading
                        </v-icon>
                        <v-icon v-else color="grey">mdi-help-circle</v-icon>
                      </td>
                      <td>{{ item.duration }}</td>
                      <td>{{ item.expName }}</td>
                      <td>{{ item.workflow }}</td>
                      <td>{{ item.startTime }}</td>
                      <td>{{ item.registryStatus }}</td>
                      <td style="white-space: nowrap">
                        <IconInfoBtn @on-click="openInfoModal(item)" />
                        <IconDeleteBtn
                          @on-click="
                            removeData([
                              {
                                deviceKey:
                                  item.run_id ?? item.raw?.runId ?? item.raw?.id,
                              },
                            ])
                          "
                        />
                      </td>
                    </tr>
                  </tbody>
                </v-table>
              </v-sheet>

              <v-card-actions class="text-center mt-8 justify-center">
                <v-pagination
                  v-model="data.params.pageNum"
                  :length="data.pageLength"
                  :total-visible="10"
                  color="primary"
                  rounded="circle"
                  @update:model-value="changePageNum"
                />
              </v-card-actions>
            </v-col>
          </v-card>
        </v-card>
      </v-card>
    </v-container>

    <!-- 생성 다이얼로그 -->
    <v-dialog v-model="data.isCreateVisible" max-width="600" persistent>
      <ExperimentCreateDialog
        :edit-data="data.selectedData"
        :mode="data.modalMode"
        @close-modal="closeModal"
        @saved="onSaved"
        @handle-data="() => {}"
      />
    </v-dialog>
  </div>

  <div class="w-100" v-else>
    <ViewComponent
      v-if="openView"
      :experiment-info="execSelected"
      :onClose="closeView"
    />
  </div>
</template>

<style scoped>
.execution-name-link {
  cursor: pointer;
}
.execution-name-link:hover {
  text-decoration: underline;
}
</style>
