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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";

/** importType*/
import type {
  DataOption,
  DataDateMonthObject,
} from "@/modules/09_leave/interface/index/Main";

/** importComponents*/
import Header from "@/components/DialogHeader.vue";

/** use*/
const mixin = useCounterMixin();
const $q = useQuasar();
const { date2Thai, monthYear2Thai, dateToISO, messageError } = mixin;

// const apiGenReport =
//   "https://report-server.frappet.synology.me/api/v1/report-template/xlsx";

const props = defineProps({
  modal: {
    type: Boolean,
    requier: true,
    default: false,
  },
  close: {
    type: Function,
    requier: true,
  },
});

const loadingBtn = ref<boolean>(true);
const filterType = ref<string>("DAY");
const filterTypeMain = ref<DataOption[]>([
  { id: "DAY", name: "รายวัน" },
  { id: "MONTH", name: "รายเดือน" },
]);
const filterTypeOption = ref<DataOption[]>(filterTypeMain.value);
const date = ref<Date>(new Date());
const dateMonth = ref<DataDateMonthObject>({
  month: new Date().getMonth(),
  year: new Date().getFullYear(),
});

const detailReport = ref<any>();

/** function อัปเดทรายงานสถิติการลา*/
async function updateFilterType() {
  filterType.value === "DAY"
    ? updateDte()
    : filterType.value === "MONTH"
    ? updateMonth()
    : false;
}

/** function อัปเดทวัน*/
async function updateDte() {
  const body = {
    startDate: dateToISO(date.value),
    endDate: dateToISO(date.value),
    type: filterType.value,
  };
  fetchReportTimeRecords(body);
}

/** function อัปเดทเดือน*/
async function updateMonth() {
  const mount = dateMonth.value.month + 1;
  //  วันเริ่มต้นของเดือน
  const firstDay = new Date(dateMonth.value.year, mount - 1, 1);
  // วันสิ้นสุดของเดือนถัดไป
  const lastDay = new Date(dateMonth.value.year, mount, 0);
  const body = {
    startDate: dateToISO(firstDay),
    endDate: dateToISO(lastDay),
    type: filterType.value,
  };
  fetchReportTimeRecords(body);
}

/**
 * function เรียกข้อมูลรายงานสถิติการลา
 * @param body วันเรื่มต้นและสิ้นสุด
 */
async function fetchReportTimeRecords(body: any) {
  loadingBtn.value = true;
  await http
    .post(config.API.leaveReportTimeRecords(), body)
    .then((res) => {
      const data = res.data.result;
      detailReport.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      setTimeout(() => {
        loadingBtn.value = false;
      }, 500);
    });
}

/**
 *  function filterOption
 * @param val  คำค้นหา
 * @param update functoin
 */
function filterFnOptions(val: any, update: Function) {
  update(() => {
    filterTypeOption.value = filterTypeMain.value.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

/**
 * function เรียกไฟล์ XLSX
 * @param data ข้อมูลรายงานสถิติการลา
 */
async function genReportXLSX(data: any) {
  await axios
    .post(`${config.API.reportTemplate}/xlsx`, data, {
      headers: {
        accept:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "content-Type": "application/json",
      },
      responseType: "blob",
    })
    .then(async (res) => {
      const blob = new Blob([res.data]);
      await downloadReport(blob, "xlsx");
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    });
}

/**
 *
 * @param data ข้อมูลรายงานสถิติการลา
 * @param type นามสกุลไฟล์
 */
async function downloadReport(data: any, type: string) {
  const link = document.createElement("a");
  var fileName = "รายงานสรุปบันทึกการลงเวลาปฏิบัติงาน";
  link.href = window.URL.createObjectURL(new Blob([data]));
  link.setAttribute("download", `${fileName}.${type}`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

function monthYearThai(val: DataDateMonthObject) {
  if (val == null) return "";
  else return monthYear2Thai(val.month, val.year);
}

watch(
  () => props.modal,
  () => {
    filterType.value = "DAY";
    date.value = new Date();
    props.modal && updateFilterType();
  }
);
</script>
<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="width: 700px; max-width: 100vw">
      <Header :close="props.close" :tittle="'รายงานสถิติการลงเวลา'" />

      <q-separator />

      <q-card-section class="q-pt-none" style="padding: 0px">
        <div class="q-pa-sm q-gutter-y-sm">
          <q-toolbar class="q-pa-sm bg-grey-2" style="border-radius: 5px">
            <div class="q-pr-xs col-4">
              <q-select
                class="bg-white"
                outlined
                dense
                v-model="filterType"
                :options="filterTypeOption"
                emit-value
                map-options
                option-label="name"
                option-value="id"
                @update:model-value="updateFilterType"
                @filter="(inputValue: any,
        doneFn: Function) => filterFnOptions(inputValue, doneFn,)"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </div>
            <div class="q-pr-xs col-4" v-if="filterType === 'DAY'">
              <datepicker
                menu-class-name="modalfix"
                v-model="date"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                @update:model-value="updateDte"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    class="bg-white"
                    outlined
                    dense
                    borderless
                    :model-value="date ? date2Thai(date) : null"
                    :label="`${'วันที่'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="q-pr-xs col-4" v-if="filterType === 'MONTH'">
              <datepicker
                v-model="dateMonth"
                :locale="'th'"
                autoApply
                month-picker
                :enableTimePicker="false"
                @update:model-value="updateMonth"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    class="bg-white"
                    outlined
                    dense
                    borderless
                    :label="`${'เดือน'}`"
                    :model-value="monthYearThai(dateMonth)"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      ></q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="q-pr-xs col-4">
              <q-btn
                :loading="loadingBtn"
                :disable="loadingBtn"
                color="primary"
                icon="download"
                label="ดาวน์โหลดรายงาน"
                @click="genReportXLSX(detailReport)"
                style="width: 100%"
              >
                <q-tooltip>ดาวน์โหลดรายงาน</q-tooltip>
              </q-btn>
            </div>
          </q-toolbar>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
