<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useQuasar } from "quasar";
import { useRoute, useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";

import type { ResponseTitle } from "@/modules/05_placement/interface/response/Receive";

import http from "@/plugins/http";
import config from "@/app.config";

const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const mixin = useCounterMixin();

const paramsId = route.params.id;
const {
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
  success,
  dialogConfirm,
} = mixin;

const title = ref<ResponseTitle>({
  fullname: "",
  organizationPositionOld: "",
  positionLevelOld: "",
  positionTypeOld: "",
});
const appointment = ref<any>([]);

const edit = ref<boolean>(false);
const profileId = ref<string>("");
const organizationPositionOld = ref<string>("");
const positionTypeOld = ref<string>("");
const positionLevelOld = ref<string>("");
const posNo = ref<string>("");
const salary = ref<string>("");
const educationOld = ref<string>("");
const reason = ref<string>("");
const date = ref<Date | null>(null);

onMounted(async () => {
  await fecthappointmentByid();
});

const fecthappointmentByid = async () => {
  showLoader();
  await http
    .get(config.API.appointmentByid(paramsId.toString()))
    .then((res: any) => {
      const data = res.data.result;
      appointment.value = data;
      // console.log(data);

      profileId.value = data.profileId;
      title.value.fullname = `${data.firstname ?? "-"} ${data.lastname ?? "-"}`;
      title.value.organizationPositionOld = data.organizationPositionOld ?? "-";
      title.value.positionLevelOld = data.positionLevelOld ?? "-";
      title.value.positionTypeOld = data.positionTypeOld ?? "-";

      educationOld.value = data.educationOld;
      organizationPositionOld.value = data.organizationPositionOld;
      positionTypeOld.value = data.positionTypeOld;
      positionLevelOld.value = data.positionLevelOld;
      posNo.value = data.positionNumberOld;
      salary.value = data.salary;
      // organization.value = data.organization; //ไม่มี
      reason.value = data.reason;
      date.value = data.positionDate;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
const clickSave = () => {
  dialogConfirm($q, () => putAppointment());
};
const putAppointment = async () => {
  console.log("บันทึกข้อมูล");
  let data = {
    citizenId: appointment.value.citizenId,
    prefixId: appointment.value.prefixId,
    firstname: appointment.value.firstname,
    lastname: appointment.value.lastname,
    // dateOfBirth: "2023-08-15T08:44:38.060Z",
    // genderId: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    // nationality: "string",
    // race: "string",
    // religionId: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    // bloodGroupId: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    // relationshipId: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    // telephoneNumber: "string",
    educationOld: educationOld.value,
    organizationPositionOld: organizationPositionOld.value,
    positionTypeOld: positionTypeOld.value,
    positionLevelOld: positionLevelOld.value,
    positionNumberOld: posNo.value,
    amountOld: Number(salary.value),
    reason: reason.value,
    positionDate: date.value,
    // positionDate: "2023-08-15T08:44:38.060Z",
    // file: ["string"],
  };
  console.log(data);
  showLoader();
  await http
    .put(config.API.appointmentByid(paramsId.toString()), data)
    .then(() => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
      console.log(e);
    })
    .finally(() => {
      fecthappointmentByid();
      edit.value = false;
    });
};
const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>
<template>
  <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.go(-1)" />
    รายละเอียดการแต่งตั้ง-เลื่อน {{ title.fullname }}
  </div>
  <q-card bordered class="row col-12 text-dark">
    <div class="bg-grey-1 q-pa-sm col-12 row items-center text-primary">
      <div class="q-pl-sm text-weight-bold text-subtitle2">
        {{ title.fullname }}
      </div>
      <q-space />
      <q-btn outline color="blue" dense icon-right="mdi-open-in-new" class="q-px-sm" label="ดูข้อมูลทะเบียนประวัติ"
        @click="router.push(`/registry/${profileId}`)" />
    </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-3 col-sm-2 col-md-1 row">
          <!-- <q-img
            :src="responseData.avataPath"
            v-if="responseData.avataPath !== ''"
          /> -->
          <q-img src="@/assets/avatar_user.jpg" />
        </div>
        <div class="col-xs-6 col-sm-3 row items-center">
          <div class="col-12 q-pl-md">
            <div class="col-12 text-top">ตำแหน่งในสายงาน</div>
            <div class="col-12 text-detail">
              {{ title.positionTypeOld }}
            </div>
          </div>
        </div>
        <div class="col-xs-6 col-sm-3 row items-center">
          <div class="col-12">
            <div class="col-12 text-top">ระดับ</div>
            <div class="col-12 text-detail">
              {{ title.positionLevelOld }}
            </div>
          </div>
        </div>
        <div class="col-xs-6 col-sm-3 row items-center">
          <div class="col-12">
            <div class="col-12 text-top">สังกัด</div>
            <div class="col-12 text-detail">
              {{ title.organizationPositionOld }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </q-card>

  <q-card bordered class="row col-12 text-dark q-mt-sm">
    <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" />
      </div>
      <div class="q-gutter-sm" v-else>
        <q-btn outline color="public" dense class="q-px-sm" label="บันทึก" style="width: 80px" @click="clickSave" />
        <q-btn outline color="red" dense class="q-px-sm" label="ยกเลิก" style="width: 80px" @click="edit = !edit" />
      </div>
    </div>
    <div class="col-12"><q-separator /></div>
    <q-form ref="myForm">
      <div class="row col-12 q-pa-md">
        <div class="col-12">
          <div class="text-weight-bold text-grey">วุฒิการศึกษา</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) => !!val || `${'กรุณากรอกวุฒิการศึกษา'}`]" hide-bottom-space
            :label="`${'วุฒิการศึกษา'}`" type="text" />
        </div>
      </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 q-pa-md items-center">
            <div class="col-12">
              <div class="text-weight-bold text-grey">
                ตำแหน่งและหน่วยงานเดิม
              </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) => !!val || `${'กรุณากรอกตำแหน่ง/สังกัด'}`]"
                hide-bottom-space :label="`${'ตำแหน่ง/สังกัด'}`" type="textarea" />
            </div>
          </div>

          <div class="col-xs-6 col-sm-3 row items-center">
            <div class="col-12">
              <q-input :class="getClass(edit)" :outlined="edit" dense lazy-rules :readonly="!edit" :borderless="!edit"
                v-model="positionTypeOld" :rules="[(val) => !!val || `${'กรุณากรอกตำแหน่งประเภท'}`]" hide-bottom-space
                :label="`${'ตำแหน่งประเภท'}`" />
            </div>
          </div>
          <div class="col-xs-6 col-sm-3 row items-center">
            <div class="col-12">
              <q-input :class="getClass(edit)" :outlined="edit" dense lazy-rules :readonly="!edit" :borderless="!edit"
                v-model="positionLevelOld" :rules="[(val) => !!val || `${'กรุณากรอกระดับ'}`]" hide-bottom-space
                :label="`${'ระดับ'}`" />
            </div>
          </div>
          <div class="col-xs-6 col-sm-3 row items-center">
            <div class="col-12">
              <q-input :class="getClass(edit)" :outlined="edit" dense lazy-rules :readonly="!edit" :borderless="!edit"
                v-model="posNo" :rules="[(val) => !!val || `${'กรุณากรอกเลขที่'}`]" hide-bottom-space
                :label="`${'เลขที่'}`" />
            </div>
          </div>
          <div class="col-xs-6 col-sm-3 row items-center">
            <div class="col-12">
              <q-input :class="getClass(edit)" :outlined="edit" dense lazy-rules :readonly="!edit" :borderless="!edit"
                v-model="salary" :rules="[(val) => !!val || `${'กรุณากรอกเงินเดือน'}`]" hide-bottom-space
                :label="`${'เงินเดือน'}`" type="number" />
            </div>
          </div>
          <div class="col-12"><q-separator /></div>
          <!-- <div class="col-xs-6 col-sm-6 row items-center">
            <div class="col-12">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="organization"
                :rules="[(val) => !!val || `${'กรุณากรอกโอนไปสังกัด'}`]"
                hide-bottom-space
                :label="`${'โอนไปสังกัด'}`"
              />
            </div>
          </div> -->
          <div class="col-xs-6 col-sm-6 row items-center">
            <div class="col-12">
              <datepicker menu-class-name="modalfix" :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 lazy-rules :borderless="!edit"
                    :model-value="date !== null ? date2Thai(date) : null"
                    :rules="[(val) => !!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" :rules="[(val) => !!val || `${'กรุณากรอกหมายเหตุ '}`]" hide-bottom-space
              :label="`${'หมายเหตุ '}`" type="textarea" />
          </div>
        </div>
      </div>
    </q-form>
  </q-card>
</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>
