<script setup lang="ts">
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconDownloadBtn from "@/components/atoms/button/IconDownloadBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
import IconInfoBtn from "@/components/atoms/button/IconInfoBtn.vue";
import { computed, onMounted, ref, watch } from "vue";
import { storage } from "@/utils/storage";
import ViewComponent from "@/components/templates/trainingscript/ViewComponent.vue";
import TrainingScriptBaseDoalog from "@/components/atoms/organisms/TrainingScriptBaseDoalog.vue";
import AutoScriptDialog from "@/components/atoms/organisms/AutoScriptDialog.vue";
import ScriptCompileDialog from "@/components/atoms/organisms/ScriptCompileDialog.vue";
import { AttachmentsService } from "@/components/service/management/AttachmentsService";
import { commonStore } from "@/stores/commonStore";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const activeRefId = ref<number | null>(null);
const activeRefName = computed(() => String(route.query.refName ?? ""));
const store = commonStore();
const openView = ref(false);
const openModify = ref(false);

const username = ref<string>("");

type SearchType = "전체" | "제목" | "작성자";

const searchOptions = [
  { label: "전체", value: "전체" as SearchType },
  { label: "제목", value: "제목" as SearchType },
  { label: "작성자", value: "작성자" as SearchType },
];

const SEARCH_TYPE_MAP: Record<SearchType | "", "ALL" | "TITLE" | "AUTHOR"> = {
  "": "ALL",
  전체: "ALL",
  제목: "TITLE",
  작성자: "AUTHOR",
};

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

// 테이블 헤더 (맨 앞 컬럼은 선택 체크박스용)
const tableHeader = [
  { label: "", width: "4%", style: "word-break: keep-all;" },
  { label: "No", width: "5%", style: "word-break: keep-all;" },
  { label: "Title", width: "7%", style: "word-break: keep-all;" },
  { label: "File Name", width: "7%", style: "word-break: keep-all;" },
  { label: "File Path", width: "7%", style: "word-break: keep-all;" },
  { label: "Description", width: "7%", style: "word-break: keep-all;" },
  { label: "Created Data", width: "7%", style: "word-break: keep-all;" },
  { label: "Action", width: "7%", style: "word-break: keep-all;" },
];

const data = ref({
  params: {
    pageNum: 1,
    pageSize: 10,
    searchType: "전체" as SearchType,
    searchText: "",
  },
  results: [] as any[],
  totalElements: 0,
  pageLength: 0,
  modalMode: "" as "create" | "edit" | "setting" | "",
  selectedData: null as any,
  allSelected: false,
  selected: [] as Array<{ deviceKey: number }>,
  isCreateVisible: false,
  isUploadVisible: false,
  isAutoScriptVisible: false,
  isModalVisible: false,
  isConfirmDialogVisible: false,
  userOption: [] as any[],
});

function getRefIdFromRoute(q: any): number | null {
  const raw = q?.refId;
  const n = Number(raw);
  return Number.isFinite(n) && n > 0 ? n : null;
}

// 유저명
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;

    return u1.toString();
  } catch {
    return "";
  }
}

// 프로젝트 ID
const getProjectId = (): number => {
  const v = Number(localStorage.getItem("projectId"));
  return Number.isFinite(v) ? v : 0;
};

const fmtDate = (v?: string) =>
  v ? String(v).replace("T", " ").slice(0, 19) : "";

// 행 변환기(표 스키마에 맞춤)
const toRow = (a: any) => ({
  deviceKey: a.id,
  id: a.id,
  title: a.title ?? "",
  fileName: a.originalName ?? "",
  filePath: a.storagePath ?? "",
  description: a.description ?? "",
  createdData: fmtDate(a.regDt),

  modifiedData: "-",
});

const fetchList = async () => {
  const projectId = Number(localStorage.getItem("projectId"));
  if (!projectId) {
    console.warn("[TrainingScript] projectId 없음 — 프로젝트 먼저 선택");
    data.value.results = [];
    data.value.totalElements = 0;
    data.value.pageLength = 0;
    return;
  }

  const { pageNum, pageSize, searchType, searchText } = data.value.params;

  const mapped = SEARCH_TYPE_MAP[searchType] || "ALL";
  const keyword = (searchText || "").trim();
  const needLocalFilter = mapped !== "ALL" && keyword.length > 0;

  let reqPage = data.value.params.pageNum;
  let reqSize = data.value.params.pageSize;
  if (needLocalFilter) {
    reqPage = 0;
    reqSize = 1000;
  }

  const payload = {
    projectId,
    page: reqPage,
    size: reqSize,
    keyword,
    searchType: mapped,
    sortField: "id",
    sortDirection: "DESC",
    refType: "TRAINING_SCRIPT",
    // 그룹 미선택 시 refId=0으로 조회 (Auto Script 등 refId 0 저장 항목 포함)
    refId: activeRefId.value ?? 0,
  };

  try {
    const res = await AttachmentsService.search(payload as any);
    const result = res?.data ?? res;
    let list = result?.content ?? [];

    if (needLocalFilter) {
      const kw = keyword.toLowerCase();
      if (mapped === "TITLE") {
        list = list.filter((x: any) =>
          String(x?.title ?? "")
            .toLowerCase()
            .includes(kw),
        );
      } else if (mapped === "AUTHOR") {
        list = list.filter((x: any) =>
          String(x?.regUserId ?? "")
            .toLowerCase()
            .includes(kw),
        );
      }

      // 로컬 재페이지
      const uiSize = data.value.params.pageSize;
      const totalElements = list.length;
      const totalPages = Math.max(1, Math.ceil(totalElements / uiSize));
      const safePage = Math.min(Math.max(1, pageNum), totalPages);
      const start = (safePage - 1) * uiSize;
      const pageSlice = list.slice(start, start + uiSize);

      data.value.results = pageSlice.map(toRow);
      data.value.totalElements = totalElements;
      data.value.pageLength = totalPages;
      return;
    }

    // 서버 페이징 그대로 적용
    data.value.results = (list as any[]).map(toRow);
    data.value.totalElements = result?.totalElements ?? list.length;
    data.value.pageLength = result?.totalPages ?? 1;
  } catch (err) {
    console.error("[TrainingScript] 조회 에러:", err);
    data.value.results = [];
    data.value.totalElements = 0;
    data.value.pageLength = 1;
  }
};

/** 검색 실행 (페이지 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();
};

// 삭제/수정 버튼 등
const removeData = (value?: Array<{ deviceKey: number }>) => {
  const removeList = value ?? data.value.selected;
  if (!removeList || removeList.length === 0) return;

  const ids = removeList.map((x) => x.deviceKey);
  const removeOne = (id: number) =>
    AttachmentsService.delete(id).then((res) => {
      if (res.status < 200 || res.status >= 300) return Promise.reject(res);
    });

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

    fetchList();
    data.value.isConfirmDialogVisible = false;
    data.value.selected = [];
    data.value.allSelected = false;
  };

  // 단건/다건 처리
  if (ids.length === 1) {
    removeOne(ids[0])
      .then(() => {
        store.setSnackbarMsg({
          color: "success",
          text: "삭제되었습니다.",
          result: 200,
        });
        after();
      })
      .catch((err) => {
        console.error("삭제 실패:", err);
        store.setSnackbarMsg({
          color: "warning",
          text: "삭제 실패",
          result: 500,
        });
      });
  } else {
    Promise.all(ids.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 closeDetail = () => {
  openView.value = false;
};

async function downloadScript(item: any) {
  const objectName = item?.filePath || item?.storagePath;
  if (!objectName) {
    store.setSnackbarMsg({ color: "warning", text: "다운로드 경로가 없습니다.", result: 400 });
    return;
  }
  try {
    const res = await AttachmentsService.downloadFile(objectName);
    const ct = String(res.headers["content-type"] || "").toLowerCase();
    if (ct.includes("application/json")) {
      const text = await (res.data as Blob).text();
      try {
        const json = JSON.parse(text);
        throw new Error(json.message || text);
      } catch {
        throw new Error(text);
      }
    }
    const cd = res.headers["content-disposition"] || "";
    const mUtf8 = cd.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);
    const mStd = cd.match(/filename\s*=\s*(?:"([^"]+)"|([^;]+))/i);
    const filename =
      (mUtf8 && decodeURIComponent(mUtf8[1].trim())) ||
      (mStd && (mStd[1] || mStd[2])?.trim()) ||
      item?.fileName ||
      objectName.split(/[\\/]/).pop() ||
      "download";
    const blob = new Blob([res.data]);
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.setAttribute("download", filename);
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
    store.setSnackbarMsg({ color: "success", text: "다운로드되었습니다.", result: 200 });
  } catch (e) {
    console.error("[TrainingScript] 다운로드 실패:", e);
    store.setSnackbarMsg({ color: "warning", text: "다운로드에 실패했습니다.", result: 500 });
  }
}

const compileDialogOpen = ref(false);
const compileDialogItem = ref<{ deviceKey?: number; id?: number; title?: string; fileName?: string; filePath?: string } | null>(null);
function openCompileDialog(item: any) {
  compileDialogItem.value = item ? { deviceKey: item.deviceKey, id: item.id, title: item.title, fileName: item.fileName, filePath: item.filePath } : null;
  compileDialogOpen.value = true;
}
function onCompiled() {
  store.setSnackbarMsg({ color: "success", text: "스크립트 컴파일이 완료되었습니다.", result: 200 });
}

const openDetailModal = (selectedItem: any) => {
  data.value.selectedData = selectedItem;
  openView.value = true;
};

const openCreateModal = () => {
  data.value.modalMode = "create";
  data.value.selectedData = {
    username: username.value,
    projectId: getProjectId(),
    refId: activeRefId.value,
  };
  data.value.isCreateVisible = true;
};

const openModifyModal = (item: any) => {
  data.value.modalMode = "edit";
  data.value.selectedData = {
    id: item.deviceKey,
    title: item.title,
    description: item.description,
  };
  data.value.isCreateVisible = true;
};

const openAutoScriptModal = () => {
  data.value.isAutoScriptVisible = true;
};
const closeAutoScriptModal = () => {
  data.value.isAutoScriptVisible = false;
};
const openMergeScriptModal = async () => {
  const selected = data.value.selected;
  if (!selected || selected.length === 0) {
    store.setSnackbarMsg({
      color: "warning",
      text: "머지할 스크립트를 선택하세요.",
      result: 400,
    });
    return;
  }

  const projectId = getProjectId();
  if (!projectId) {
    store.setSnackbarMsg({
      color: "warning",
      text: "프로젝트를 먼저 선택하세요.",
      result: 400,
    });
    return;
  }

  const scriptIds = selected.map((x) => x.deviceKey);
  const defaultTitle = `merged-${scriptIds.join("-")}`;
  const title = window.prompt("머지 결과 스크립트 제목을 입력하세요.", defaultTitle);
  if (!title) {
    return;
  }

  try {
    const raw =
      storage?.get?.("autoflow-auth") ??
      storage?.getAuth?.() ??
      localStorage.getItem("autoflow-auth") ??
      null;
    const auth = typeof raw === "string" ? JSON.parse(raw) : raw;
    const userInfo = auth?.userInfo ?? auth?.userinfo ?? auth ?? {};
    const userId = userInfo.username ?? userInfo.id ?? "unknown";

    const payload = {
      scriptIds,
      title,
      description: "",
      refId: activeRefId.value ?? 0,
      refType: "TRAINING_SCRIPT",
      regUserId: String(userId),
      projectId,
    };

    const res = await AttachmentsService.mergeScripts(payload as any);
    const att = (res as any)?.data?.attachment ?? (res as any)?.attachment ?? null;

    store.setSnackbarMsg({
      color: "success",
      text: "Merge Script가 생성되었습니다.",
      result: 200,
    });

    if (att?.id) {
      // 새로 생성된 스크립트가 보이도록 첫 페이지로 이동 후 리프레시
      data.value.params.pageNum = 1;
    }
    fetchList();
  } catch (e: any) {
    console.error("[TrainingScript] Merge Script 실패:", e);
    const msg =
      e?.response?.data?.error ??
      e?.response?.data?.message ??
      e?.message ??
      "Merge Script 생성에 실패했습니다.";
    store.setSnackbarMsg({
      color: "warning",
      text: msg,
      result: e?.response?.status ?? 500,
    });
  }
};
// Auto Script 저장 후: 목록만 갱신 (현재 그룹이면 해당 그룹 refId로 저장되어 목록에 표시)
const onAutoScriptSaved = () => {
  fetchList();
};

const closeCreateModal = () => {
  data.value.isModalVisible = false;
  data.value.isCreateVisible = false;
  data.value.selectedData = null;
};

const closeModifyModal = () => {
  data.value.isModalVisible = false;
  data.value.isUploadVisible = false;
  data.value.selectedData = null;
};

const getSelectedAllData = () => {
  data.value.selected = data.value.allSelected
    ? data.value.results.map((item: any) => ({ deviceKey: item.deviceKey }))
    : [];
};
onMounted(() => {
  username.value = readUsernameFromStorage();
  activeRefId.value = getRefIdFromRoute(route.query);
  fetchList();
});
watch(
  () => route.query.refId,
  () => {
    activeRefId.value = getRefIdFromRoute(route.query);
    data.value.params.pageNum = 1;
    fetchList();
  },
);
</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>TrainingScript</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"
              >
                <!-- 스크립트의 totalElements 사용 -->
                <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
                class="d-flex align-center mr-3 mb-2 bg-shades-transparent"
              >
                <v-chip
                  v-if="activeRefId"
                  class="ml-2"
                  color="secondary"
                  variant="tonal"
                >
                  Filter: DataGroup {{ activeRefName }}
                </v-chip>
                <v-btn
                  v-if="activeRefId"
                  size="small"
                  variant="text"
                  @click="router.replace({ path: '/TrainingScriptGroup' })"
                >
                  필터 해제
                </v-btn>
              </v-sheet>
            </v-sheet>

            <v-sheet class="d-flex align-center justify-end mb-2">
              <v-btn color="info" class="mr-2" @click="openCreateModal"
                >Upload Script</v-btn
              >
              <v-btn color="info" class="mr-2" @click="openAutoScriptModal">Auto Script</v-btn>
              <v-btn color="info" @click="openMergeScriptModal">Merge Script</v-btn>
            </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"
                      >
                        <template v-if="i === 0">
                          <v-checkbox
                            v-model="data.allSelected"
                            density="compact"
                            hide-details
                            @change="getSelectedAllData"
                          />
                        </template>
                        <template v-else>
                          {{ item.label }}
                        </template>
                      </th>
                    </tr>
                  </thead>

                  <tbody class="text-body-2">
                    <tr
                      v-for="(item, i) in data.results"
                      :key="i"
                      class="text-center"
                    >
                      <td>
                        <v-checkbox
                          v-model="data.selected"
                          :value="{ deviceKey: item.deviceKey }"
                          density="compact"
                          hide-details
                        />
                      </td>
                      <td>
                        {{
                          data.totalElements -
                          ((data.params.pageNum - 1) * data.params.pageSize + i)
                        }}
                      </td>
                      <td>{{ item.title }}</td>
                      <td>{{ item.fileName }}</td>
                      <td>{{ item.filePath }}</td>
                      <td>{{ item.description }}</td>
                      <td>{{ item.createdData }}</td>

                      <td style="white-space: nowrap">
                        <v-tooltip location="bottom" text="스크립트 컴파일">
                          <template #activator="{ props: tooltipProps }">
                            <v-btn
                              v-bind="tooltipProps"
                              icon="mdi-hammer-wrench"
                              color="secondary"
                              density="comfortable"
                              elevation="0"
                              size="small"
                              class="ma-1"
                              @click="openCompileDialog(item)"
                            />
                          </template>
                        </v-tooltip>
                        <IconDownloadBtn @on-click="downloadScript(item)" />
                        <IconInfoBtn @on-click="openDetailModal(item)" />
                        <IconModifyBtn @on-click="openModifyModal(item)" />
                        <IconDeleteBtn
                          @on-click="
                            removeData([{ deviceKey: item.deviceKey }])
                          "
                        />
                      </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>
      <TrainingScriptBaseDoalog
        :edit-data="data.selectedData"
        :mode="data.modalMode"
        @close-modal="closeCreateModal"
        @saved="fetchList"
        :user-option="data.userOption"
      />
    </v-dialog>

    <!-- Auto Script 다이얼로그 (선택된 그룹 refId 전달 → 해당 그룹 목록에 저장) -->
    <v-dialog v-model="data.isAutoScriptVisible" max-width="720" persistent>
      <AutoScriptDialog
        :current-ref-id="activeRefId"
        @close-modal="closeAutoScriptModal"
        @generated="onAutoScriptSaved"
      />
    </v-dialog>

    <!-- 스크립트 컴파일 창 (로그 확인 후 컴파일 실행) -->
    <ScriptCompileDialog
      v-model="compileDialogOpen"
      :item="compileDialogItem"
      @compiled="onCompiled"
    />
  </div>

  <div class="w-100" v-else>
    <ViewComponent
      v-if="data.selectedData"
      :id="data.selectedData.deviceKey"
      @close="closeDetail"
    />
  </div>
</template>

<style scoped></style>
