<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { useQuasar } from "quasar";
import { useRoute, useRouter } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { tokenParsed } from "@/plugins/auth";
import { useDisciplineSuspendStore } from "@/modules/11_discipline/store/SuspendStore";

/**Import type */
import type { QForm } from "quasar";
import type { DataDetail } from "@/modules/11_discipline/interface/response/Suspend";
import type { DataProfile } from "@/modules/05_placement/interface/index/Main";

import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";
import CardProfile from "@/components/CardProfile.vue";

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

/**
 * กำหนดค่าตัวแปร
 */
const myForm = ref<QForm | null>(null);
const roleAdmin = ref<boolean>(false);
const edit = ref<boolean>(false);
const dataProfile = ref<DataProfile>();
const mainData = ref<any>();

const data = reactive<DataDetail>({
  id: "",
  personId: "",
  citizenId: "",
  avatar: "",
  name: "",
  prefix: "",
  firstName: "",
  lastName: "",
  organization: "",
  position: "",
  posNo: "",
  posTypeName: "",
  positionLevel: "",
  salary: 0,
  status: "",
  descriptionSuspend: "",
  startDateSuspend: null,
  endDateSuspend: null,
  title: "",
  offenseDetails: "",
  disciplinaryFaultLevel: "",
  disciplinaryCaseFault: "",
  child1: "",
  child1Id: null,
  child1ShortName: "",
  child2: "",
  child2Id: null,
  child2ShortName: "",
  child3: "",
  child3Id: null,
  child3ShortName: "",
  child4: "",
  child4Id: null,
  child4ShortName: "",
  root: "",
  rootId: null,
  rootShortName: "",
  positionType: "",
});

/**นำข้อมูลจาก API มาแสดง */
async function getData() {
  showLoader();
  await http
    .get(config.API.suspendById(dataId))
    .then((res) => {
      const dataGet = res.data.result;
      mainData.value = res.data.result;
      dataProfile.value = dataGet as DataProfile;

      data.id = dataGet.id;
      data.personId = dataGet.personId;
      data.citizenId = dataGet.citizenId;
      data.name = `${dataGet.prefix}${dataGet.firstName} ${dataGet.lastName}`;
      data.prefix = dataGet.prefix;
      data.firstName = dataGet.firstName;
      data.lastName = dataGet.lastName;
      data.organization = dataGet.organization;
      data.position = dataGet.position;
      data.posNo = dataGet.posNo;
      data.positionLevel = dataGet.positionLevel;
      data.positionType = dataGet.positionType;
      data.salary = dataGet.salary;
      data.status = dataGet.status;
      data.descriptionSuspend = dataGet.descriptionSuspend
        ? dataGet.descriptionSuspend
        : "ออกจากราชการ";
      data.startDateSuspend = dataGet.startDateSuspend;
      data.endDateSuspend = dataGet.endDateSuspend;
      data.title = dataGet.title;
      data.offenseDetails = dataGet.offenseDetails;
      data.disciplinaryFaultLevel = dataGet.disciplinaryFaultLevel;
      data.disciplinaryCaseFault = dataGet.disciplinaryCaseFault;
      data.child1 = dataGet.child1;
      data.child1Id = dataGet.child1Id;
      data.child1ShortName = dataGet.child1ShortName;
      data.child2 = dataGet.child2;
      data.child2Id = dataGet.child2Id;
      data.child2ShortName = dataGet.child2ShortName;
      data.child3 = dataGet.child3;
      data.child3Id = dataGet.child3Id;
      data.child3ShortName = dataGet.child3ShortName;
      data.child4 = dataGet.child4;
      data.child4Id = dataGet.child4Id;
      data.child4ShortName = dataGet.child4ShortName;
      data.root = dataGet.root;
      data.rootId = dataGet.rootId;
      data.rootShortName = dataGet.rootShortName;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชั่น Cancle
 */
async function clickCancel() {
  edit.value = false;
  const dataGet = mainData.value;
  if (dataGet) {
    data.id = dataGet.id;
    data.personId = dataGet.personId;
    data.citizenId = dataGet.citizenId;
    data.name = `${dataGet.prefix}${dataGet.firstName} ${dataGet.lastName}`;
    data.prefix = dataGet.prefix;
    data.firstName = dataGet.firstName;
    data.lastName = dataGet.lastName;
    data.organization = dataGet.organization;
    data.position = dataGet.position;
    data.posNo = dataGet.posNo;
    data.positionLevel = dataGet.positionLevel;
    data.positionType = dataGet.positionType;
    data.salary = dataGet.salary;
    data.status = dataGet.status;
    data.descriptionSuspend = dataGet.descriptionSuspend
      ? dataGet.descriptionSuspend
      : "ออกจากราชการ";
    data.startDateSuspend = dataGet.startDateSuspend;
    data.endDateSuspend = dataGet.endDateSuspend;
    data.title = dataGet.title;
    data.offenseDetails = dataGet.offenseDetails;
    data.disciplinaryFaultLevel = dataGet.disciplinaryFaultLevel;
    data.disciplinaryCaseFault = dataGet.disciplinaryCaseFault;
    data.child1 = dataGet.child1;
    data.child1Id = dataGet.child1Id;
    data.child1ShortName = dataGet.child1ShortName;
    data.child2 = dataGet.child2;
    data.child2Id = dataGet.child2Id;
    data.child2ShortName = dataGet.child2ShortName;
    data.child3 = dataGet.child3;
    data.child3Id = dataGet.child3Id;
    data.child3ShortName = dataGet.child3ShortName;
    data.child4 = dataGet.child4;
    data.child4Id = dataGet.child4Id;
    data.child4ShortName = dataGet.child4ShortName;
    data.root = dataGet.root;
    data.rootId = dataGet.rootId;
    data.rootShortName = dataGet.rootShortName;
  }
  myForm.value?.resetValidation();
  // await getData();
}

/**
 * ฟังก์ชั่น Saveจาก API
 */
async function saveData() {
  dialogConfirm($q, async () => {
    const body = {
      organization: data.organization,
      positionType: data.positionType,
      posNo: data.posNo,
      position: data.position,
      positionLevel: data.positionLevel,
      salary: data.salary,
      descriptionSuspend: data.descriptionSuspend,
      startDateSuspend: data.startDateSuspend,
      endDateSuspend: data.endDateSuspend,
    };
    showLoader();
    await http
      .put(config.API.suspendById(dataId), body)
      .then(async () => {
        await getData();
        success($q, "แก้ไขข้อมูลเพื่อลงบัญชีแนบท้ายสำเร็จ");
        edit.value = false;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        hideLoader();
      });
  });
}

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

function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

/** เช็ควันที่สิ้นสุดต้องมากกว่า หรือเท่ากับวันเริ่ม */
function changeFormDataDate() {
  const startDate = new Date(data.startDateSuspend as Date);
  const endDate = new Date(data.endDateSuspend as Date);
  if (startDate > endDate) {
    data.endDateSuspend = null;
  }
}

/** Hook */
onMounted(async () => {
  const user = await tokenParsed();
  if (user) {
    roleAdmin.value = await user.role.includes("placement1");
  }
  await getData();
});
</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)"
    />
    รายละเอียดผู้ถูกพักราชการ {{ data.name }}
  </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="saveData"
      @reset="clickCancel"
    >
      <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">
          {{
            checkRoutePermission
              ? "รายละเอียดข้อมูลบัญชีแนบท้าย"
              : "แก้ไขข้อมูลเพื่อลงบัญชีแนบท้าย"
          }}
        </div>
        <q-space />

        <div
          v-if="
            data.status !== 'DONE' &&
            data.status !== 'REPORT' &&
            !checkRoutePermission
          "
        >
          <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"
              type="reset"
            />
          </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="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="data.positionType"
                :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="data.positionLevel"
                :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="data.posNo"
                :rules="[(val:string) => !!val || `${'กรุณากรอกตำแหน่งเลขที่'}`]"
                hide-bottom-space
                :label="`${'ตำแหน่งเลขที่'}`"
              />
            </div>
          </div>
          <!-- <div class="col-xs-6 col-sm-3 row">
            <div class="col-12">
              <q-input
                v-model="data.salary"
                :outlined="edit"
                dense
                :readonly="!edit"
                hide-bottom-space
                :borderless="!edit"
                :label="`${'เงินเดือน'}`"
                :rules="[(val:number) => !!val || `${'กรุณากรอกเงินเดือน'}`]"
                lazy-rules
                mask="###,###,###,###"
                reverse-fill-mask
                class="inputgreen"
              />
            </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="data.organization"
                :rules="[(val:string) => !!val || `${'กรุณากรอก'}`]"
                hide-bottom-space
                :label="`${'สังกัด'}`"
              />
            </div>
          </div>
          <div class="col-xs-3 col-sm-3 row">
            <div class="col-12">
              <datepicker
                menu-class-name="modalfix"
                :readonly="!edit"
                v-model="data.startDateSuspend"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                @update:model-value="changeFormDataDate()"
              >
                <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="
                      data.startDateSuspend !== null
                        ? date2Thai(data.startDateSuspend)
                        : 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-3 col-sm-3 row">
            <div class="col-12">
              <datepicker
                menu-class-name="modalfix"
                :readonly="!edit || data.startDateSuspend === null"
                v-model="data.endDateSuspend"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                :min-date="data.startDateSuspend"
              >
                <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 || data.startDateSuspend === null"
                    :borderless="!edit"
                    :model-value="
                      data.endDateSuspend !== null
                        ? date2Thai(data.endDateSuspend)
                        : null
                    "
                    :rules="[(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
              :outlined="edit"
              dense
              readonly
              :borderless="!edit"
              v-model="data.title"
              hide-bottom-space
              :label="`${'เรื่องร้องเรียน '}`"
              type="textarea"
            />
          </div>
          <div class="col-3">
            <q-select
              for="#fault"
              :outlined="edit"
              dense
              readonly
              v-model="data.offenseDetails"
              :options="dataStore.offenseDetailsOps"
              label="ผลการสืบสวน"
              emit-value
              map-options
              option-label="name"
              option-value="id"
              use-input
              ><template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="col-4">
            <q-input
              :outlined="edit"
              dense
              readonly
              :borderless="!edit"
              v-model="data.disciplinaryFaultLevel"
              hide-bottom-space
              :label="`${'ระดับโทษความผิด'}`"
            />
          </div>
          <div class="col-12">
            <q-input
              :outlined="edit"
              dense
              lazy-rules
              readonly
              :borderless="!edit"
              v-model="data.disciplinaryCaseFault"
              hide-bottom-space
              :label="`${'กรณีความผิด '}`"
              type="textarea"
            />
          </div>
          <div class="col-12">
            <q-input
              :class="getClass(edit)"
              :outlined="edit"
              dense
              lazy-rules
              :readonly="!edit"
              :borderless="!edit"
              v-model="data.descriptionSuspend"
              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>
