<script setup lang="ts">
import { onMounted, ref, reactive } 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 { 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 PopupPersonal from "@/components/Dialogs/PopupPersonal.vue";
  
const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");
/** use */
const dataStore = useDisciplineSuspendStore();
const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const mixin = useCounterMixin();
const dataId = route.params.id.toString();
const {
  date2Thai,
  dialogMessage,
  messageError,
  showLoader,
  hideLoader,
  success,
} = mixin;

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

const data = reactive<dataDetail>({
  id: "",
  personId: "",
  citizenId: "",
  avatar: "",
  name: "",
  prefix: "",
  firstName: "",
  lastName: "",
  organization: "",
  position: "",
  posNo: "",
  positionLevel: "",
  salary: 0,
  status: "",
  descriptionSuspend: "",
  startDateSuspend: null,
  endDateSuspend: null,
  title: "",
  offenseDetails: "",
  disciplinaryFaultLevel: "",
  disciplinaryCaseFault: "",
});

/**นำข้อมูลจาก API มาแสดง */
async function getData(){
  showLoader();
  await http
    .get(config.API.suspendById(dataId))
    .then((res) => {
      const dataGet = res.data.result;
      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.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;
      getAvatar(dataGet.personId)
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 * ฟังชั่น ดึงรูปภาพโปรไฟล์
 * @param id id ของบุคคล
 */
function getAvatar(id:string){
  if(id){
    http
    .get(config.API.profileAvaId(id))
    .then((res)=>{
      console.log(res)
      const dataList = res.data.result
      data.avatar = dataList.avatar
    }).catch((e)=>{

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

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

/**
 * ฟังก์ชั่น Saveจาก API
 */
 async function saveData(){
  const body = {
    organization: data.organization,
    position: data.position,
    posNo: data.posNo,
    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((res: any) => {
      success($q, "แก้ไขข้อมูลเพื่อลงบัญชีแนบท้ายสำเร็จ");
      edit.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await getData();
      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 onclickViewinfo(id: string) {
  modalPersonal.value = true;
  personId.value = id;
}

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 () => {
  if (keycloak.tokenParsed != null) {
    roleAdmin.value = await keycloak.tokenParsed.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>
  <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">
        {{ data.name }}
      </div>
      <q-space />
      <q-btn
        outline
        color="blue"
        dense
        icon-right="mdi-open-in-new"
        class="q-px-sm"
        label="ดูข้อมูลทะเบียนประวัติ"
        @click="onclickViewinfo(data.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="data.avatar" v-if="data.avatar !== '' && data.avatar !== null" />
          <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">
              {{ data.position }}
            </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">
              {{ data.positionLevel }}
            </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">
              {{ data.organization }}
            </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="data.status !== 'DONE' && data.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-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="data.position"
                :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="data.positionLevel"
                :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="data.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="data.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="data.organization"
                :rules="[(val) => !!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
                    lazy-rules
                    :readonly="!edit"
                    :borderless="!edit"
                    :model-value="
                      data.startDateSuspend !== null
                        ? date2Thai(data.startDateSuspend)
                        : 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-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
                    lazy-rules
                    :readonly="!edit || data.startDateSuspend === null"
                    :borderless="!edit"
                    :model-value="
                      data.endDateSuspend !== null
                        ? date2Thai(data.endDateSuspend)
                        : 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
              :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>
