<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";

/** importType*/
import type { QForm } from "quasar";
import type { resHelpDetail } from "@/modules/05_placement/interface/response/officer";
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 {
  date2Thai,
  dialogConfirm,
  messageError,
  showLoader,
  hideLoader,
  success,
  findOrgName,
  convertDateToAPI
} = mixin;

const dataId = route.params.id as string;
const myForm = ref<QForm | null>(null);
const edit = ref<boolean>(false); //การแก้ไขข้อมูล
const dataProfile = ref<DataProfile>(); //ข้อมุลส่วนตัว
const fullname = ref<string>(""); //ชื่อ
const mainData = ref<any>();

/** form แก้ไขข้อมูลเพื่อลงบัญชีแนบท้าย*/
const organizationPositionOld = ref<string>(""); //ตำแหน่ง/สังกัดเดิม
const organization = ref<string>(""); //หน่วยงานเดิม
const dateStart = ref<Date | null>(null); //ตั้งแต่วันที่
const dateEnd = ref<Date | null>(null); // ถึงวันที่
const reason = ref<string>(""); //หมายเหตุ
const status = ref<string>("");

/** fetch ข้อมูลรายละเอียด*/
async function getData() {
  showLoader();
  await http
    .get(config.API.officerDetail(dataId))
    .then((res: resHelpDetail) => {
      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}`;
      organizationPositionOld.value = data.organizationPositionOld
        ? data.organizationPositionOld
        : findOrgName(data);
      organization.value = data.organization;
      dateStart.value = data.dateStart;
      dateEnd.value = data.dateEnd;
      reason.value = data.reason;
      status.value = data.status;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ยืนยันการบันทึกข้อมูลลงบัญชีแนบท้าย*/
function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      const body = {
        organizationPositionOld: organizationPositionOld.value,
        organization: organization.value,
        dateStart: convertDateToAPI(dateStart.value),
        dateEnd: convertDateToAPI(dateEnd.value),
        reason: reason.value,
      };
      await http
        .put(config.API.officerMainEdit(dataId), body)
        .then(async () => {
          await getData();
          await success($q, "แก้ไขข้อมูลเพื่อลงบัญชีแนบท้ายสำเร็จ");
          edit.value = false;
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ต้องการแก้ไขข้อมูลหรือไม่?",
    "แก้ไขข้อมูลเพื่อลงบัญชีแนบท้าย"
  );
}

/** ยกเลิกการแก้ไขข้อมูลเพื่อลงบัญชีแนบท้าย*/
function cancelBtn() {
  edit.value = !edit;
  const data = mainData.value;
  if (data) {
    organizationPositionOld.value = data.organizationPositionOld
      ? data.organizationPositionOld
      : findOrgName(data);
    organization.value = data.organization;
    dateStart.value = data.dateStart;
    dateEnd.value = data.dateEnd;
    reason.value = data.reason;
    status.value = data.status;
  }
  myForm.value?.resetValidation();
}

/** class Input*/
function getClass(val: boolean) {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
}

/** ทำงานเมื่อมีการเรียกใช้ Components*/
onMounted(() => {
  getData();
});
</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/help-government`)"
      />
      รายละเอียดการช่วยราชการ {{ 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 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"
              v-if="
                !(status == 'REPORT' || status == 'DONE') &&
                checkPermission($route)?.attrIsUpdate
              "
            />
          </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="cancelBtn"
            />
          </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="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-12"><q-separator /></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="organization"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกโอนไปสังกัด'}`]"
                  hide-bottom-space
                  :label="`${'หน่วยงานที่ให้ช่วยราชการ'}`"
                />
              </div>
            </div>
            <div class="col-xs-6 col-sm-4 row">
              <div class="col-12">
                <datepicker
                  menu-class-name="modalfix"
                  :readonly="!edit"
                  v-model="dateStart"
                  :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"
                      :rules="edit?[(val:string) => !!val || `${'กรุณาเลือกตั้งแต่วัน'}`]:[]"
                      :model-value="
                        dateStart !== null ? date2Thai(dateStart) : null
                      "
                      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">
              <div class="col-12">
                <datepicker
                  menu-class-name="modalfix"
                  :readonly="!edit"
                  v-model="dateEnd"
                  :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
                      :readonly="!edit"
                      :class="getClass(edit)"
                      :outlined="edit"
                      dense
                      :borderless="!edit"
                      :model-value="
                        dateEnd !== null ? date2Thai(dateEnd) : 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-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>
