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

import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";
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 { DataOption } from "@/modules/09_leave/interface/index/Main";
import type {
  DataLeaveType,
  DataLeaveBeginning,
} from "@/modules/09_leave/interface/response/leaveHistory";

import DialogHeader from "@/components/DialogHeader.vue";

/** useStore*/
const $q = useQuasar();
const route = useRoute();
const { leaveTypeData } = storeToRefs(useLeaveHistoryDataStore());
const { dialogConfirm, showLoader, success, messageError, hideLoader } =
  useCounterMixin();

const { pagination, params, onRequest } = usePagination("", () =>
  onSearchData(false)
);

const modal = defineModel<boolean>("modal", { required: true });
const isStatusEdit = defineModel<boolean>("isStatusEdit", { required: true });
const rowData = defineModel<DataLeaveBeginning>("rowData", {
  default: {} as DataLeaveBeginning,
});

const props = defineProps({
  fetchDataLeaveBeginning: { type: Function, required: true },
});

const formFilter = reactive({
  citizenId: "",
  type: "citizenId",
  keyword: "",
});
const searchTypeOption = ref<DataOption[]>([
  { id: "citizenId", name: "เลขประจำตัวประชาชน" },
  { id: "fullName", name: "ชื่อ-นามสกุล" },
]);
const rows = ref<DataLeaveBeginning[]>([]);
const selected = ref<DataLeaveBeginning[]>([]);
const columns = ref<QTableColumn[]>([
  {
    name: "citizenId",
    align: "left",
    label: " เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "firstName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return `${row.prefix || ""}${row.firstName || ""} ${row.lastName || ""}`;
    },
  },
]);

const leaveTypeCode = ref<string>("");
const profileId = ref<string>("");
const rowId = ref<string>("");
const formData = reactive({
  leaveTypeId: "", //ประเภทการลา
  leaveYear: calculateFiscalYear(new Date()), //ปี
  leaveDays: "", //วันลาที่ยกมา
  leaveDaysUsed: "", //วันลาที่ใช้ไป
  leaveCount: "", //ครั้งที่ใช้ไป
  beginningLeaveDays: "", //ยักมา (วัน)
  beginningLeaveCount: "", // ยกมา (ครั่ง)
});
const leaveTypeOptions = ref<DataLeaveType[]>([]);
const leaveTypeOptionsMain = ref<DataLeaveType[]>([]);

/** ฟังก์ชันบันทึกข้อมูล*/
async function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const pathAPI = !isStatusEdit.value
      ? config.API.leaveBeginning
      : `${config.API.leaveBeginning}/${rowId.value}`;
    const method = !isStatusEdit.value ? "post" : "put";
    await http[method](pathAPI, {
      profileId: !isStatusEdit.value ? selected.value[0].id : profileId.value,
      leaveTypeId: formData.leaveTypeId,
      leaveYear: formData.leaveYear,
      leaveDays: formData.leaveDays ? Number(formData.leaveDays) : 0,
      leaveDaysUsed: formData.leaveDaysUsed
        ? Number(formData.leaveDaysUsed)
        : 0,
      leaveCount: formData.leaveCount ? Number(formData.leaveCount) : 0,
      beginningLeaveDays: formData.beginningLeaveDays
        ? Number(formData.beginningLeaveDays)
        : 0,
      beginningLeaveCount: formData.beginningLeaveCount
        ? Number(formData.beginningLeaveCount)
        : 0,
    })

      .then(async () => {
        await props?.fetchDataLeaveBeginning();
        onClose();
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** ฟังก์ชันเรียกรายชื่อคน*/
async function fetchDataPerson() {
  try {
    const res = await http.post(
      config.API.orgSearchPersonal(),
      {
        fieldName: formFilter.type,
        keyword: formFilter.keyword.trim(),
        system: (route.meta?.Key as string) || undefined,
      },
      {
        params: params.value,
      }
    );
    const result = res.data.result;
    pagination.value.rowsNumber = result.total;
    rows.value = result.data;
  } catch (e) {
    messageError($q, e);
  }
}

/**
 * ฟังก์ชันกำหนดค่าของ formData เมื่อมีการแก้ไขข้อมูล
 * @param data ข้อมูลที่ต้องการแก้ไข
 */
async function defineDataLeaveBeginning(data: DataLeaveBeginning) {
  profileId.value = data.profileId;
  rowId.value = data.id;
  filterCodeLeaveTypeData(data.leaveTypeId);
  formData.leaveTypeId = data.leaveTypeId;
  formData.leaveYear = data.leaveYear;
  formData.leaveDays = data.leaveDays ? data.leaveDays.toString() : "0";
  formData.leaveDaysUsed = data.leaveDaysUsed
    ? data.leaveDaysUsed.toString()
    : "0";
  formData.leaveCount = data.leaveCount ? data.leaveCount.toString() : "0";
  formData.beginningLeaveDays = data.beginningLeaveDays
    ? data.beginningLeaveDays.toString()
    : "0";
  formData.beginningLeaveCount = data.beginningLeaveCount
    ? data.beginningLeaveCount.toString()
    : "0";
}

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

/** ฟังก์ชันปิด Dialog*/
function onClose() {
  modal.value = false;
  formFilter.citizenId = "";
  formFilter.type = "citizenId";
  formFilter.keyword = "";
  formData.leaveTypeId = "";
  formData.leaveYear = calculateFiscalYear(new Date());
  formData.leaveDays = "";
  formData.leaveDaysUsed = "";
  formData.leaveCount = "";
  formData.beginningLeaveDays = "";
  formData.beginningLeaveCount = "";
  rows.value = [];
  selected.value = [];
  pagination.value = {
    page: 1,
    rowsPerPage: 10,
    rowsNumber: 0,
    sortBy: "",
    descending: false,
  };
}

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

/** ฟังก์ชันกำหนดประเภทการลา*/
function filterLeaveTypeData() {
  //ตัดรายการทั้งหมดออก
  const typeOptions = leaveTypeData.value.filter(
    (e: DataLeaveType) => e.id !== "00000000-0000-0000-0000-000000000000"
  );
  leaveTypeOptionsMain.value = typeOptions;
  leaveTypeOptions.value = typeOptions;
}

/**
 * ฟังก์ชันค้นหา Code ประเภทการลา
 * @param id ประเภทการลา
 */
function filterCodeLeaveTypeData(id: string) {
  //หา Code ประเภทการลา
  const code = leaveTypeData.value.find(
    (e: DataLeaveType) => e.id === id
  )?.code;
  leaveTypeCode.value = code ?? "";
  formData.leaveDays = code !== "LV-005" ? "0" : "";
}

function classInput(val: boolean) {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
}

watch(modal, async (val) => {
  if (val) {
    try {
      showLoader();
      await Promise.all([
        filterLeaveTypeData(),
        isStatusEdit.value && defineDataLeaveBeginning(rowData.value),
      ]);
    } finally {
      hideLoader();
    }
  }
});
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card :style="!isStatusEdit ? 'min-width: 80vw' : 'min-width: 30vw'">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="!isStatusEdit ? 'บันทึกวันลาย้อนหลัง' : 'แก้ไขวันลาย้อนหลัง'"
          :close="onClose"
        />
        <q-separator />

        <q-card-section
          :horizontal="$q.screen.gt.md"
          class="q-pa-none"
          style="height: 50vh"
        >
          <div class="row col-12 no-wrap full-height">
            <!-- รายชื่อ -->
            <div class="col-8 overflow-auto q-pa-md" v-if="!isStatusEdit">
              <div class="row q-col-gutter-sm">
                <div class="col-12 col-sm-6 col-md-3">
                  <q-select
                    label="ค้นหาจาก"
                    v-model="formFilter.type"
                    :options="searchTypeOption"
                    outlined
                    emit-value
                    dense
                    emit-option
                    option-label="name"
                    option-value="id"
                    map-options
                  />
                </div>
                <div class="col-12 col-sm-6 col-md-9">
                  <q-input
                    v-model="formFilter.keyword"
                    outlined
                    hide-bottom-space
                    dense
                    label="คำค้น"
                  >
                    <template v-slot:after>
                      <q-btn
                        color="primary"
                        icon="search"
                        label="ค้นหา"
                        class="full-width q-py-sm q-px-md"
                        outline
                        @click.prevent="onSearchData(true)"
                      >
                      </q-btn>
                    </template>
                  </q-input>
                </div>
              </div>

              <div class="col-12 q-pt-sm">
                <p-table
                  ref="table"
                  :columns="columns"
                  :rows="rows"
                  row-key="id"
                  flat
                  bordered
                  :paging="true"
                  dense
                  :rows-per-page-options="[10, 25, 50, 100]"
                  selection="single"
                  v-model:selected="selected"
                  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"
                      >
                        <span class="text-weight-medium">{{ col.label }}</span>
                      </q-th>
                    </q-tr>
                  </template>

                  <template v-slot:body="props">
                    <q-tr :props="props" class="cursor-pointer">
                      <q-td>
                        <q-checkbox
                          keep-color
                          color="primary"
                          dense
                          v-model="props.selected"
                        />
                      </q-td>
                      <q-td
                        v-for="col in props.cols"
                        :key="col.name"
                        :props="props"
                      >
                        <div>
                          {{ col.value ? col.value : "-" }}
                        </div>
                      </q-td>
                    </q-tr>
                  </template>
                </p-table>
              </div>
            </div>

            <q-separator vertical />

            <!-- input -->
            <div class="col overflow-hidden q-pa-md">
              <div class="row q-col-gutter-sm">
                <div class="col-12">
                  <datepicker
                    menu-class-name="modalfix"
                    v-model="formData.leaveYear"
                    :locale="'th'"
                    autoApply
                    year-picker
                    :enableTimePicker="false"
                    :max-date="`${calculateFiscalYear(new Date())}, 12, 31`"
                  >
                    <template #year="{ year }">{{ year + 543 }}</template>
                    <template #year-overlay-value="{ value }">{{
                      parseInt(value + 543)
                    }}</template>
                    <template #trigger>
                      <q-input
                        dense
                        outlined
                        :model-value="Number(formData.leaveYear) + 543"
                        bg-color="white"
                        label="ปีงบประมาณ"
                      >
                        <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-12">
                  <q-select
                    :class="classInput(true)"
                    emit-value
                    map-options
                    outlined
                    dense
                    option-value="id"
                    option-label="name"
                    label="ประเภทการลา"
                    use-input
                    v-model="formData.leaveTypeId"
                    hide-selected
                    fill-input
                    hide-bottom-space
                    @update:model-value="filterCodeLeaveTypeData"
                    :options="leaveTypeOptions"
                    @filter="(inputValue:string,
                            doneFn:Function) => filterOptionFn(inputValue,doneFn)"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกประเภทการลา'}`,]"
                    lazy-rules
                  >
                    <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-12">
                  <q-input
                    :class="classInput(leaveTypeCode == 'LV-005')"
                    :readonly="leaveTypeCode !== 'LV-005'"
                    v-model="formData.leaveDays"
                    dense
                    outlined
                    label="จำนวนสิทธิ์การลา"
                    hide-bottom-space
                    :rules="[(val: string) => !val || /^\d+(\.\d*)?$/.test(val) || 'กรุณากรอกเฉพาะตัวเลข']"
                  />
                </div>
                <div class="col-12">
                  <q-input
                    :class="classInput(true)"
                    v-model="formData.leaveDaysUsed"
                    dense
                    outlined
                    label="ที่ใช้ไป (วัน)"
                    hide-bottom-space
                    :rules="[(val: string) => !val || /^\d+(\.\d*)?$/.test(val) || 'กรุณากรอกเฉพาะตัวเลข']"
                  />
                </div>
                <div class="col-12">
                  <q-input
                    :class="classInput(true)"
                    v-model="formData.leaveCount"
                    dense
                    outlined
                    label="ที่ใช้ไป (ครั้ง)"
                    hide-bottom-space
                    mask="#"
                    reverse-fill-mask
                  />
                </div>

                <div class="col-12">
                  <q-input
                    :class="classInput(true)"
                    v-model="formData.beginningLeaveDays"
                    dense
                    outlined
                    label="ยกมา (วัน)"
                    hide-bottom-space
                    :rules="[(val: string) => !val || /^\d+(\.\d*)?$/.test(val) || 'กรุณากรอกเฉพาะตัวเลข']"
                  />
                </div>

                <div class="col-12">
                  <q-input
                    :class="classInput(true)"
                    v-model="formData.beginningLeaveCount"
                    dense
                    outlined
                    label="ยกมา (ครั้ง)"
                    hide-bottom-space
                    mask="#"
                    reverse-fill-mask
                  />
                </div>
              </div>
            </div>
          </div>
        </q-card-section>

        <q-separator />
        <q-card-actions align="right">
          <q-btn
            :disable="!isStatusEdit && selected.length === 0"
            label="บันทึก"
            color="secondary"
            type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped lang="scss"></style>
