<script setup lang="ts">
import IconDeleteBtn from "@/components/atoms/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/atoms/button/IconModifyBtn.vue";
import IconSettingBtn from "@/components/atoms/button/IconSettingBtn.vue";
// import FormComponent from "@/components/device/FormComponent.vue";
import { onMounted, ref, watch } from "vue";
import ViewComponent from "@/components/templates/workflow/ViewComponent.vue";
import WorkflowsBaseDialog from "@/components/atoms/organisms/WorkflowsBaseDialog.vue";
import WorkflowsUploadDialog from "@/components/atoms/organisms/WorkflowsUploadDialog.vue";
import { AutoflowService } from "@/components/service/management/AutoflowService";
import { commonStore } from "@/stores/commonStore";
import IconInfoBtn from "@/components/atoms/button/IconInfoBtn.vue";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import tz from "dayjs/plugin/timezone";
const store = commonStore();

const openView = ref(false);
const tableHeader = [
  {
    label: "No",
    width: "5%",
    style: "word-break: keep-all;",
  },
  {
    label: "Workflow Name",
    width: "7%",
    style: "word-break: keep-all;",
  },

  {
    label: "Step Count",
    width: "7%",
    style: "word-break: keep-all;",
  },
  {
    label: "Config Progress",
    width: "7%",
    style: "word-break: keep-all;",
  },
  {
    label: "Kubeflow Status",
    width: "7%",
    style: "word-break: keep-all;",
  },
  {
    label: "Created DateTime",
    width: "7%",
    style: "word-break: keep-all;",
  },
  {
    label: "Action",
    width: "7%",
    style: "word-break: keep-all;",
  },
];

const searchOptions = [
  {
    searchType: "전체",
    searchText: "",
  },
  {
    searchType: "디바이스 별칭",
    searchText: "deviceAlias",
  },
  {
    searchType: "디바이스 키",
    searchText: "deviceKey",
  },
  {
    searchType: "사용자",
    searchText: "userId",
  },
  {
    searchType: "디바이스 이름",
    searchText: "deviceName",
  },
  {
    searchType: "디바이스 모델",
    searchText: "deviceModel",
  },
  {
    searchType: "디바이스 OS",
    searchText: "deviceOs",
  },
];

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

const data = ref({
  params: {
    pageNum: 1,
    pageSize: 10,
    searchType: "",
    searchText: "",
  },
  results: [],
  totalDataLength: 0,
  pageLength: 0,
  modalMode: "",
  selectedData: null,
  allSelected: false,
  selected: [],
  isCreateVisible: false,
  isUploadVisible: false,
  isModalVisible: false,
  isConfirmDialogVisible: false,
  userOption: [],
});

dayjs.extend(utc);
dayjs.extend(tz);

const KST = "Asia/Seoul";
const formatDateTime = (
  v?: string | number | Date,
  fmt = "YYYY-MM-DD HH:mm:ss",
) => (v ? dayjs(v).tz(KST).format(fmt) : "");

const getCodeList = () => {
  // UserService.search(data.value.params).then((d) => {
  //   if (d.status === 200) {
  //     data.value.userOption = d.data.userList;
  //   }
  // });
};

const toRow = (workflow: any, index: number, offset: number) => ({
  no: offset + index + 1,
  name: workflow.workflowName,
  description: workflow.workflowDescription,
  version: workflow.version,
  stepCount: workflow.stepCount,
  configProgress: workflow.configProgress,
  kubeflowStatus: workflow.kubeflowStatus,
  registDt: workflow.regDt,
  deviceKey: workflow.id,
});

const getData = () => {
  const params = data.value.params;
  const pageNum = params.pageNum;
  const pageSize = params.pageSize;
  const startIndex = (pageNum - 1) * pageSize;

  AutoflowService.getAll()
    .then((res) => {
      if (res.status !== 200) {
        console.error("워크플로우 조회 실패:", res);

        return;
      }
      const result = res.data;
      console.log(result);
      const rawList = Array.isArray(result) ? result : (result.content ?? []);
      const totalCount = Array.isArray(result)
        ? rawList.length
        : (result.totalElements ?? rawList.length);
      const currentPageList = Array.isArray(result)
        ? rawList.slice(startIndex, startIndex + pageSize)
        : rawList;

      data.value.results = currentPageList.map((w: any, i: number) =>
        toRow(w, i, startIndex),
      );
      data.value.totalDataLength = totalCount;

      setPaginationLength();
    })
    .catch((err) => {
      console.error("워크플로우 조회 에러:", err);
    });
};
const setPaginationLength = () => {
  const total = data.value.totalDataLength || 0;
  const pageSize = data.value.params.pageSize || 10;
  data.value.pageLength =
    total % pageSize === 0 ? total / pageSize : Math.ceil(total / pageSize);
};

const saveData = (formData: any) => {
  if (data.value.modalMode === "create") {
    AutoflowService.add(formData)
      .then((res) => {
        if (res.status === 200 || res.status === 201) {
          data.value.isCreateVisible = false;
          store.setSnackbarMsg({
            text: "등록 되었습니다.",
            result: 200,
            color: "success",
          });
          changePageNum(1); // 첫 페이지로
        } else {
          store.setSnackbarMsg({
            text: "등록 실패",
            result: 500,
            color: "warning",
          });
        }
      })
      .catch((err) => {
        console.error("등록 에러:", err);
        store.setSnackbarMsg({
          text: "등록 중 오류가 발생했습니다.",
          result: 500,
          color: "error",
        });
      })
      .finally(() => {
        getData();
      });
  } else {
    // 수정
    const id =
      Number(formData?.id) ??
      Number(formData?.deviceKey) ??
      Number(data.value.selectedData?.deviceKey) ??
      Number(data.value.selectedData?.id);

    if (!id) {
      store.setSnackbarMsg({
        text: "수정할 ID가 없습니다.",
        result: 500,
        color: "error",
      });
      return;
    }

    AutoflowService.update(id, formData)
      .then((res) => {
        if (res.status === 200) {
          data.value.isCreateVisible = false;
          store.setSnackbarMsg({
            text: "수정 되었습니다.",
            result: 200,
            color: "success",
          });
          changePageNum(data.value.params.pageNum); // 현재 페이지 유지
        } else {
          store.setSnackbarMsg({
            text: "수정 실패",
            result: 500,
            color: "warning",
          });
        }
      })
      .catch((err) => {
        console.error("수정 에러:", err);
        store.setSnackbarMsg({
          text: "수정 중 오류가 발생했습니다.",
          result: 500,
          color: "error",
        });
      })
      .finally(() => {
        getData(); // 목록 새로고침
      });
  }
};

const removeData = (value) => {
  const removeList = value ?? data.value.selected;
  if (!removeList || removeList.length === 0) return;

  const ids = removeList.map((x) => x.deviceKey);

  const remove = (id) =>
    AutoflowService.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;
    }
    getData();

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

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

const handleRemoveData = () => {
  if (data.value.selected.length === 0) {
    // store.setSnackbarMsg({
    //   text: "삭제 할 데이터를 선택해주세요. ",
    //   result: 500,
    // });
    return;
  }
  if (data.value.allSelected || data.value.selected.length !== 1) {
    data.value.isConfirmDialogVisible = true;
    return;
  }
  //리스트로 삭제 할때
  removeData(undefined);
};
const closeDetail = () => {
  openView.value = false;
};
const changePageNum = (page) => {
  data.value.params.pageNum = page;
  getData();
};
const openDetailModal = (selectedItem) => {
  data.value.selectedData = selectedItem;
  openView.value = true;
};
const openModifyModal = (item: any) => {
  console.log("[openModifyModal] row =", item);
  data.value.selectedData = {
    id: item.deviceKey,
    workflowName: item.name,
    workflowDescription: item.description,
  };

  data.value.modalMode = "edit";
  data.value.isCreateVisible = true;
};

const openCreateModal = () => {
  data.value.selectedData = null;
  data.value.modalMode = "create";
  data.value.isCreateVisible = true;
};

const openUploadModal = () => {
  data.value.selectedData = null;
  data.value.modalMode = "upload";
  data.value.isUploadVisible = true;
};
const closeCreateModal = () => {
  data.value.isModalVisible = false;
  data.value.isCreateVisible = false;
};
const closeUploadModal = () => {
  data.value.isModalVisible = false;
  data.value.isUploadVisible = false;
};

const getSelectedAllData = () => {
  data.value.selected = data.value.allSelected
    ? data.value.results.map((item) => {
        return {
          deviceKey: item.deviceKey,
        };
      })
    : [];
};
watch(
  () => data.value.isCreateVisible,
  (now, prev) => {
    if (prev && !now) getData();
  },
);

watch(
  () => data.value.isUploadVisible,
  (now, prev) => {
    if (prev && !now) getData();
  },
);
onMounted(() => {
  getData();
  getCodeList();
});
</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 class="text-primary">Workflows</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="searchType"
                  item-value="searchText"
                  hide-details
                ></v-select>
              </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="changePageNum(1)"
                ></v-text-field>
              </v-responsive>

              <div class="ml-3">
                <v-btn
                  size="large"
                  color="primary"
                  :rounded="5"
                  @click="changePageNum(1)"
                >
                  <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.totalDataLength.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="changePageNum(1)"
                  ></v-select>
                </v-responsive>
              </v-sheet>
            </v-sheet>
            <v-sheet class="justify-end mb-2">
              <!-- <v-btn color="info" class="mr-4" @click="openUploadModal"
                >Upload Workflow
              </v-btn> -->
              <v-btn color="info" @click="openCreateModal"
                >Create Workflow
              </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"
                  col-md-12
                  col-12
                  overflow-x-auto
                >
                  <colgroup>
                    <col style="width: 5%" />
                    <col
                      v-for="(item, i) in tableHeader"
                      :key="i"
                      :style="`width:${item.width}`"
                    />
                  </colgroup>
                  <thead>
                    <tr>
                      <th>
                        <v-checkbox
                          v-model="data.allSelected"
                          style="min-width: 36px"
                          :indeterminate="data.allSelected === true"
                          hide-details
                          @change="getSelectedAllData"
                        ></v-checkbox>
                      </th>
                      <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>
                        <v-checkbox
                          v-model="data.selected"
                          hide-details
                          :value="{
                            deviceKey: item.deviceKey,
                          }"
                        ></v-checkbox>
                      </td>
                      <td>{{ item.no }}</td>
                      <td>{{ item.name }}</td>
                      <td>{{ item.stepCount }}</td>
                      <td>{{ item.configProgress }}</td>
                      <td>{{ item.kubeflowStatus }}</td>
                      <td>{{ formatDateTime(item.registDt) }}</td>
                      <td style="white-space: nowrap">
                        <IconInfoBtn @on-click="openDetailModal(item)" />
                        <!-- <IconSettingBtn /> -->
                        <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-pagination>
              </v-card-actions>
            </v-col>
          </v-card>
        </v-card>
      </v-card>
    </v-container>
    <v-dialog v-model="data.isCreateVisible" max-width="800" persistent>
      <WorkflowsBaseDialog
        :key="data.modalMode + String(data.selectedData?.deviceKey ?? '')"
        :edit-data="data.selectedData"
        :mode="data.modalMode"
        @close-modal="closeCreateModal"
        @handle-data="saveData"
        :user-option="data.userOption"
      />
    </v-dialog>
    <v-dialog v-model="data.isUploadVisible" max-width="800" persistent>
      <WorkflowsUploadDialog
        :edit-data="data.selectedData"
        :mode="data.modalMode"
        @close-modal="closeUploadModal"
        @handle-data="saveData"
        :user-option="data.userOption"
      />
    </v-dialog>
  </div>

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

<style scoped></style>
