<template>
  <div>
    <v-snackbar
      color="success"
      v-model="snackbarSuccess"
      right="right"
      :timeout="3000"
      top="top"
    >
      {{ successMsg }}
      <v-btn color="white" flat @click="snackbarSuccess = false"> Close </v-btn>
    </v-snackbar>
    <v-snackbar
      color="error"
      v-model="snackbarError"
      right="right"
      :timeout="3000"
      top="top"
    >
      {{ errorMsg }}
      <v-btn color="white" flat @click="snackbarError = false"> Close </v-btn>
    </v-snackbar>
    <v-dialog v-model="dialogConfirmation" width="600">
      <v-card>
        <v-card-title class="headline grey lighten-2" primary-title>
          KONFIRMASI VOID ORDER {{ selectedPatient.labNumber }}
        </v-card-title>

        <v-card-text>
          Apakah anda yakin melakukan void order
          <span style="font-weight: bold;">
            {{ selectedPatient.labNumber }}-{{ selectedPatient.patientName }}
          </span>
          ?
          <v-textarea
            class="mt-3"
            v-model="note"
            auto-grow
            :disabled="loading"
            box
            label="Alasan *"
            rows="1"
          ></v-textarea>
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn
            color="red"
            :disabled="loading"
            flat
            :loading="loading"
            @click="dialogConfirmation = false"
          >
            Batal
          </v-btn>
          <v-btn
            color="primary"
            :loading="loading"
            :disabled="loading"
            flat
            @click="voidOrder()"
          >
            Yakin
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="showProgress" persistent width="400">
      <v-card>
        <v-card-title class="subtitle-1">
          {{ currentFileName }}
        </v-card-title>
        <v-card-text>
          <template v-if="typeof downloadProgress === 'number'">
            <div class="mb-2">
              Downloaded
              {{
                progressEvent ? formatFileSize(progressEvent.loaded) : "0 Bytes"
              }}
            </div>
            <div class="mb-2">Progress : {{ downloadProgress }}%</div>
            <v-progress-linear
              :value="downloadProgress"
              color="primary"
              height="25"
              class="text-center"
            >
              <template v-slot:default>
                <strong style="color: white;" class="text-center ml-3"
                  >{{ downloadProgress }}%</strong
                >
              </template>
            </v-progress-linear>
          </template>
          <template v-else>
            <div class="mb-2">
              {{ downloadProgress }}
            </div>
            <v-progress-linear indeterminate color="primary" height="25">
              <template v-slot:default>
                <strong>{{ downloadProgress }}</strong>
              </template>
            </v-progress-linear>
          </template>
        </v-card-text>
      </v-card>
    </v-dialog>
    <v-layout class="fill-height" column>
      <v-layout align-center column>
        <v-toolbar dark color="primary">
          <v-toolbar-title class="white--text">DOWNLOAD BACKUP</v-toolbar-title>

          <v-spacer></v-spacer>
        </v-toolbar>
        <v-card style="width: 100%;" class="mb-2 pa-2 searchbox">
          <v-layout row wrap>
            <!-- <v-flex xs3 class="">
              <v-menu
                v-model="menuFormDateStart"
                :close-on-content-click="false"
                :nudge-right="40"
                lazy
                transition="scale-transition"
                offset-y
                full-width
                max-width="290px"
                min-width="290px"
              >
                <template v-slot:activator="{ on }">
                  <v-text-field
                    class="mr-2 mb-2"
                    v-model="formatedStartDate"
                    label="Tanggal Awal"
                    outline
                    hide-details
                    readonly
                    v-on="on"
                    @blur="deFormatedDate(formatedStartDate)"
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="startDate"
                  no-title
                  @input="menuFormDateStart = false"
                ></v-date-picker>
              </v-menu>
            </v-flex>
            <v-flex xs3 class="">
              <v-menu
                v-model="menuFormDateEnd"
                :close-on-content-click="false"
                :nudge-right="40"
                lazy
                transition="scale-transition"
                offset-y
                full-width
                max-width="290px"
                min-width="290px"
              >
                <template v-slot:activator="{ on }">
                  <v-text-field
                    class="mr-2 mb-2"
                    v-model="formatedEndDate"
                    label="Tanggal Akhir"
                    outline
                    readonly
                    hide-details
                    v-on="on"
                    @blur="deFormatedDate(formatedEndDate)"
                  ></v-text-field>
                </template>
                <v-date-picker
                  v-model="endDate"
                  no-title
                  @input="menuFormDateEnd = false"
                ></v-date-picker>
              </v-menu>
            </v-flex>
            <v-flex xs3>
              <v-text-field
                label="Cari..."
                outline
                class="mr-2 mb-2"
                hide-details
                v-model="search"
              ></v-text-field>
            </v-flex> -->
            <v-flex xs3>
              <v-select
                class="mini-select"
                :items="type"
                label="Tipe"
                hide
                hide-details
                v-model="selectedType"
                @input="changeType()"
                outline
              ></v-select>
            </v-flex>
          </v-layout>
        </v-card>
      </v-layout>
      <v-card style="overflow-y: scroll; height: 65vh;" class="fill-height">
        <v-data-table
          :loading="loading"
          :items="listData"
          :headers="headers"
          class="v-table elevation-1"
          hide-actions
        >
          <template v-slot:headers="props">
            <tr>
              <th
                v-for="header in props.headers"
                :width="header.width"
                :class="header.class"
              >
                {{ header.text }}
              </th>
            </tr>
          </template>
          <v-progress-linear
            v-slot:progress="loading"
            color="blue"
            :indeterminate="true"
          ></v-progress-linear>
          <template v-slot:items="props">
            <tr @click="redirectUploadDocument(props.item)">
              <td class="py-2">
                {{ props.item.last_modified }}
              </td>
              <td class="py-2">
                {{ props.item.name }}
              </td>
              <td class="py-2">
                {{ props.item.size }}
              </td>
              <td class="py-2 text--center">
                <div
                  class="text-center"
                  style="width: 100%; display: flex; justify-content: center;"
                >
                  <v-btn
                    @click="downloadFile(props.item.full_path)"
                    color="info"
                    :loading="loading"
                    :disabled="loading"
                    >DOWNLOAD</v-btn
                  >
                </div>
              </td>
            </tr>
          </template>
        </v-data-table>
      </v-card>
      <v-card class="pa-2">
        <!-- <div class="text-xs-left">
          <v-pagination v-model="page" :length="total"></v-pagination>
        </div> -->
      </v-card>
    </v-layout>
  </div>
</template>
<style scoped>
  .searchbox .v-input.v-text-field .v-input__slot {
    min-height: 60px;
  }
  .searchbox .v-btn {
    min-height: 60px;
  }
  table.v-table tbody td,
  table.v-table tbody th {
    height: 40px;
  }

  table.v-table thead tr {
    height: 40px;
  }
  .scroll-container {
    scroll-padding: 50px 0 0 50px;
  }

  ::-webkit-scrollbar {
    width: 7px;
  }

  /* this targets the default scrollbar (compulsory) */

  ::-webkit-scrollbar-track {
    background-color: #73baf3;
  }

  /* the new scrollbar will have a flat appearance with the set background color */

  ::-webkit-scrollbar-thumb {
    background-color: #2196f3;
  }

  /* this will style the thumb, ignoring the track */

  ::-webkit-scrollbar-button {
    background-color: #0079da;
  }

  /* optionally, you can style the top and the bottom buttons (left and right for horizontal bars) */

  ::-webkit-scrollbar-corner {
    background-color: black;
  }
</style>
<script>
  // const { data } = require("./onePriceHeader.vue");

  module.exports = {
    //   components: {
    //     "one-dialog-info": httpVueLoader("../../common/oneDialogInfo.vue"),
    //     "one-dialog-alert": httpVueLoader("../../common/oneDialogAlert.vue"),
    //   },
    mounted() {
      this.$store.dispatch("patient/getListData");
      // this.$store.dispatch("patient/search");
    },
    methods: {
      changeType() {
        let type = this.selectedType;
        console.log(type);
        if (type === "cpone") {
          this.listData = this.tmpListData.cpone ?? [];
        }
        if (type === "log") {
          this.listData = this.tmpListData.cpone_log ?? [];
        }
      },
      voidOrder() {
        if (this.note.trim() == "") {
          alert("Harus mengisi alasan ..... ");
          return;
        }
        this.$store.dispatch("patient/voidOrder");
      },
      async downloadFile(path) {
        try {
          // Validasi input
          if (!path) {
            this.errorMsg = "Path file tidak valid";
            this.snackbarError = true;
            return;
          }

          this.currentFileName = path.split("/").pop();
          let url =
            window.location.protocol +
            "//" +
            window.location.host +
            "/one-api/tools/downloadbackup/file";
          let token = one_token();

          this.loading = true;
          this.showProgress = true;
          this.downloadProgress = 0;
          this.progressEvent = null;

          try {
            // Dapatkan ukuran file
            const headResponse = await axios({
              method: "HEAD",
              url: url,
              headers: {
                Authorization: `Bearer ${token}`,
                "Content-Type": "application/json",
              },
              data: {
                path: path,
                token: one_token(),
              },
            });

            this.totalSize = parseInt(
              headResponse.headers["content-length"] || 0
            );

            // Lakukan download
            const response = await axios({
              method: "POST",
              url: url,
              data: {
                path: path,
                token: one_token(),
              },
              headers: {
                Authorization: `Bearer ${token}`,
                "Content-Type": "application/json",
              },
              responseType: "blob",
              onDownloadProgress: (progressEvent) => {
                this.progressEvent = progressEvent;
                const total = progressEvent.total || this.totalSize;

                if (total) {
                  const progress = Math.round(
                    (progressEvent.loaded * 100) / total
                  );
                  this.downloadProgress = progress;
                } else {
                  const loadedMB = this.formatFileSize(progressEvent.loaded);
                  this.downloadProgress = `${loadedMB} terdownload`;
                }
              },
            });

            // Validasi response
            if (!response.data || response.data.size === 0) {
              throw new Error("File download gagal atau file kosong");
            }

            const blob = response.data;
            const contentDisposition = response.headers["content-disposition"];
            let filename = path.split("/").pop();

            if (contentDisposition) {
              const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(
                contentDisposition
              );
              if (matches && matches[1]) {
                filename = matches[1].replace(/['"]/g, "");
              }
            }

            // Validasi blob
            if (!(blob instanceof Blob)) {
              throw new Error("Format file tidak valid");
            }

            const url_download = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url_download;
            link.download = filename;
            document.body.appendChild(link);
            link.click();

            // Cleanup
            link.remove();
            window.URL.revokeObjectURL(url_download);
          } catch (error) {
            throw error; // Re-throw error untuk ditangkap oleh catch block luar
          }
        } catch (error) {
          console.error("Error downloading file:", error);

          // Handle specific errors
          if (error.response) {
            // Server returned error response
            switch (error.response.status) {
              case 401:
                this.errorMsg = "Tidak memiliki akses, silahkan login ulang";
                break;
              case 404:
                this.errorMsg = "File tidak ditemukan";
                break;
              case 403:
                this.errorMsg = "Tidak memiliki izin untuk mengakses file";
                break;
              default:
                this.errorMsg = `Error server: ${error.response.status}`;
            }
          } else if (error.request) {
            this.errorMsg = "Tidak dapat terhubung ke server";
          } else {
            this.errorMsg =
              error.message || "Terjadi kesalahan saat mengunduh file";
          }

          // Reset immediate saat error
          this.showProgress = false;
          this.downloadProgress = 0;
          this.snackbarError = true;
        } finally {
          this.loading = false;
          this.progressEvent = null;
          this.totalSize = 0;
          setTimeout(() => {
            this.showProgress = false;
            this.downloadProgress = 0;
          }, 1000);
        }
      },
      openDialogConfirm(data) {
        this.note = "";
        this.selectedPatient = data;
        this.dialogConfirmation = true;
      },
      redirectUploadDocument(data) {
        // noreg=R2407150001&id=322
        let link =
          window.location.protocol +
          "//" +
          window.location.hostname +
          "/one-ui/" +
          this.url +
          "?noreg=" +
          data.labNumber +
          "&id=" +
          data.orderID;

        // window.open(link, "_blank");
      },
      formatDate(date) {
        if (!date) return null;

        const [year, month, day] = date.split("-");
        return `${day}-${month}-${year}`;
      },
      deFormatedDate(date) {
        if (!date) return null;

        const [day, month, year] = date.split("-");
        return `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
      },
      formatFileSize(bytes) {
        if (bytes === 0) return "0 Bytes";

        const k = 1024;
        const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
        const i = Math.floor(Math.log(bytes) / Math.log(k));

        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
      },
    },
    computed: {
      url: {
        get() {
          return this.$store.state.patient.url;
        },
        set(val) {
          this.$store.commit("patient/update_url", val);
        },
      },
      listData: {
        get() {
          return this.$store.state.patient.listData;
        },
        set(val) {
          this.$store.commit("patient/update_listData", val);
        },
      },
      tmpListData: {
        get() {
          return this.$store.state.patient.tmpListData;
        },
        set(val) {
          this.$store.commit("patient/update_tmpListData", val);
        },
      },
      type: {
        get() {
          return this.$store.state.patient.type;
        },
        set(val) {
          this.$store.commit("patient/update_type", val);
        },
      },
      selectedType: {
        get() {
          return this.$store.state.patient.selectedType;
        },
        set(val) {
          this.$store.commit("patient/update_selectedType", val);
        },
      },
      selectedPatient: {
        get() {
          return this.$store.state.patient.selectedPatient;
        },
        set(val) {
          this.$store.commit("patient/update_selectedPatient", val);
        },
      },
      total: {
        get() {
          return this.$store.state.patient.total;
        },
        set(val) {
          this.$store.commit("patient/update_total", val);
        },
      },
      dialogConfirmation: {
        get() {
          return this.$store.state.patient.dialogConfirmation;
        },
        set(val) {
          this.$store.commit("patient/update_dialogConfirmation", val);
        },
      },
      note: {
        get() {
          return this.$store.state.patient.note;
        },
        set(val) {
          this.$store.commit("patient/update_note", val);
        },
      },
      loading: {
        get() {
          return this.$store.state.patient.loading;
        },
        set(val) {
          this.$store.commit("patient/update_loading", val);
        },
      },
      search: {
        get() {
          return this.$store.state.patient.search;
        },
        set(val) {
          this.$store.commit("patient/update_search", val);
          this.$store.commit("patient/update_page", 1);

          this.$store.dispatch("patient/search");
        },
      },
      setupList: {
        get() {
          return this.$store.state.patient.setupList;
        },
        set(val) {
          this.$store.commit("patient/update_setupList", val);
        },
      },
      selectedSetup: {
        get() {
          return this.$store.state.patient.selectedSetup;
        },
        set(val) {
          this.$store.commit("patient/update_selectedSetup", val);
          this.$store.commit("patient/update_startDate", val.Mgm_McuStartDate);
          this.$store.commit("patient/update_endDate", val.Mgm_McuEndDate);
          this.$store.commit("patient/update_page", 1);

          this.$store.dispatch("patient/search");
        },
      },

      status() {
        return this.$store.state.patient.status;
      },

      selectedStatus: {
        get() {
          return this.$store.state.patient.selectedStatus;
        },
        set(val) {
          this.$store.commit("patient/update_selectedStatus", val);
          this.$store.commit("patient/update_page", 1);

          this.$store.dispatch("patient/search");
        },
      },
      orderList: {
        get() {
          return this.$store.state.patient.orderList;
        },
        set(val) {
          this.$store.commit("patient/update_orderList", val);
        },
      },
      successMsg: {
        get() {
          return this.$store.state.patient.successMsg;
        },
        set(val) {
          this.$store.commit("patient/update_successMsg", val);
        },
      },
      errorMsg: {
        get() {
          return this.$store.state.patient.errorMsg;
        },
        set(val) {
          this.$store.commit("patient/update_errorMsg", val);
        },
      },
      snackbarError: {
        get() {
          return this.$store.state.patient.snackbarError;
        },
        set(val) {
          this.$store.commit("patient/update_snackbarError", val);
        },
      },
      snackbarSuccess: {
        get() {
          return this.$store.state.patient.snackbarSuccess;
        },
        set(val) {
          this.$store.commit("patient/update_snackbarSuccess", val);
        },
      },
      page: {
        get() {
          return this.$store.state.patient.page;
        },
        set(val) {
          this.$store.commit("patient/update_page", val);
          this.$store.dispatch("patient/search");
        },
      },
      startDate: {
        get() {
          return this.$store.state.patient.startDate;
        },
        set(val) {
          this.$store.commit("patient/update_startDate", val);
          this.$store.dispatch("patient/search");
          this.$store.commit("patient/update_page", 1);
        },
      },
      endDate: {
        get() {
          return this.$store.state.patient.endDate;
        },
        set(val) {
          this.$store.commit("patient/update_endDate", val);
          this.$store.dispatch("patient/search");
          this.$store.commit("patient/update_page", 1);
        },
      },
      formatedStartDate() {
        return this.formatDate(this.startDate);
      },
      formatedEndDate() {
        return this.formatDate(this.endDate);
      },
    },
    watch: {},
    data() {
      return {
        menuFormDateStart: false,
        menuFormDateEnd: false,
        headers: [
          {
            text: "TANGGAL",
            align: "center",
            sortable: false,
            value: "lab",
            width: "10%",
            class: "pa-2 blue darken-2 white--text",
          },
          {
            text: "NAMA",
            align: "center",
            sortable: false,
            value: "lab",
            width: "35%",
            class: "pa-2 blue darken-2 white--text",
          },
          {
            text: "UKURAN",
            align: "center",
            sortable: false,
            value: "lab",
            width: "15%",
            class: "pa-2 blue darken-2 white--text",
          },
          {
            text: "AKSI",
            align: "center",
            sortable: false,
            value: "lab",
            width: "15%",
            class: "pa-2 blue darken-2 white--text",
          },
        ],
        downloadProgress: 0,
        showProgress: false,
        currentFileName: "",
        progressEvent: null,
        totalSize: 0,
      };
    },
  };
</script>
