<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 CurrencyInput from "@/components/CurruncyInput.vue";
import http from "@/plugins/http";
import config from "@/app.config";
import keycloak from "@/plugins/keycloak";
/**Import type */
import type { QForm } from "quasar";
import type { ResponseDataDetail } from "@/modules/06_retirement/interface/response/discharged";
import PopupPersonal from "@/components/Dialogs/PopupPersonal.vue";

const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");
/** use */
const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const mixin = useCounterMixin();
const dataId = route.params.id.toString();
const {
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
  success,
  dialogConfirm,
} = mixin;

const myForm = ref<QForm | null>(null);
const roleAdmin = ref<boolean>(false);
const edit = ref<boolean>(false);

/**
 * กำหนดค่าตัวแปร
 */
const organizationPositionOld = ref<string>("");
const positionTypeOld = ref<string>("");
const positionLevelOld = ref<string>("");
const posNo = ref<string>("");
const salary = ref<number>(0);
const organization = ref<string>("");
const date = ref<Date | null>(null);
const reason = ref<string>("");
const responseData = ref<ResponseDataDetail>({
  personId: "",
  avataPath: "",
  createdAt: new Date(),
  date: new Date(),
  id: "",
  organization: "",
  organizationPositionOld: "",
  positionLevelOld: "",
  positionNumberOld: "",
  positionTypeOld: "",
  reason: "",
  salary: 0,
  status: "",
  fullname: "",
});

/** Hook */
onMounted(async () => {
  if (keycloak.tokenParsed != null) {
    roleAdmin.value = await keycloak.tokenParsed.role.includes("placement1");
  }
  await getData();
});

/** Fnction เรียกข้อมูลจาก API  */
const getData = async () => {
  showLoader();
  await http
    .get(config.API.dischargeByid(dataId))
    .then((res: any) => {
      const data = res.data.result;
      responseData.value.personId = data.profileId;
      responseData.value.createdAt = data.createdAt;
      responseData.value.date =
        data.date !== null ? new Date(data.date) : new Date();
      responseData.value.id = data.id ?? "";
      responseData.value.organization = data.organization ?? "";
      responseData.value.organizationPositionOld =
        data.organizationPositionOld ?? "";
      responseData.value.positionLevelOld = data.positionLevelOld ?? "";
      responseData.value.positionNumberOld = data.positionNumberOld ?? "";
      responseData.value.positionTypeOld = data.positionTypeOld ?? "";
      responseData.value.reason = data.reason ?? "";
      responseData.value.salary = data.salary !== null ? data.salary : 0;
      responseData.value.status = data.status ?? "";
      responseData.value.avataPath = data.avatar ?? "";
      responseData.value.fullname = `${data.firstName ?? "-"} ${
        data.lastName ?? "-"
      }`;
      organizationPositionOld.value = data.organizationPositionOld ?? "";
      positionTypeOld.value = data.positionTypeOld ?? "";
      positionLevelOld.value = data.positionLevelOld ?? "";
      posNo.value = data.positionNumberOld ?? "";
      salary.value = data.salary ?? "";
      organization.value = data.organization ?? "";
      date.value = data.date !== null ? new Date(data.date) : null;
      reason.value = data.reason ?? "";
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 * ฟังก์ชั่น Cancle
 */
const clickCancel = async () => {
  await getData();
  edit.value = false;
};

/**
 * ฟังก์ชั่น Save
 */
const conditionSave = async () => {
  if (myForm.value !== null) {
    myForm.value.validate().then((success) => {
      if (success) {
        dialogConfirm(
          $q,
          async () => {
            await saveData();
          },
          "ยืนยันการแก้ไขข้อมูล",
          "ต้องการยืนยันการแก้ไขข้อมูลเพื่อลงบัญชีแนบท้ายหรือไม่?"
        );
      }
    });
  }
};

//บันทึกข้อมูล
const saveData = async () => {
  const body = {
    organization: organization.value,
    reason: reason.value,
    organizationPositionOld: organizationPositionOld.value,
    date: date.value,
    positionTypeOld: positionTypeOld.value,
    positionLevelOld: positionLevelOld.value,
    positionNumberOld: posNo.value,
    amountOld: salary.value,
  };
  showLoader();
  await http
    .put(config.API.dischargeByid(dataId), body)
    .then((res: any) => {
      success($q, "แก้ไขข้อมูลเพื่อลงบัญชีแนบท้ายสำเร็จ");
      edit.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await getData();
      hideLoader();
    });
};

/**
 * Function เพิ่ม Class เวลา Edit
 * @param val เมื่อเป็นEdit จะเปลี่ยน Class
 */
const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};

function onclickViewinfo(id: string) {
  modalPersonal.value = true;
  personId.value = id;
}

function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}
</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)"
    />
    รายละเอียดการปลดออกของ {{ responseData.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">
        {{ responseData.fullname }}
      </div>
      <q-space />
      <q-btn
        outline
        color="blue"
        dense
        icon-right="mdi-open-in-new"
        class="q-px-sm"
        label="ดูข้อมูลทะเบียนประวัติ"
        @click="onclickViewinfo(responseData.personId)"
      />
    </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" v-else />
        </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">
              {{ responseData.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">
              {{ responseData.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">
              {{ responseData.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
        v-if="
          responseData.status !== 'DONE' && responseData.status !== 'REPORT'
        "
      >
        <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="conditionSave"
          />
          <q-btn
            outline
            color="red"
            dense
            class="q-px-sm"
            label="ยกเลิก"
            style="width: 80px"
            @click="clickCancel"
          />
        </div>
      </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 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) => !!val || `${'กรุณากรอกตำแหน่ง/สังกัด'}`]"
                hide-bottom-space
                :label="`${'ตำแหน่ง/สังกัด'}`"
                type="textarea"
              />
            </div>
          </div>
          <div class="col-xs-6 col-sm-3 row">
            <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">
            <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">
            <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">
            <div class="col-12">
              <CurrencyInput
                v-model="salary"
                :edit="edit"
                :options="{
                  currency: 'THB',
                }"
                :label="`${'เงินเดือน'}`"
              />
            </div>
          </div>
          <div class="col-12"><q-separator /></div>
          <div class="col-xs-6 col-sm-6 row">
            <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">
            <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
                    :readonly="!edit"
                    :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"
              hide-bottom-space
              :label="`${'หมายเหตุ '}`"
              type="textarea"
            />
          </div>
        </div>
      </div>
    </q-form>
  </q-card>

  <PopupPersonal
    :modal="modalPersonal"
    :id="personId"
    @update:modal="updatemodalPersonal"
  />
</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>
