<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { date, useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType */
import type {
  changeRoundEdit,
  MyObjectRoundChangeRef,
  DataOption,
} from "@/modules/09_leave/interface/request/changeRound";

/** importStore */
import { useCounterMixin } from "@/stores/mixin";
import { useChangeRoundDataStore } from "@/modules/09_leave/stores/ChangeRoundStore";

/** useStore */
const dataStore = useChangeRoundDataStore();
const mixin = useCounterMixin();
const {
  dialogConfirm,
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
  success,
} = mixin;

const $q = useQuasar();

/**Hook */
onMounted(async () => {
  // await fetchDataOption();
});

/**FormData */
const formData = reactive<changeRoundEdit>({
  round: "",
  date: "",
  reson: "",
  effectiveDate: null,
});

/**Validate ข้อมูล */
const roundRef = ref<Object | null>(null);
const resonRef = ref<Object | null>(null);
const effectiveDateRef = ref<Object | null>(null);
const objectRoundChange: MyObjectRoundChangeRef = {
  round: roundRef,
  effectiveDate: effectiveDateRef,
  reson: resonRef,
};

/** Function validateForm */
function validateForm() {
  const hasError = [];
  for (const key in objectRoundChange) {
    if (Object.prototype.hasOwnProperty.call(objectRoundChange, key)) {
      const property = objectRoundChange[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    onSubmit();
  }
}
const dataToday = ref<Date>(new Date());

/** Function ยืนยันการบันทึกข้อมูล */
function onSubmit() {
  dialogConfirm(
    $q,
    () => {
      changeRound();
      props.closeDialog?.();
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

/** Function เปลี่ยนรอบเวลา*/
async function changeRound() {
  await http
    .post(config.API.leaveRound(), {
      profileId: props.personId,
      roundId: formData.round,
      effectiveDate: formData.effectiveDate,
      remark: formData.reson,
    })
    .then(() => {
      success($q, "บันทึกข้อมูลเปลี่ยนรอบเวลา");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      props.closeDialog?.();
    });
}

const roundOp = ref<any>([]);
/**
 *ประวัติการเปลี่ยนรอบการปฏิบัติงาน"
 *
 */
async function fetchDataOption() {
  showLoader();
  await http
    .get(config.API.leaveRound())
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({
          id: r.id.toString(),
          name: `${r.startTimeMorning}-${r.endTimeAfternoon}`,
        });
      });

      roundOp.value = option.filter(
        (e) => e.name !== props.DataRow?.currentRound
      );
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

// paging
const pageSize = ref<number>(10);

/**
 * ฟังก์ชั่น api เปลี่ยนหน้า
 * @param pageVal page
 * @param pageSizeVal pagesize
 */

// Pagination - initial pagination
const initialPagination = ref<any>({
  sortBy: null,
  descending: false,
  page: 1,
  rowsPerPage: pageSize, // set ตาม page หลักส่งมา
});

// Pagination - page & change page & get new data
const currentPage = ref<number>(1);
watch(
  [() => currentPage.value, () => initialPagination.value.rowsPerPage],
  () => {
    emit(
      "update:change-page",
      currentPage.value,
      initialPagination.value.rowsPerPage,
      true
    );
  }
);
const emit = defineEmits(["update:change-page"]);
async function updatePagination(newPagination: any) {
  initialPagination.value = newPagination;
  currentPage.value = 1; // set current page เป็น 1 เสมอเมื่อเปลี่ยน per row
}

/**Props */
const props = defineProps({
  modal: Boolean,
  closeDialog: Function,
  editCheck: String,
  DataRow: Object,
  personId: String,
});

/**ฟังก์ชั่น ปิดไดอาล็อก */
function close() {
  if (props.closeDialog) {
    props.closeDialog();
  }
}
watch(
  () => props.modal,
  async () => {
    if (props.editCheck === "edit") {
      formData.round = "";
      formData.reson = "";
      formData.effectiveDate = null;
    }
    if (props.modal === true) {
      await fetchDataOption();
    }
  }
);
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="min-width: 800px">
      <form @submit.prevent="validateForm">
        <q-toolbar>
          <q-toolbar-title class="text-subtitle1 text-bold">
            {{
              props.editCheck === "edit"
                ? "เปลี่ยนรอบการปฏิบัติงาน"
                : "ประวัติการเปลี่ยนรอบการปฏิบัติงาน"
            }}
            <span class="text-teal-6">{{
              props.DataRow ? props.DataRow.fullName : ""
            }}</span></q-toolbar-title
          >
          <q-btn
            icon="close"
            unelevated
            round
            dense
            @click="close"
            style="color: #ff8080; background-color: #ffdede"
          />
        </q-toolbar>
        <div v-if="props.editCheck === 'edit'">
          <q-separator color="grey-4" />
          <q-card-section style="max-height: 50vh" class="scroll q-pa-none">
            <div class="q-pa-md">
              <div class="row">
                <q-icon
                  name="mdi-label-variant"
                  class="cursor-pointer self-center"
                  color="blue"
                  size="md"
                >
                </q-icon>
                <span class="self-center text-bold text-blue text-subtitle1"
                  >รอบปัจจุบัน</span
                >
                <span class="self-center text-subtitle1 q-ml-sm">{{
                  props.DataRow ? `${props.DataRow.currentRound} น.` : ""
                }}</span>
              </div>
              <div class="row q-mt-sm justify-between">
                <q-select
                  v-model="formData.round"
                  label="รอบที่ต้องการเปลี่ยน"
                  dense
                  ref="roundRef"
                  :rules="[(val) => !!val || 'กรุณาเลือกรอบที่ต้องการเปลี่ยน']"
                  emit-value
                  map-options
                  option-label="name"
                  :options="roundOp"
                  option-value="id"
                  lazy-rules
                  hide-bottom-space
                  :borderless="true"
                  outlined
                  style="width: 23.5rem"
                />

                <datepicker
                  menu-class-name="modalfix"
                  v-model="formData.effectiveDate"
                  :locale="'th'"
                  autoApply
                  borderless
                  :enableTimePicker="false"
                  week-start="0"
                  :min-date="
                    dataToday
                      ? new Date(dataToday.getTime() + 24 * 60 * 60 * 1000)
                      : null
                  "
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      for="inputDatereceive"
                      outlined
                      ref="effectiveDateRef"
                      dense
                      style="width: 23.5rem"
                      class="datepicker"
                      :model-value="
                        formData.effectiveDate != null
                          ? date2Thai(formData.effectiveDate)
                          : null
                      "
                      label="วันที่ให้มีผล"
                      :rules="[
                        (val) => !!val || `${'กรุณาเลือกวันที่ให้มีผล'}`,
                      ]"
                      lazy-rules
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
              <q-input
                class="col-12 bg-white"
                outlined
                stack-label
                ref="resonRef"
                v-model="formData.reson"
                label="เหตุผล"
                hide-bottom-space
                type="textarea"
                :rules="[(val) => !!val || `กรุณากรอกเหตุผล`]"
              ></q-input>
            </div>
          </q-card-section>
        </div>
        <q-separator color="grey-4" />
        <div class="q-pa-xs">
          <div class="row justify-end q-mr-sm q-py-sm">
            <q-btn
              v-if="props.editCheck === 'edit'"
              id="onSubmit"
              type="submit"
              unelevated
              label="บันทึก"
              class="q-px-md items-center"
              color="secondary"
            />
          </div>
        </div>
      </form>
      <div v-if="props.editCheck === 'history'">
        <div class="q-pa-md">
          <d-table
            ref="table"
            :columns="dataStore.columnsHistory"
            :rows="dataStore.rowsHistory"
            row-key="id"
            flat
            bordered
            :paging="false"
            dense
            class="custom-header-table"
            :visible-columns="dataStore.visibleColumnsHistory"
            :rows-per-page-options="[5, 10, 25, 50, 100]"
            :pagination="initialPagination"
            @update:pagination="updatePagination"
          >
            <template v-slot:pagination="scope">
              ทั้งหมด {{ dataStore.total }} รายการ
              <q-pagination
                v-model="currentPage"
                active-color="primary"
                color="dark"
                :max-pages="5"
                size="sm"
                boundary-links
                direction-links
                :max="Number(dataStore.maxPage)"
              ></q-pagination>
            </template>
            <template v-slot:header="props">
              <q-tr :props="props">
                <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" class="cursor-pointer">
                <q-td v-for="col in props.cols" :key="col.name" :props="props">
                  <div>
                    {{ col.value }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </div>
    </q-card>
  </q-dialog>
</template>
