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

/** importType */
import type {
  changeRoundEdit,
  MyObjectRoundChangeRef,
} 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 } = mixin;

const $q = useQuasar();

const roundRef = ref<Object | null>(null);
const resonRef = ref<Object | null>(null);
const effectiveDateRef = ref<Object | null>(null);

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

const roundOp = ref([
  {
    id: "1",
    name: "08:30 - 17:00",
  },
  {
    id: "2",
    name: "08:00 - 16:30",
  },
]);
const objectRoundChange: MyObjectRoundChangeRef = {
  round: roundRef,
  effectiveDate: effectiveDateRef,
};

/** 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();
  } else {
    console.log(hasError);
  }
}

/** Function ยืนยันการบันทึกข้อมูล */
function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      props.closeDialog?.();
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}
const props = defineProps({
  modal: Boolean,
  closeDialog: Function,
  editCheck: String,
  DataRow: Object,
});

function close() {
  if (props.closeDialog) {
    props.closeDialog();
  }
}
watch(
  () => props.modal,
  (newDetailData, oldDetailData) => {
    if (props.editCheck === "edit") {
      formData.round = "";
      formData.reson = "";
      formData.effectiveDate = null;
    }
  }
);
</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"
                >
                  <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
                v-model="formData.reson"
                label="เหตุผล"
                hide-bottom-space
                type="textarea"
              ></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"
          >
            <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 v-if="col.name == 'round'">
                    {{ props.rowIndex + 1 }}
                  </div>
                  <div>
                    {{ col.value }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </div>
    </q-card>
  </q-dialog>
</template>
