<template>
  <div class="q-px-md q-pb-md">
    <div class="col-12 row q-py-sm items-center">
      <span class="text-subtitle1">{{ titleText }}</span>
      <q-select
        dense
        outlined
        :model-value="inputvisibleFilter"
        :options="optionsFilter"
        class="col-xs-12 col-sm-4 col-md-3"
        option-value="id"
        option-label="name"
        map-options
        emit-value
        @update:model-value="updateVisibleFilter"
        v-if="optionsFilter != undefined && optionsFilter.length > 0"
      />
      <q-file
        v-model="files"
        dense
        :label="setSeat == false ? 'อัปโหลดที่นั่งสอบ' : 'อัปโหลดคะแนนสอบ'"
        outlined
        use-chips
        multiple
        v-if="statusPayment"
        class="q-pl-sm"
      >
        <template v-slot:prepend>
          <q-icon name="attach_file" color="blue" />
        </template>
      </q-file>
      <q-btn
        size="md"
        icon="mdi-upload"
        round
        flat
        color="blue"
        v-if="statusPayment"
        @click="uploadFile"
      >
        <q-tooltip v-if="setSeat == false">อัปโหลดที่นั่งสอบ</q-tooltip>
        <q-tooltip v-if="setSeat == true">อัปโหลดคะแนนสอบ</q-tooltip>
      </q-btn>
      <q-btn icon="mdi-download" round color="primary" flat>
        <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
        <q-menu>
          <q-list style="min-width: 100px">
            <q-item clickable v-close-popup @click="downloadFile()">
              <q-item-section class="text-blue"
                >ดาวน์โหลดข้อมูลผู้สมัคร(แบบย่อ)</q-item-section
              >
            </q-item>
            <q-item clickable v-close-popup @click="downloadFileDetail()">
              <q-item-section class="text-primary"
                >ดาวน์โหลดข้อมูลผู้สมัคร</q-item-section
              >
            </q-item>
          </q-list>
        </q-menu>
      </q-btn>
      <q-space />
      <div class="items-center" style="display: flex">
        <!-- ค้นหาข้อความใน table -->
        <q-input
          standout
          dense
          :model-value="inputfilter"
          ref="filterRef"
          @update:model-value="updateInput"
          outlined
          debounce="300"
          placeholder="ค้นหา"
          style="max-width: 200px"
          class="q-ml-sm"
        >
          <template v-slot:append>
            <q-icon v-if="inputfilter == ''" name="search" />
            <q-icon
              v-if="inputfilter !== ''"
              name="clear"
              class="cursor-pointer"
              @click="resetFilter"
            />
          </template>
        </q-input>
        <!-- แสดงคอลัมน์ใน table -->
        <q-select
          :model-value="inputvisible"
          @update:model-value="updateVisible"
          :display-value="$q.lang.table.columns"
          multiple
          outlined
          dense
          :options="attrs.columns"
          options-dense
          option-value="name"
          map-options
          emit-value
          style="min-width: 150px"
          class="gt-xs q-ml-sm"
        />
      </div>
    </div>
    <q-table
      ref="table"
      flat
      bordered
      class="custom-header-table"
      v-bind="attrs"
      virtual-scroll
      :virtual-scroll-sticky-size-start="48"
      dense
      :pagination-label="paginationLabel"
      :pagination="initialPagination"
      :rows-per-page-options="paging == true ? [25, 50, 100, 500] : []"
    >
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th auto-width v-if="boss == true" />
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            <span class="text-weight-medium">{{ col.label }}</span>
          </q-th>
          <q-th
            auto-width
            v-if="
              editvisible == true || nextPageVisible == true || history == true
            "
          />
        </q-tr>
      </template>
      <!-- สำหรับเรียกใช้ template ตัวข้างนอก -->
      <template #body="props">
        <slot v-bind="props" name="columns"></slot>
      </template>
    </q-table>
  </div>
</template>
<script setup lang="ts">
import { ref, useAttrs } from "vue";
import { useRoute } from "vue-router";
import { useDataStore } from "@/stores/data";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";

const route = useRoute();
const dataStore = useDataStore();
const { loaderPage } = dataStore;
const mixin = useCounterMixin();
const { dateToISO, success, modalError, dialogMessage } = mixin;
const $q = useQuasar(); // show dialog
const attrs = ref<any>(useAttrs());
const table = ref<any>(null);
const files = ref<File[]>([]);
const filterRef = ref<any>(null);
const examId = ref<string>(route.params.examId.toString());
const { messageError, showLoader, hideLoader } = mixin;
const props = defineProps({
  inputfilter: String,
  inputvisible: Array,
  inputvisibleFilter: String,
  editvisible: Boolean,
  titleText: String,
  optionsFilter: {
    type: Array,
    defualt: [],
  },
  boss: {
    type: Boolean,
    defualt: false,
  },
  saveNoDraft: {
    type: Boolean,
    defualt: false,
  },
  history: {
    type: Boolean,
    defualt: false,
  },
  paging: {
    type: Boolean,
    defualt: false,
  },
  nornmalData: {
    type: Boolean,
    defualt: false,
  },
  nextPageVisible: {
    type: Boolean,
    defualt: false,
  },
  publicData: {
    type: Boolean,
    defualt: true,
    required: false,
  },
  updateData: {
    type: Boolean,
    defualt: true,
    required: false,
  },
  statusPayment: {
    type: Boolean,
    required: false,
  },
  setSeat: {
    type: Boolean,
    required: false,
  },
  publicNoBtn: {
    type: Boolean,
    defualt: false,
  },
  save: {
    type: Function,
    default: () => console.log("not function"),
  },
  cancel: {
    type: Function,
    default: () => console.log("not function"),
  },
  publish: {
    type: Function,
    default: () => console.log("not function"),
  },
  validate: {
    type: Function,
    default: () => console.log("not function"),
  },
  fetchData: {
    type: Function,
    default: () => console.log("not function"),
  },
});
const initialPagination = ref<any>({
  rowsPerPage: props.paging == true ? 25 : 0,
});

const emit = defineEmits([
  "update:inputfilter",
  "update:inputvisible",
  "update:editvisible",
  "update:titleText",
  "update:inputvisibleFilter",
]);

const updateInput = (value: any) => {
  emit("update:inputfilter", value);
};
const updateVisible = (value: any) => {
  emit("update:inputvisible", value);
};
const updateVisibleFilter = (value: any) => {
  emit("update:inputvisibleFilter", value);
};

const paginationLabel = (start: string, end: string, total: string) => {
  if (props.paging == true)
    return " " + start + " ใน " + end + " จากจำนวน " + total + " ณายการ";
  else return start + "-" + end + " ใน " + total;
};

const uploadFile = async () => {
  if (files.value.length > 0) {
    if (props.setSeat == false) {
      uploadDataSeat();
    } else {
      uploadDataPoint();
    }
  } else {
    modalError(
      $q,
      "ไม่สามารถอัปโหลดไฟล์ได้",
      "กรุณาเลือกไฟล์ที่ต้องการอัปโหลด"
    );
  }
};

const uploadDataSeat = async () => {
  showLoader();
  const formData = new FormData();
  formData.append("", files.value[0]);
  await http
    .put(config.API.periodExamUploadSeat(examId.value), formData)
    .then((res) => {
      success($q, "อัพเดทที่นั่งสอบสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      files.value = [];
      props.fetchData();
    });
};

const uploadDataPoint = async () => {
  showLoader();
  const formData = new FormData();
  formData.append("", files.value[0]);
  await http
    .put(config.API.periodExamUploadPoint(examId.value), formData)
    .then((res) => {
      success($q, "อัพเดทคะแนนสอบสำเร็จ");
      files.value = [];
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      files.value = [];
      props.fetchData();
    });
};

const downloadFile = async () => {
  showLoader();
  await http
    .get(config.API.periodExamDownload(examId.value), {
      responseType: "blob",
    })
    .then((res) => {
      const data = res.data;
      downloadFilePDF(data, `Candidate__${dateToISO(new Date())}.xlsx`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const downloadFileDetail = async () => {
  showLoader();
  await http
    .get(config.API.periodExamDownloadDetail(examId.value), {
      responseType: "blob",
    })
    .then((res) => {
      const data = res.data;
      downloadFilePDF(data, `Candidate_Detail_${dateToISO(new Date())}.xlsx`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const downloadFilePDF = async (res: string, fileName: string) => {
  const link = document.createElement("a");
  link.href = window.URL.createObjectURL(
    new Blob([res], {
      type: "application/vnd.ms-excel",
    })
  );
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
};

const checkSave = () => {
  props.validate();
  props.save();
};

const publishModal = () => {
  props.validate();
  const filter = attrs.value.rows.filter((r: any) => r.name == "");

  if (filter.length == 0 || attrs.value.rows.length == 0) {
    dialogMessage(
      $q,
      "ต้องการเผยแพร่ข้อมูลนี้หรือไม่?",
      "ข้อมูลที่กำลังถูกเผยแพร่นี้จะมีผลใช้งานทันที",
      "public",
      "เผยแพร่",
      "public",
      props.publish,
      undefined
    );
  }
};

const resetFilter = () => {
  // reset ค่าที่ค้นหาเมื่อกดปุ่ม X ในกล่องค้นหา
  emit("update:inputfilter", "");
  filterRef.value.focus();
};
</script>
<style lang="scss">
.icon-color {
  color: #4154b3;
}
.custom-header-table {
  max-height: 64vh;
  .q-table tr:nth-child(odd) td {
    background: white;
  }
  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }
  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }
  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
