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

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

import type { DataOption } from "@/modules/06_retirement/interface/index/Main";

import DialogHeader from "@/components/DialogHeader.vue";
import { useRoute } from "vue-router";

const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  data: Object,
  fetchData: Function,
});
const $q = useQuasar();
const mixin = useCounterMixin();
const route = useRoute();
const {
  showLoader,
  hideLoader,
  messageError,
  success,
  dialogConfirm,
  date2Thai,
  convertDatetimeToAPI,
  convertDateToAPI,
} = mixin;

const paramsId = ref<string>(route.params.id as string);
const routeName = ref<string>(route?.name as string);
const formData = reactive({
  location: "",
  sendDate: null,
  activeDate: null,
  reasonResign: "",
  remark: "",
});
const options = ref<DataOption[]>([
  {
    id: "CAREER",
    name: "ประกอบอาชีพอื่น",
  },
  {
    id: "MOVE",
    name: "รับราชการสังกัดอื่น",
  },
  {
    id: "FAMILY",
    name: "ดูแลบิดามารดา",
  },
  {
    id: "EDUCATION",
    name: "ศึกษาต่อ",
  },
  {
    id: "OTHER",
    name: "อื่น ๆ",
  },
]);

function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    try {
      const path =
        routeName.value === "resignbyid" ? "resign" : "resign-employee";
      const payload = {
        ...formData,
        activeDate: convertDateToAPI(formData.activeDate),
        sendDate: convertDateToAPI(formData.sendDate),
        remark: formData.reasonResign === "OTHER" ? formData.remark : undefined,
      };

      await http.put(config.API.updateResign(path, paramsId.value), payload);
      await props.fetchData?.(paramsId.value);
      success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    } catch (error) {
      messageError(error);
    } finally {
      hideLoader();
    }
  });
}

function closeDialog() {
  modal.value = false;
  formData.location = "";
  formData.sendDate = null;
  formData.activeDate = null;
  formData.reasonResign = "";
  formData.remark = "";
}

watch(
  () => modal.value,
  (val) => {
    if (val) {
      const data = props.data;
      formData.location = data?.location || "";
      formData.sendDate = data?.sendDate || null;
      formData.activeDate = data?.activeDate || null;
      formData.reasonResign = data?.reason || "";
      formData.remark = data?.remark || "";
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 60%; max-width: 900px">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader :tittle="'แก้ไขข้อมูลการลาออก'" :close="closeDialog" />
        <q-separator />

        <q-card-section>
          <div class="row q-pa-sm q-col-gutter-sm">
            <div class="col-6">
              <q-input
                class="inputgreen"
                dense
                outlined
                v-model="formData.location"
                hide-bottom-space
                label="สถานที่ยื่นขอลาออกจากราชการ"
                :rules="[(val:string) => !!val || `${'กรุณากรอกสถานที่ยื่นขอลาออกจากราชการ'}`]"
              />
            </div>
            <div class="col-3">
              <datepicker
                class="inputgreen"
                menu-class-name="modalfix"
                v-model="formData.sendDate"
                :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
                    outlined
                    dense
                    hide-bottom-space
                    class="full-width"
                    :model-value="
                      formData.sendDate != null
                        ? date2Thai(formData.sendDate)
                        : null
                    "
                    :label="`${'วันที่ยื่นขอลาออกจากราชการ'}`"
                    :rules="[
                          (val: string) =>
                            !!val || `${'กรุณาเลือกวันที่ยื่นขอลาออกจากราชการ'}`,
                        ]"
                  >
                    <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-3">
              <datepicker
                class="inputgreen"
                menu-class-name="modalfix"
                v-model="formData.activeDate"
                :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
                    outlined
                    dense
                    hide-bottom-space
                    class="full-width"
                    :model-value="
                      formData.activeDate != null
                        ? date2Thai(formData.activeDate)
                        : null
                    "
                    :label="`${'วันที่ขอลาออกจากราชการ'}`"
                    :rules="[
                          (val: string) =>
                            !!val || `${'กรุณาเลือกวันที่ขอลาออกจากราชการ'}`,
                        ]"
                  >
                    <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
                v-model="formData.reasonResign"
                class="inputgreen"
                dense
                outlined
                emit-value
                map-options
                hide-bottom-space
                option-label="name"
                option-value="id"
                :options="options"
                label="เหตุผลที่ลาออกจากราชการ"
                :rules="[(val: string) => !!val || `${'กรุณาเลือกเหตุผลที่ลาออกจากราชการ'}`]"
              />
            </div>
            <div class="col-12" v-if="formData.reasonResign === 'OTHER'">
              <q-input
                class="inputgreen"
                v-model="formData.remark"
                outlined
                hide-bottom-space
                dense
                type="textarea"
                label="ระบุเหตุผล"
                :rules="[(val: string) => !!val || `${'กรุณาระบุเหตุผล'}`,]"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
