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

import { useRoute, useRouter } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

/** impotyType*/
import type { resApiData } from "@/modules/05_placement/interface/response/OhterMain";
import type { QForm } from "quasar";
import type { DataProfile } from "@/modules/05_placement/interface/index/Main";

/** importComponents*/
import CardProfile from "@/components/CardProfile.vue";

/** use*/
const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const mixin = useCounterMixin();
const {
  messageError,
  showLoader,
  hideLoader,
  date2Thai,
  dialogConfirm,
  findOrgName,
  success,
  convertDateToAPI,
} = mixin;

const paramsId = route.params.id;
const myForm = ref<QForm | null>(null);
const dataProfile = ref<DataProfile>(); //ข้อมุลส่วนตัว
const edit = ref<boolean>(false);
const status = ref<string>("");
const fullName = ref<string>("");
const mainData = ref<any>();

const educationOld = ref<string>(""); //วุฒิ/สาขา
const organizationPositionOld = ref<string>(""); //ตำแหน่ง/สังกัด
const positionTypeOld = ref<string>(""); //ตำแหน่งประเภท
const positionLevelOld = ref<string>(""); //ระดับตำแหน่ง
const posNo = ref<string>(""); //เลขที่
const salary = ref<number>(0); //เงินเดือน
const date = ref<Date | null>(null); //ตั้งแต่วัน
const militaryDate = ref<Date | null>(null); //พ้นราชการทหารเมื่อ
const reason = ref<string>(""); //หมายเหตุ

/** fetch รายละเอียดรายการอื่นๆ*/
async function fetchData() {
  showLoader();
  await http
    .get(config.API.otherByid(paramsId.toString()))
    .then((res: resApiData) => {
      const data = res.data.result;
      mainData.value = res.data.result;
      dataProfile.value = res.data.result as unknown as DataProfile;

      fullName.value = `${data.prefix ?? "-"}${data.firstName ?? "-"} ${
        data.lastName ?? "-"
      }`;
      status.value = data.status;

      educationOld.value = data.educationOld ?? "";
      organizationPositionOld.value = data.organizationPositionOld
        ? data.organizationPositionOld
        : findOrgName(data);
      positionTypeOld.value = data.positionTypeOld ?? "";
      positionLevelOld.value = data.positionLevelOld ?? "";
      posNo.value = data.positionNumberOld ?? "";
      salary.value = data.amountOld ?? "";
      date.value = data.positionDate ?? null;
      militaryDate.value = data.militaryDate ?? null;
      reason.value = data.reason ?? "";
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
      edit.value = false;
    });
}

/** ยืนยันการบันทึกข้อมูลเพื่อลงบัญชีแนบท้าย*/
function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      let data = {
        educationOld: educationOld.value,
        organizationPositionOld: organizationPositionOld.value,
        positionTypeOld: positionTypeOld.value,
        positionLevelOld: positionLevelOld.value,
        positionNumberOld: posNo.value,
        amountOld: salary.value.toString().replace(/,/g, ""),
        positionDate: convertDateToAPI(date.value),
        militaryDate: convertDateToAPI(militaryDate.value),
        reason: reason.value,
      };
      await http
        .put(config.API.otherByid(paramsId.toString()), data)
        .then(async () => {
          await fetchData();
          await success($q, "แก้ไข้ข้อมูลสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ต้องการแก้ไขข้อมูลหรือไม่?",
    "แก้ไขข้อมูลเพื่อลงบัญชีแนบท้าย"
  );
}

/**
 * ยกเลิกการแก้ไขข้อมูลเพื่อลงบัญชีแนบท้าย
 */
function cancel() {
  edit.value = false;
  const data = mainData.value;
  if (data) {
    educationOld.value = data.educationOld ?? "";
    organizationPositionOld.value = data.organizationPositionOld
      ? data.organizationPositionOld
      : findOrgName(data);
    positionTypeOld.value = data.positionTypeOld ?? "";
    positionLevelOld.value = data.positionLevelOld ?? "";
    posNo.value = data.positionNumberOld ?? "";
    salary.value = data.amountOld ?? "";
    date.value = data.positionDate ?? null;
    militaryDate.value = data.militaryDate ?? null;
    reason.value = data.reason ?? "";
  }
  // fetchData();
  myForm.value?.resetValidation();
}

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};

onMounted(async () => {
  fetchData();
});
</script>

<template>
  <div class="q-gutter-sm q-pa-sm">
    <div class="toptitle text-dark col-12 row items-center">
      <q-btn
        icon="mdi-arrow-left"
        unelevated
        round
        dense
        flat
        color="primary"
        class="q-mr-sm"
        @click="router.push(`/placement/other`)"
      />
      รายละเอียดรายการอื่นๆ {{ fullName }}
    </div>

    <CardProfile :data="dataProfile as DataProfile" />

    <q-card bordered class="row col-12 text-dark q-mt-sm">
      <q-form
        ref="myForm"
        greedy
        @submit.prevent
        @validation-success="onSubmit"
        class="col-12"
      >
        <div class="bg-grey-1 q-pa-sm col-12 row items-center text-primary">
          <div class="q-pl-sm text-weight-bold text-dark">
            แก้ไขข้อมูลเพื่อลงบัญชีแนบท้าย
          </div>
          <q-space />
          <div
            v-if="
              status !== 'DONE' &&
              status !== 'REPORT' &&
              checkPermission($route)?.attrIsUpdate
            "
          >
            <div class="q-gutter-sm" v-if="!edit">
              <q-btn
                outline
                color="primary"
                dense
                icon-right="mdi-file-edit-outline"
                class="q-px-sm"
                label="แก้ไข"
                style="width: 80px"
                @click="edit = !edit"
              />
            </div>
            <div class="q-gutter-sm" v-else>
              <q-btn
                outline
                color="public"
                dense
                class="q-px-sm"
                label="บันทึก"
                style="width: 80px"
                type="submit"
              />
              <q-btn
                outline
                color="red"
                dense
                class="q-px-sm"
                label="ยกเลิก"
                style="width: 80px"
                @click="cancel()"
              />
            </div>
          </div>
        </div>
        <div class="col-12"><q-separator /></div>

        <div class="row col-12 q-pa-md">
          <div class="col-12 row bg-white q-col-gutter-md">
            <div class="row col-12 q-pa-md">
              <div class="col-12">
                <div class="text-weight-bold">วุฒิการศึกษา</div>
              </div>
              <div class="col-12">
                <q-input
                  :class="getClass(edit)"
                  :outlined="edit"
                  dense
                  lazy-rules
                  :readonly="!edit"
                  :borderless="!edit"
                  v-model="educationOld"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกวุฒิการศึกษา'}`]"
                  hide-bottom-space
                  :label="`${'วุฒิการศึกษา'}`"
                  type="text"
                />
              </div>
            </div>

            <div class="col-xs-12 row items-center">
              <div class="col-12">
                <div class="text-weight-bold">ตำแหน่ง/สังกัดเดิม</div>
              </div>
              <div class="col-12">
                <q-input
                  :class="getClass(edit)"
                  :outlined="edit"
                  dense
                  lazy-rules
                  :readonly="!edit"
                  :borderless="!edit"
                  v-model="organizationPositionOld"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกตำแหน่ง/สังกัด'}`]"
                  hide-bottom-space
                  :label="`${'ตำแหน่ง/สังกัด'}`"
                  type="textarea"
                />
              </div>
            </div>
            <div class="col-xs-6 col-sm-4 row">
              <div class="col-12">
                <q-input
                  :class="getClass(edit)"
                  :outlined="edit"
                  dense
                  lazy-rules
                  :readonly="!edit"
                  :borderless="!edit"
                  v-model="positionTypeOld"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกตำแหน่งประเภท'}`]"
                  hide-bottom-space
                  :label="`${'ตำแหน่งประเภท'}`"
                />
              </div>
            </div>
            <div class="col-xs-6 col-sm-4 row">
              <div class="col-12">
                <q-input
                  :class="getClass(edit)"
                  :outlined="edit"
                  dense
                  lazy-rules
                  :readonly="!edit"
                  :borderless="!edit"
                  v-model="positionLevelOld"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกระดับตำแหน่ง'}`]"
                  hide-bottom-space
                  :label="`${'ระดับตำแหน่ง'}`"
                />
              </div>
            </div>
            <div class="col-xs-6 col-sm-4 row">
              <div class="col-12">
                <q-input
                  :class="getClass(edit)"
                  :outlined="edit"
                  dense
                  lazy-rules
                  :readonly="!edit"
                  :borderless="!edit"
                  v-model="posNo"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกเลขที่'}`]"
                  hide-bottom-space
                  :label="`${'เลขที่'}`"
                />
              </div>
            </div>

            <div class="col-12"><q-separator /></div>
            <div class="col-xs-6 col-sm-4 row items-center">
              <div class="col-12">
                <datepicker
                  :readonly="!edit"
                  v-model="date"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  week-start="0"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      :class="getClass(edit)"
                      :outlined="edit"
                      dense
                      :readonly="!edit"
                      :borderless="!edit"
                      :model-value="date !== null ? date2Thai(date) : null"
                      :rules="edit ? [(val:string) => !!val || `${'กรุณาเลือกตั้งแต่วันที่'}`]:[]"
                      hide-bottom-space
                      :label="`${'ตั้งแต่วันที่'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          :style="
                            edit
                              ? 'color: var(--q-primary)'
                              : 'color: var(--q-grey)'
                          "
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
            </div>

            <div class="col-xs-6 col-sm-4 row items-center">
              <div class="col-12">
                <datepicker
                  :readonly="!edit"
                  v-model="militaryDate"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  week-start="0"
                  clearable
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      :class="getClass(edit)"
                      :outlined="edit"
                      dense
                      :readonly="!edit"
                      :borderless="!edit"
                      :model-value="
                        militaryDate !== null ? date2Thai(militaryDate) : null
                      "
                      hide-bottom-space
                      :label="`${'พ้นราชการทหารเมื่อ (ลาออกเพื่อไปรับราชการทหารเท่านั้น)'}`"
                      clearable
                      @clear="
                        () => {
                          militaryDate = null;
                        }
                      "
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          :style="
                            edit
                              ? 'color: var(--q-primary)'
                              : 'color: var(--q-grey)'
                          "
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
            </div>
            <div class="col-12">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="reason"
                hide-bottom-space
                :label="`${'หมายเหตุ '}`"
                type="textarea"
              />
            </div>
          </div>
        </div>
      </q-form>
    </q-card>
  </div>
</template>

<style lang="scss" scope>
.q-img {
  border-radius: 5px;
  height: 70px;
}
.text-top {
  color: gray;
  font-weight: 400;
  padding-bottom: 3px;
}
.text-detail {
  font-weight: 500;
}
</style>
