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

import http from "@/plugins/http";
import config from "@/app.config";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useLeaveHistoryDataStore } from "@/modules/09_leave/stores/LeaveHistoryStore";
import { calculateFiscalYear } from "@/utils/function";
import { usePagination } from "@/composables/usePagination";

import type { QTableColumn } from "quasar";
import type {
  DataLeaveType,
  DataLeaveBeginning,
} from "@/modules/09_leave/interface/response/leaveHistory";

import DialogForm from "@/modules/09_leave/components/07_LeaveHistory/DialogForm.vue";

const $q = useQuasar();
const { leaveTypeData } = storeToRefs(useLeaveHistoryDataStore());
const { showLoader, hideLoader, messageError, dialogRemove, success } =
  useCounterMixin();
const { pagination, params, onRequest, checkAndUpdatePage } = usePagination(
  "",
  () => onSearchData(false)
);

const formFilter = reactive({
  year: calculateFiscalYear(new Date()),
  type: "00000000-0000-0000-0000-000000000000",
  keyword: "",
});
const leaveTypeOptions = ref<DataLeaveType[]>([]);

const rows = ref<DataLeaveBeginning[]>([]);
const columns = ref<QTableColumn[]>([
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    format(val, row) {
      return `${row.prefix}${row.firstName} ${row.lastName}`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "leaveType",
    align: "left",
    label: " ประเภทการลา",
    sortable: true,
    field: "leaveType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "leaveYear",
    align: "left",
    label: "ปี",
    sortable: true,
    field: "leaveYear",
    format(val, row) {
      return row.leaveYear ? `${Number(row.leaveYear) + 543}` : "-";
    },

    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "leaveDays",
    align: "left",
    label: "จำนวนสิทธิ์การลา",
    sortable: true,
    field: "leaveDays",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "leaveDaysUsed",
    align: "left",
    label: "ที่ใช้ไป (วัน)",
    sortable: true,
    field: "leaveDaysUsed",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "leaveCount",
    align: "left",
    label: "ที่ใช้ไป (ครั้ง)",
    sortable: true,
    field: "leaveCount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "beginningLeaveDays",
    align: "left",
    label: "ยกมา (วัน)",
    sortable: true,
    field: "beginningLeaveDays",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "beginningLeaveCount",
    align: "left",
    label: "ยกมา (ครั้ง)",
    sortable: true,
    field: "beginningLeaveCount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "fullName",
  "leaveType",
  "leaveYear",
  "leaveDays",
  "leaveDaysUsed",
  "leaveCount",
  "beginningLeaveDays",
  "beginningLeaveCount",
]);

const modalDialogForm = ref<boolean>(false); //modal Dialog บันทึกข้อมูลการลาย้อนหลัง
const isStatusEdit = ref<boolean>(false); //สถานะการแก้ไข
const rowData = ref<DataLeaveBeginning>(); //ข้อมูลรายการที่ต้องการ

/** ฟังก์ชันเรียกข้อมูลประเภทการลา*/
async function fetchLeaveType() {
  if (leaveTypeData.value.length === 1) {
    try {
      const res = await http.get(config.API.leaveType());
      leaveTypeData.value.push(...res.data.result);
    } catch (err) {
      messageError($q, err);
    }
  }
  leaveTypeOptions.value = leaveTypeData.value;
}

/** ฟังก์ชันเรียกข้อมูลรายการลาย้อนหลัง*/
async function fetchDataLeaveBeginning() {
  await http
    .post(config.API.leaveBeginning + `/list`, {
      ...formFilter,
      ...params.value,
      keyword: formFilter.keyword.trim(),
    })
    .then((res) => {
      const result = res.data.result;
      pagination.value.rowsNumber = result.total;
      rows.value = result.data;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * ฟังก์ชันค้นหารายชื่อคน
 * @param newSearch สถานะการค้นข้อมูล true ค้นหาหน้าแรก false ค้นหาหน้าต่อไป
 */
async function onSearchData(newSearch: boolean = true) {
  try {
    showLoader();
    if (newSearch) {
      pagination.value.page = 1;
    }
    await fetchDataLeaveBeginning();
  } finally {
    hideLoader();
  }
}

/**
 * ฟังก์ชันเปิด Dialog form บันทึกข้อมูลย้อนหลัง
 * @param isEdit สถานะก่ารแก้ไข
 * @param data ข้อมูลที่ต้องการแก้ไข
 */
function onOpenDialogForm(
  isEdit: boolean,
  data: DataLeaveBeginning = {} as DataLeaveBeginning
) {
  isStatusEdit.value = isEdit;
  rowData.value = data;
  modalDialogForm.value = true;
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFn(val: string, update: Function) {
  update(() => {
    leaveTypeOptions.value = leaveTypeData.value.filter(
      (e: DataLeaveType) => e.name.search(val) !== -1
    );
  });
}

/**
 * ฟังก์ชันยืนยันการลบรายการการลาย้อนหัง
 * @param id รายการที่ต้องการลบ
 */
function onDeleteLeaveBeginning(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.leaveBeginning + `/${id}`)
      .then(async () => {
        await checkAndUpdatePage(rows.value.length);
        await fetchDataLeaveBeginning();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

onMounted(async () => {
  try {
    showLoader();
    await fetchLeaveType();
    await fetchDataLeaveBeginning();
  } finally {
    hideLoader();
  }
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    จำนวนสิทธิ์และวันลาที่ใช้ไป
  </div>

  <q-card flat bordered class="q-pa-md">
    <div class="row q-col-gutter-sm">
      <div class="col-12">
        <div class="row q-col-gutter-sm">
          <div class="row q-col-gutter-sm col-xs-12 col-sm-6 col-md-6">
            <div class="col-xs-12 col-sm-4 col-md-4">
              <datepicker
                v-model="formFilter.year"
                :locale="'th'"
                autoApply
                year-picker
                :enableTimePicker="false"
                @update:model-value="onSearchData()"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    :model-value="Number(formFilter.year) + 543"
                    :label="`${'ปีงบประมาณ'}`"
                    bg-color="white"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-12 col-sm-7 col-md-4">
              <q-select
                emit-value
                map-options
                outlined
                dense
                option-value="id"
                option-label="name"
                label="ประเภทการลา"
                use-input
                v-model="formFilter.type"
                hide-selected
                fill-input
                :options="leaveTypeOptions"
                @update:model-value="onSearchData()"
                @filter="(inputValue:string,
              doneFn:Function) => filterOptionFn(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="col-xs-12 col-sm-1 col-md-4 items-center">
              <q-btn
                v-if="checkPermission($route)?.attrIsCreate"
                dense
                flat
                round
                color="primary"
                icon="add"
                @click.stop.prevent="onOpenDialogForm(false)"
              >
                <q-tooltip>เพิ่มข้อมูลวันลาย้อนหลัง</q-tooltip>
              </q-btn>
            </div>
          </div>

          <q-space />
          <div class="row q-col-gutter-sm col-xs-12 col-sm-6 col-md-4">
            <div class="col-xs-12 col-sm-7 col-md-8">
              <q-input
                standout
                dense
                v-model="formFilter.keyword"
                outlined
                placeholder="ค้นหา"
                @keydown.enter.prevent="onSearchData()"
              >
                <template v-slot:append>
                  <q-icon name="search" />
                </template>
              </q-input>
            </div>
            <div class="col-xs-12 col-sm-5 col-md-4">
              <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>
          </div>
        </div>
      </div>

      <div class="col-12">
        <p-table
          ref="table"
          :columns="columns"
          :rows="rows"
          flat
          bordered
          :paging="true"
          dense
          class="custom-header-table"
          :visible-columns="visibleColumns"
          v-model:pagination="pagination"
          @request="onRequest"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width></q-th>
              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                style="color: #000000; font-weight: 500"
              >
                <span class="text-weight-medium">{{ col.label }}</span>
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td auto-width>
                <q-btn
                  v-if="
                    checkPermission($route)?.attrIsGet &&
                    checkPermission($route)?.attrIsUpdate
                  "
                  dense
                  flat
                  round
                  color="edit"
                  icon="edit"
                  @click.stop.prevent="onOpenDialogForm(true, props.row)"
                  ><q-tooltip>แก้ไขข้อมูล</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="checkPermission($route)?.attrIsDelete"
                  dense
                  flat
                  round
                  color="red"
                  icon="delete"
                  @click.stop.prevent="onDeleteLeaveBeginning(props.row.id)"
                  ><q-tooltip>ลบข้อมูล</q-tooltip>
                </q-btn>
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <div>
                  {{ col.value ?? "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </p-table>
      </div>
    </div>
  </q-card>

  <DialogForm
    v-model:modal="modalDialogForm"
    :is-status-edit="isStatusEdit"
    :row-data="rowData"
    :fetch-data-leave-beginning="fetchDataLeaveBeginning"
  />
</template>

<style scoped></style>
