<script setup lang="ts">
import IconDeleteBtn from "@/components/button/IconDeleteBtn.vue";
import IconModifyBtn from "@/components/button/IconModifyBtn.vue";
// import FormComponent from "@/components/device/FormComponent.vue";
import { onMounted, ref, watch } from "vue";

// const store = commonStore();

const tableHeader = [
  {
    label: "Run Name",
    width: "20%",
    style: "word-break: keep-all;",
  },
  {
    label: "Status",
    width: "20%",
    style: "word-break: keep-all;",
  },
  {
    label: "Duration",
    width: "20%",
    style: "word-break: keep-all;",
  },
  {
    label: "Pipeline",
    width: "20%",
    style: "word-break: keep-all;",
  },
  {
    label: "Start Time",
    width: "20%",
    style: "word-break: keep-all;",
  },
];
const experimentInfo = ref({
  experimentName: "Baseline Model Training",
  projectName: "배터리 상태 예측 모델 프로젝트",
  createdDate: "2025-02-06",
  createdId: "ADMIN_001",
  description: "기본 모델 구조로 학습 성능 측정",
});

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

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

const getData = () => {
  const params = { ...data.value.params };
  if (params.searchType === "" || params.searchText === "") {
    delete params.searchType;
    delete params.searchText;
  }
  data.value.results = [
    {
      name: "run-batch32-lr0.001",
      status: "Succeeded",
      Duration: "0:00:21",
      configProgress: "0/2",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-06-10T00:00:00Z",
    },
    {
      name: "run-batch64-lr0.001",
      status: "Failed",
      Duration: "0:00:21",
      configProgress: "1/3",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-06-09T00:00:00Z",
    },
    {
      name: "run-batch32-lr0.0005",
      status: "Succeeded",
      Duration: "0:00:21",
      configProgress: "0/3",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-06-01T00:00:00Z",
    },
    {
      name: "run-batch64-lr0.0005",
      status: "Running",
      Duration: "0:00:21",
      configProgress: "1/3",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-05-29T00:00:00Z",
    },
    {
      name: "run-augmented-data",
      status: "Succeeded",
      Duration: "0:00:21",
      configProgress: "0/3",
      Pipeline: "baseline_train_pipeline",
      registDt: "2025-05-31T00:00:00Z",
    },
  ];
  data.value.totalDataLength = 5;
  // DeviceService.search(params).then((d) => {
  //   if (d.status === 200) {
  //     data.value.results = d.data.deviceList;
  //     data.value.totalDataLength = d.data.totalCount;
  //     setTimeout(() => {
  //       setPaginationLength();
  //     }, 200);
  //   } else {
  //     store.setSnackbarMsg({
  //       text: "디바이스 조회 실패",
  //       color: "error",
  //     });
  //   }
  // });
  // DeviceService.search().then((d) => {
  //   data.value.totalDataLength = d.data.totalCount;
  //   setTimeout(() => {
  //     setPaginationLength();
  //   }, 200);
  // });
};

// const setPaginationLength = () => {
//   if (data.value.totalDataLength % data.value.params.pageSize === 0) {
//     data.value.pageLength =
//       data.value.totalDataLength / data.value.params.pageSize;
//   } else {
//     data.value.pageLength = Math.ceil(
//       data.value.totalDataLength / data.value.params.pageSize,
//     );
//   }
// };

const saveData = (formData) => {
  if (data.value.modalMode === "create") {
    // DeviceService.add(formData).then((d) => {
    //   if (d.status === 200) {
    //     data.value.isModalVisible = false;
    //     store.setSnackbarMsg({
    //       text: "등록 되었습니다.",
    //       result: 200,
    //     });
    //     changePageNum(1);
    //   } else {
    //     store.setSnackbarMsg({
    //       text: d,
    //       result: 500,
    //     });
    //   }
    // });
  } else {
    // DeviceService.update(formData.deviceKey, formData).then((d) => {
    //   if (d.status === 200) {
    //     data.value.isModalVisible = false;
    //     store.setSnackbarMsg({
    //       text: "수정 되었습니다.",
    //       result: 200,
    //     });
    //     changePageNum();
    //   } else {
    //     store.setSnackbarMsg({
    //       text: d,
    //       result: 500,
    //     });
    //   }
    // });
  }
};

const removeData = (value) => {
  let removeList = value ? value : data.value.selected;
  const remove = (code) => {
    // return DeviceService.delete(code).then((d) => {
    //   if (d.status !== 200) {
    //     store.setSnackbarMsg({
    //       text: d,
    //       result: 500,
    //     });
    //   }
    // });
  };

  if (removeList.length === 1) {
    remove(removeList[0].deviceKey).then(() => {
      // store.setSnackbarMsg({
      //   text: "삭제되었습니다.",
      //   result: 200,
      // });
      changePageNum();
      data.value.isConfirmDialogVisible = false;
      data.value.selected = [];
      data.value.allSelected = false;
    });
  } else {
    Promise.all(removeList.map((item) => remove(item.deviceKey))).finally(
      () => {
        // store.setSnackbarMsg({
        //   text: "모두 삭제되었습니다.",
        //   result: 200,
        // });
        changePageNum();
        data.value.isConfirmDialogVisible = false;
        data.value.selected = [];
        data.value.allSelected = false;
      },
    );
  }
};

const changePageNum = (page) => {
  data.value.params.pageNum = page;
  getData();
};

const emit = defineEmits<{
  (e: "close"): void;
}>();

onMounted(() => {
  getData();
  getCodeList();
});
</script>

<template>
  <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 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">View Details</div>
          </div>
        </v-card-item>
      </v-card>

      <v-card flat class="bordered-box mb-6 w-100 rounded-lg pa-8">
        <v-card-title class="grey lighten-4 py-2 px-4">
          <span class="font-weight-bold">Experiment Information</span>
        </v-card-title>
        <v-card-text class="px-4 pb-4 pt-2 d-flex justify-center">
          <tbody>
            <tr>
              <th class="text-center pa-3">Experiment Name</th>
              <td class="text-left" colspan="3">
                {{ experimentInfo.experimentName }}
              </td>
            </tr>
            <tr>
              <th class="text-center pa-3">Project Name</th>
              <td class="text-left" colspan="3">
                {{ experimentInfo.projectName }}
              </td>
            </tr>
            <tr>
              <th class="text-center pa-3">Created Date</th>
              <td class="text-left">{{ experimentInfo.createdDate }}</td>
              <th class="text-center pa-3">Created ID</th>
              <td class="text-left">{{ experimentInfo.createdId }}</td>
            </tr>
            <tr>
              <th class="text-center pa-3">Description</th>
              <td class="text-left" colspan="3">
                {{ experimentInfo.description }}
              </td>
            </tr>
          </tbody>
        </v-card-text>
      </v-card>
      <v-card flat class="bg-shades-transparent w-100">
        <v-card class="rounded-lg pa-8">
          <v-card-title class="grey lighten-4 py-2 px-4">
            <span class="font-weight-bold">Runs</span>
          </v-card-title>
          <v-col cols="12">
            <v-sheet>
              <v-table
                density="comfortable"
                fixed-header
                height="300"
                col-md-12
                col-12
                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.name }}</td>
                    <td>{{ item.status }}</td>
                    <td>{{ item.Duration }}</td>
                    <td>{{ item.Pipeline }}</td>
                    <td>{{ item.registDt }}</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="getData"
              ></v-pagination>
            </v-card-actions>
          </v-col>
          <v-sheet class="d-flex justify-end mb-2">
            <v-btn color="primary" @click="emit('close')"> Back to List </v-btn>
          </v-sheet>
        </v-card>
      </v-card>
    </v-card>
  </v-container>
</template>

<style scoped>
.v-card-text {
  width: 100% !important;
  border-collapse: collapse;
  /* 전체 테이블 1px 테두리 */
}

.v-card-text th {
  font-size: 20px;
  min-width: 400px;
  border: 1px solid rgba(255, 255, 255, 0.12);
  background-color: rgba(255, 255, 255, 0.05);
  font-weight: 600;
  text-align: center;
  white-space: nowrap;
}
.v-card-text td {
  font-size: 16px;
  min-width: 600px;
  padding: 12px 16px;
  text-align: left;
  border: 1px solid rgba(255, 255, 255, 0.12);
}
.v-card-text tr:nth-child(odd) {
  background-color: rgba(255, 255, 255, 0.02);
}
</style>
