<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type { QTableProps } from "quasar";
import type { DataBackup } from "@/modules/04_system/interface/response/Main";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import { useDataStore } from "@/modules/04_system/stores/main";
import { storeToRefs } from "pinia";

/** use*/
const $q = useQuasar();
const {
  showLoader,
  date2Thai,
  dialogRemove,
  dialogConfirm,
  onSearchDataTable,
  hideLoader,
  messageError,
} = useCounterMixin();
const {
  createBackUp,
  restore,
  deleteBackUp,
  fetchListBackup,
  backupRunningList,
  restoreRunningList,
  stopAllPolling,
} = useDataStore();
const storeData = useDataStore();
const {
  dataBackUp,
  backupRunTotal,
  restoreRunTotal,
  prevBackupRunTotal,
  prevRestoreRunTotal,
} = storeToRefs(storeData);

/** Table*/
const filter = ref<string>("");
const visibleColumns = ref<string[]>([
  "name",
  "createAt",
  "databaseSize",
  "storageSize",
  "status",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ชื่อข้อมูลสำรอง",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createAt",
    align: "center",
    label: "วันที่สร้าง",
    sortable: true,
    field: "timestamp",
    format: (v) => date2Thai(v, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "status",
    align: "center",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** function สร้างรายการข้อมูลสำรอง*/
function onCreateBackup() {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      await createBackUp();
    },
    "ยืนยันการสร้างข้อมูลสำรอง",
    "ต้องการยืนยันการสร้างข้อมูลสำรองใช่หรือไม่?"
  );
}

/**
 * function ลบรายการข้อมูลสำรอง
 * @param id รายการสำรอง
 */
function onDelete(name: string) {
  dialogRemove($q, async () => {
    showLoader();
    deleteBackUp(name);
  });
}

/**
 * function คืนค่าข้อมูลสำรอง
 * @param id ข้อมูลสำรอง
 */
function onRestore(name: string) {
  dialogConfirm(
    $q,
    async () => {
      await restore(name);
    },
    "ยืนยันการคืนค่าข้อมูลสำรอง",
    "ต้องการยืนยันการคืนค่าข้อมูลสำรองนี้ใช่หรือไม่?"
  );
}

const dataMain = ref<DataBackup[]>([]);

function onDownloadFile(name: string) {
  showLoader();
  http
    .get(config.API.backup + `/download/${name}`)
    .then((res) => {
      const link = document.createElement("a");
      link.href = res.data;
      link.setAttribute("download", name);
      document.body.appendChild(link);
      link.click();
      link.remove();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function serchDataTable() {
  dataBackUp.value = onSearchDataTable(
    filter.value,
    dataMain.value,
    columns.value ? columns.value : []
  );
}

onMounted(async () => {
  prevBackupRunTotal.value = -1;
  prevRestoreRunTotal.value = -1;
  await fetchListBackup();
  await backupRunningList(fetchListBackup);
  await restoreRunningList(() => {});
  dataMain.value = dataBackUp.value;
});

onUnmounted(() => {
  stopAllPolling();
});
</script>

<template>
  <q-card-section class="q-pa-none q-mt-sm">
    <div class="items-center col-12 row q-gutter-x-sm q-mb-sm">
      <q-btn
        color="primary"
        icon="add"
        label="สร้างข้อมูลสำรอง"
        @click="onCreateBackup"
        :disable="backupRunTotal > 0"
      >
        <q-tooltip>สร้างข้อมูลสำรอง </q-tooltip>
      </q-btn>

      <q-space />

      <q-input
        borderless
        dense
        outlined
        v-model="filter"
        placeholder="ค้นหา"
        @keydown.enter.prevent="serchDataTable"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>
      <q-select
        v-model="visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="columns"
        option-value="name"
        style="min-width: 140px"
      />
    </div>

    <d-table
      :rows="dataBackUp"
      :columns="columns"
      row-key="name"
      :visible-columns="visibleColumns"
    >
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th v-for="(col, i) in props.cols" :key="col.name" :props="props">
            <span class="text-weight-medium" :class="{ 'q-ml-md': i === 2 }">{{
              col.label
            }}</span>
          </q-th>
          <q-th auto-width></q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td v-for="(col, i) in props.cols" :key="col.name" :props="props">
            <div :class="{ 'text-center': i === 4 }">
              {{
                i !== 4 && i !== 2 && i !== 3
                  ? col.value
                  : col.value === "สำเร็จ"
                  ? "สำเร็จ"
                  : // : i === 2 || i === 3
                    // ? getSize(col.value)
                    ""
              }}

              <q-circular-progress
                v-if="props.row.status === 'running' && col.name === 'status'"
                indeterminate
                rounded
                size="20px"
                color="lime"
                class="q-ma-md"
              />
            </div>
          </q-td>
          <q-td>
            <q-btn
              v-if="props.row.status !== 'running'"
              dense
              flat
              round
              icon="delete"
              color="red"
              @click.petvent="onDelete(props.row.name)"
            >
              <q-tooltip>ลบข้อมูลสำรอง</q-tooltip>
            </q-btn>

            <q-btn
              v-if="props.row.status !== 'running'"
              dense
              flat
              round
              icon="mdi-download"
              color="primary"
              @click.petvent="onDownloadFile(props.row.name)"
            >
              <q-tooltip>ดาวน์โหลดข้อมูลสำรอง</q-tooltip>
            </q-btn>

            <q-btn
              v-if="props.row.status !== 'running'"
              dense
              flat
              round
              :disable="restoreRunTotal !== 0"
              icon="restore"
              color="blue"
              @click.petvent="onRestore(props.row.name)"
            >
              <q-tooltip>คืนค่า</q-tooltip>
            </q-btn>
          </q-td>
        </q-tr>
      </template>
    </d-table>
  </q-card-section>
</template>

<style scoped></style>
