<template>
  <div class="col-12 row">
    <div class="row col-12" style="padding-top: 80px">
      <div id="information" name="1" class="row col-12 information">
        <!-- <Informationvue
          v-model:statusEdit="statusEdit"
          :profileType="profileType"
        /> -->
        <Information
          v-model:statusEdit="statusEdit"
          :fetchDataProfile="fetchData"
        />
      </div>
      <div id="government" name="16" class="row col-12 q-mt-md">
        <Government
          v-model:statusEdit="statusEdit"
          :profileType="profileType"
          :employeeClass="employeeClass"
        />
      </div>
      <div id="address" name="17" class="row col-12 q-mt-md">
        <Address v-model:statusEdit="statusEdit" />
      </div>
      <div id="family" name="18" class="row col-12 q-mt-md">
        <Family v-model:statusEdit="statusEdit" />
      </div>
      <div id="certicate" name="15" class="row col-12 q-mt-md">
        <Certicate v-model:statusEdit="statusEdit" :profileType="profileType" />
      </div>
      <div id="education" name="2" class="row col-12 q-mt-md">
        <EducationVue v-model:statusEdit="statusEdit" />
      </div>
      <div id="training" name="3" class="row col-12 q-mt-md">
        <TrainVue v-model:statusEdit="statusEdit" />
      </div>
      <div id="insignia" name="4" class="row col-12 q-mt-md">
        <InsigniaVue v-model:statusEdit="statusEdit" />
      </div>
      <div id="coined" name="5" class="row col-12 q-mt-md">
        <CoinedVue v-model:statusEdit="statusEdit" :profileType="profileType" />
      </div>
      <div id="assessment" name="6" class="row col-12 q-mt-md">
        <AssessmentVue
          v-model:statusEdit="statusEdit"
          :profileType="profileType"
        />
      </div>
      <div id="position" name="7" class="row col-12 q-mt-md">
        <SalaryVue
          v-model:statusEdit="statusEdit"
          v-if="profileType === 'officer'"
        />
        <SalaryEmployeeTempVue
          v-model:statusEdit="statusEdit"
          v-else-if="employeeClass === 'temp'"
        />
        <SalaryEmployeeVue v-model:statusEdit="statusEdit" v-else />
      </div>
      <div id="rule" name="8" class="row col-12 q-mt-md">
        <DisciplineVue v-model:statusEdit="statusEdit" />
      </div>
      <div id="leave" name="9" class="row col-12 q-mt-md">
        <LeaveVue v-model:statusEdit="statusEdit" />
      </div>
      <div id="talent" name="10" class="row col-12 q-mt-md">
        <TalentVue v-model:statusEdit="statusEdit" />
      </div>
      <div id="work" name="11" class="row col-12 q-mt-md">
        <WorkVue v-model:statusEdit="statusEdit" />
      </div>
      <div id="record" name="12" class="row col-12 q-mt-md">
        <RecordVue v-model:statusEdit="statusEdit" />
      </div>
      <div id="other" name="13" class="row col-12 q-mt-md">
        <OtherVue v-model:statusEdit="statusEdit" />
      </div>
      <div id="document" name="14" class="row col-12 q-my-md">
        <DocumentVue v-model:statusEdit="statusEdit" />
      </div>
    </div>
    <q-page-sticky
      position="top"
      expand
      class="bg-grey-2 text-white"
      style="z-index: 99; padding: 0% 1% 0% 1%"
    >
      <div
        class="row col-12 q-gutter-sm q-pb-sm text-dark no-wrap items-center"
      >
        <q-btn
          flat
          round
          class="bg-teal-1 full-height"
          color="primary"
          icon="mdi-chevron-left"
          dense
          @click="router.go(-1)"
        >
        </q-btn>
        <q-avatar
          v-if="imageUrl == null"
          size="65px"
          rounded
          class="containerimage"
        >
          <img
            src="@/assets/avatar_user.jpg"
            class="bg-grey-3"
            style="object-fit: cover"
          />
          <div
            class="overlay absolute-bottom text-subtitle2 text-center cursor-pointer"
            @click="clickImage()"
          >
            <q-icon name="mdi-camera" size="18px" color="blue">
              <q-tooltip>อัปเดตรูปภาพ</q-tooltip>
            </q-icon>

            <input
              type="file"
              style="display: none"
              ref="inputImage"
              accept="image/*"
              @change="uploadImage"
            />
          </div>
        </q-avatar>
        <q-avatar v-else size="65px" rounded class="containerimage">
          <img :src="imageUrl" class="bg-grey-3" style="object-fit: cover" />
          <div
            class="overlay absolute-bottom text-subtitle2 text-center cursor-pointer"
            @click="clickImage()"
          >
            <q-icon name="mdi-camera" size="18px" color="blue">
              <q-tooltip>อัปเดตรูปภาพ</q-tooltip>
            </q-icon>

            <input
              type="file"
              style="display: none"
              ref="inputImage"
              accept="image/*"
              @change="uploadImage"
            />
          </div>
        </q-avatar>
        <div class="row items-center text-dark q-ml-md">
          <div class="column">
            <div class="text-bold q-pb-xs text-name">
              {{ fullname }}{{ leaveReason }}
            </div>
            <div>{{ position }}</div>
          </div>
        </div>
        <q-space />

        <q-btn round flat color="blue" icon="mdi-file-document">
          <q-menu transition-show="jump-down" transition-hide="jump-up">
            <q-list dense style="min-width: 160px">
              <q-item clickable v-close-popup @click="helpPost">
                <q-item-section style="min-width: 0px" avatar class="q-py-sm">
                </q-item-section>
                <q-item-section>ช่วยราชการ</q-item-section>
              </q-item>
              <q-separator />
              <q-item clickable v-close-popup @click="repatriationPost">
                <q-item-section style="min-width: 0px" avatar class="q-py-sm">
                </q-item-section>
                <q-item-section>ส่งตัวกลับ</q-item-section>
              </q-item>
              <q-separator />
              <q-item clickable v-close-popup @click="appointPost">
                <q-item-section style="min-width: 0px" avatar class="q-py-sm">
                </q-item-section>
                <q-item-section>แต่งตั้ง-เลื่อน-ย้าย</q-item-section>
              </q-item>
              <q-separator />
              <!-- <q-item clickable v-close-popup @click="relocationPost">
                <q-item-section style="min-width: 0px" avatar class="q-py-sm">
                </q-item-section>
                <q-item-section>ย้าย</q-item-section>
              </q-item>
              <q-separator /> -->
              <q-item clickable v-close-popup @click="clickPassaway">
                <q-item-section style="min-width: 0px" avatar class="q-py-sm">
                </q-item-section>
                <q-item-section>ถึงแก่กรรม</q-item-section>
              </q-item>
              <q-separator />
              <q-item clickable v-close-popup @click="outPost">
                <q-item-section style="min-width: 0px" avatar class="q-py-sm">
                </q-item-section>
                <q-item-section>ให้ออกจากราชการ</q-item-section>
              </q-item>
              <q-separator />
              <q-item clickable v-close-popup @click="dischargePost">
                <q-item-section style="min-width: 0px" avatar class="q-py-sm">
                </q-item-section>
                <q-item-section>ปลดออกจากราชการ</q-item-section>
              </q-item>
              <q-separator />
              <q-item clickable v-close-popup @click="expulsionPost">
                <q-item-section style="min-width: 0px" avatar class="q-py-sm">
                </q-item-section>
                <q-item-section>ไล่ออกจากราชการ</q-item-section>
              </q-item>
              <q-separator />
              <q-item clickable v-close-popup @click="otherPost">
                <q-item-section style="min-width: 0px" avatar class="q-py-sm">
                </q-item-section>
                <q-item-section>อื่นๆ</q-item-section>
              </q-item>
              <q-separator />
            </q-list>
          </q-menu>
          <!-- <q-tooltip>ส่งรายชื่อ</q-tooltip> -->
        </q-btn>

        <q-btn
          round
          flat
          :color="reasonStatus ? 'primary' : 'pink-5'"
          @click="clickRetire()"
          :icon="
            reasonStatus ? 'mdi-home-import-outline' : 'mdi-home-export-outline'
          "
        >
          <q-tooltip>{{
            reasonStatus ? "การกลับเข้ารับราชการ" : "การออกจากราชการ"
          }}</q-tooltip>
        </q-btn>

        <q-btn icon="mdi-file-eye-outline" round color="primary" flat>
          <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
          <q-menu>
            <q-list style="min-width: 100px">
              <q-item clickable v-close-popup @click="clickKp7()">
                <q-item-section class="text-blue">ก.พ.7/ก.ก.1</q-item-section>
              </q-item>
              <q-item clickable v-close-popup @click="clickKp7Short()">
                <q-item-section class="text-primary"
                  >ประวัติแบบย่อ</q-item-section
                >
              </q-item>
            </q-list>
          </q-menu>
        </q-btn>
      </div>
    </q-page-sticky>
  </div>
  <q-dialog v-model="dialog" persistent>
    <q-card style="width: 90vw; max-width: 80vw">
      <q-card-section class="row items-center q-pb-xs col-12">
        <q-space />
        <q-btn
          @click="downloadKP7()"
          unelevated
          class="btn_purple q-mr-sm"
          label="ดาวน์โหลด ก.พ.7/ก.ก.1"
        ></q-btn>
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="closeKp7"
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-card-section>
      <q-card-section class="q-p-sm">
        <!-- <viewpdf
          :src="pdfSrc"
          :currentpage="pdfCurrentPage"
          :totalpage="pdfTotalPage"
        ></viewpdf> -->
      </q-card-section>
    </q-card>
  </q-dialog>
  <q-dialog v-model="dialogShort" persistent>
    <q-card style="width: 90vw; max-width: 80vw">
      <q-card-section class="row items-center q-pb-xs col-12">
        <q-space />
        <q-btn
          @click="downloadKP7Short()"
          unelevated
          class="btn_purple q-mr-sm"
          label="ดาวน์โหลด ประวัติแบบย่อ"
        ></q-btn>
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="closeKp7Short"
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-card-section>
      <q-card-section class="q-p-sm">
        <!-- <viewpdf
          :src="pdfSrcShort"
          :currentpage="pdfCurrentPageShort"
          :totalpage="pdfTotalPageShort"
        ></viewpdf> -->
      </q-card-section>
    </q-card>
  </q-dialog>
  <!-- Dialog เลือก Image -->
  <q-dialog v-model="dialogImage" persistent>
    <q-card style="width: 100vw; max-width: 60vw">
      <q-card-section class="q-py-sm row">
        <div class="text-h6">เลือกรูปภาพ</div>
        <q-space />
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="closeImage"
          style="color: #ff8080; background-color: #ffdede"
        >
          <q-tooltip>ปิดหน้านี้</q-tooltip>
        </q-btn>
      </q-card-section>
      <q-separator />
      <q-card-section class="col-12 row">
        <div
          class="row wrap items-start col-12 q-col-gutter-sm"
          style="height: 320px; overflow: auto"
        >
          <div class="col-3" @click="addNewImage">
            <div
              style="
                height: 160px;
                max-width: 15vw;
                display: flex !important;
                justify-content: center;
                align-items: center;
              "
              class="column rounded-borders cursor-pointer bg-active-image text-white"
            >
              <q-icon name="add" size="60px" color="white" />
              <strong>อัปโหลดรูปภาพ</strong>
            </div>
          </div>
          <div
            v-for="n in images"
            :key="n"
            class="col-3"
            @click="imageActive(n)"
          >
            <div :class="getClass(n)">
              <q-img
                v-if="n.avatar != null"
                :src="n.avatar"
                :class="imageClass(n)"
              >
                <!-- <div
                  class="absolute-top bg-transparent cursor-pointer text-right"
                  style="padding: 5px"
                >
                  <q-btn
                    icon="delete"
                    unelevated
                    round
                    dense
                    @click="deletePhoto"
                    style="color: #ff8080"
                  />
                </div> -->
                <div
                  class="absolute-bottom col-12 cursor-pointer flex justify-between items-center"
                  style="padding: 5px"
                >
                  {{ date2Thai(n.createdDate) }}

                  <q-btn
                    v-if="!n.isActive"
                    icon="delete"
                    unelevated
                    dense
                    @click="deletePhoto(n.id)"
                    class="bg-white"
                    style="color: #ff8080"
                  >
                    <q-tooltip>ลบรูปภาพ</q-tooltip>
                  </q-btn>
                </div>
              </q-img>
            </div>
          </div>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <!-- <q-btn
          flat
          round
          color="red"
          @click="() => {}"
          icon="mdi-delete-outline"
        >
          <q-tooltip>ลบรูปภาพ</q-tooltip>
        </q-btn> -->
        <q-btn
          icon="check"
          dense
          flat
          round
          @click="selectAvatarHistory"
          color="positive"
        >
          <q-tooltip>เลือกรูปภาพ</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
  <!-- Dialog แนบใบมรณบัตร -->
  <q-dialog v-model="dialogPassaway" persistent>
    <div class="col-12">
      <q-card style="width: 100vw; max-width: 60vw">
        <q-form ref="myForm">
          <q-card-section class="q-py-sm row">
            <DialogHeader tittle="ถึงแก่กรรม" :close="closePassaway" />
            <div class="col-12 row q-pa-sm q-col-gutter-sm">
              <q-file
                class="col-12 col-sm-6 col-md-5"
                outlined
                dense
                v-model="filePassaway"
                label="แนบใบมรณบัตร"
                hide-bottom-space
                lazy-rules
                accept=".pdf"
              >
                <q-separator />
                <template v-slot:prepend>
                  <q-icon name="attach_file" />
                </template>
              </q-file>
              <q-input
                class="col-12 col-sm-6 col-md-7"
                dense
                outlined
                v-model="deathCertificateNo"
                label="เลขที่ใบมรณบัตร"
              />

              <datepicker
                class="col-12 col-sm-6 col-md-5"
                menu-class-name="modalfix"
                v-model="dateDeath"
                :locale="'th'"
                autoApply
                borderless
                :enableTimePicker="false"
                week-start="0"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    outlined
                    dense
                    class="full-width datepicker"
                    :model-value="
                      dateDeath != null ? date2Thai(dateDeath) : null
                    "
                    :label="`${'วันที่เสียชีวิต'}`"
                    :rules="[
                      (val) => !!val || `${'กรุณาเลือกวันที่เสียชีวิต'}`,
                    ]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>

              <q-input
                class="col-12 col-sm-6 col-md-7"
                dense
                outlined
                v-model="placeDeathCertificate"
                label="สถานที่ออกใบมรณบัตร"
              />
              <q-separator />
              <q-input
                class="col-12"
                dense
                outlined
                v-model="reasonDeath"
                label="เหตุผลการเสียชีวิต"
                type="textarea"
              />
            </div>
            <q-space />
          </q-card-section>
          <q-separator />
          <div class="flex justify-end q-pa-sm q-gutter-sm">
            <q-btn
              unelevated
              label="บันทึก"
              color="public"
              @click="clickSaveDeceased"
              :disable="
                filePassaway === null ||
                deathCertificateNo === '' ||
                placeDeathCertificate === '' ||
                reasonDeath === ''
              "
            >
              <q-tooltip>บันทึก</q-tooltip>
            </q-btn>
          </div>
          <!-- <DialogFooter
            :save="clickSave"
            :validate="validateData"
            v-model:editvisible="edit"
            v-model:modalEdit="modalEdit"
          /> -->
        </q-form>
      </q-card>
    </div>
  </q-dialog>
  <!-- Dialog เลือก เกษียณ -->
  <q-dialog v-model="dialogLeave" persistent>
    <q-card style="width: 600px">
      <q-toolbar>
        <q-toolbar-title class="text-subtitle2 text-bold"
          >ประเภทการพ้นราชการ
        </q-toolbar-title>
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="closeLeave"
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-toolbar>

      <q-separator />
      <q-card-section class="q-p-sm">
        <div
          class="row col-12 items-center q-col-gutter-x-xs q-col-gutter-y-xs"
        >
          <div class="col-xs-6 col-sm-6 col-md-6">
            <q-select
              class="full-width inputgreen cursor-pointer"
              outlined
              dense
              lazy-rules
              v-model="reason"
              :rules="[(val) => !!val || `${'กรุณาเลือกประเภทการพ้นราชการ'}`]"
              hide-bottom-space
              :label="`${'ประเภทการพ้นราชการ'}`"
              emit-value
              map-options
              option-label="name"
              :options="reasonOptions"
              option-value="id"
            />
          </div>
          <div class="col-xs-6 col-sm-6 col-md-6">
            <datepicker
              menu-class-name="modalfix"
              v-model="leaveDate"
              :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="full-width inputgreen cursor-pointer"
                  outlined
                  dense
                  lazy-rules
                  :model-value="date2Thai(leaveDate)"
                  :rules="[(val) => !!val || `${'กรุณาเลือกวันที่พ้นราชการ'}`]"
                  hide-bottom-space
                  :label="`${'วันที่พ้นราชการ'}`"
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
          </div>
          <div class="col-xs-6 col-sm-6 col-md-6">
            <q-input
              class="full-width inputgreen cursor-pointer"
              outlined
              dense
              lazy-rules
              autogrow
              v-model="leaveDetail"
              :rules="[
                (val) =>
                  !!val || `${'กรุณากรอกสาเหตุ/เหตุผลของการพ้นจากราชการ'}`,
              ]"
              hide-bottom-space
              :label="`${'สาเหตุ/เหตุผลของการพ้นจากราชการ'}`"
            />
          </div>
          <div class="col-xs-6 col-sm-6 col-md-6">
            <q-input
              class="full-width inputgreen cursor-pointer"
              outlined
              dense
              lazy-rules
              autogrow
              v-model="leaveNumberOrder"
              :rules="[(val) => !!val || `${'กรุณากรอกคำสั่ง/เอกสารอ้างอิง'}`]"
              hide-bottom-space
              :label="`${'คำสั่ง/เอกสารอ้างอิง'}`"
            />
          </div>
          <div class="col-xs-6 col-sm-6 col-md-6">
            <datepicker
              menu-class-name="modalfix"
              v-model="leaveDateOrder"
              :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="full-width inputgreen cursor-pointer"
                  outlined
                  dense
                  lazy-rules
                  :model-value="date2Thai(leaveDateOrder)"
                  :rules="[(val) => !!val || `${'กรุณาเลือกวันที่ออกคำสั่ง'}`]"
                  hide-bottom-space
                  :label="`${'วันที่ออกคำสั่ง'}`"
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
          </div>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          flat
          round
          color="public"
          @click="Retire"
          icon="mdi-content-save-outline"
        >
          <q-tooltip>บันทึก</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
  <full-loader :visibility="loader"></full-loader>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useDataStore } from "@/stores/data";
import { useRoute, useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar, QForm } from "quasar";
import EducationVue from "@/modules/04_registry/components/Education.vue";
import DialogHeader from "@/modules/04_registry/components/DialogHeader.vue";
import DialogFooter from "@/modules/04_registry/components/DialogFooter.vue";
import TrainVue from "@/modules/04_registry/components/Train.vue";
import InsigniaVue from "@/modules/04_registry/components/Insignia.vue";
import CoinedVue from "@/modules/04_registry/components/Coin.vue";
import AssessmentVue from "@/modules/04_registry/components/Assessment.vue";
import SalaryVue from "@/modules/04_registry/components/Salary.vue";
import SalaryEmployeeVue from "@/modules/04_registry/components/SalaryEmployee.vue";
import SalaryEmployeeTempVue from "@/modules/04_registry/components/SalaryEmployeeTemp.vue";
import DisciplineVue from "@/modules/04_registry/components/Discipline.vue";
import LeaveVue from "@/modules/04_registry/components/Leave.vue";
import TalentVue from "@/modules/04_registry/components/Talent.vue";
import WorkVue from "@/modules/04_registry/components/Work.vue";
import RecordVue from "@/modules/04_registry/components/Record.vue";
import OtherVue from "@/modules/04_registry/components/Other.vue";
import DocumentVue from "@/modules/04_registry/components/Document.vue";
import Certicate from "@/modules/04_registry/components/Information/Certicate.vue";
import Information from "@/modules/04_registry/components/Information/Information.vue";
import Government from "@/modules/04_registry/components/Information/Government.vue";
import Address from "@/modules/04_registry/components/Information/Address.vue";
import Family from "@/modules/04_registry/components/Information/Family.vue";
import OldName from "@/modules/04_registry/components/Information/OldName.vue";
import type { DataOption } from "@/modules/04_registry/interface/index/Main";
import http from "@/plugins/http";
import config from "@/app.config";

const $q = useQuasar();
const store = useDataStore();
const { changeTab } = store;
const reasonDeath = ref("");
const deathCertificateNo = ref("");
const placeDeathCertificate = ref("");
const mixin = useCounterMixin();
const {
  date2Thai,
  dateToISO,
  messageError,
  dialogMessage,
  success,
  showLoader,
  hideLoader,
  dialogConfirm,
} = mixin;
const route = useRoute();
const router = useRouter();
const imageUrl = ref<any>(null);
const inputImage = ref<any>(null);
const fullname = ref<string>("");
const position = ref<string>("นักจัดการงานทั่วไป");
const dateDeath = ref<Date>(new Date());
const dialog = ref<boolean>(false);
const dialogShort = ref<boolean>(false);
const dialogLeave = ref<boolean>(false);
const dialogImage = ref<boolean>(false);
const dialogPassaway = ref<boolean>(false);
const loader = ref<boolean>(false); //รอโหลด
const statusEdit = ref<boolean>(false);
const activeImage = ref<any | null>(null);
const filePassaway = ref<any>(null);
const images = ref<any>([]);
const checkValidate = ref<boolean>(false); //validate data ผ่านหรือไม่
const myForm = ref<QForm | null>(null); //form data input
const edit = ref<boolean>(false); //เช็คการกดปุ่มแก้ไขใน dialog
const modal = ref<boolean>(false); //modal add detail
const modalEdit = ref<boolean>(false); //modal ที่แสดงใช้สำหรับแก้ไขหรือไม่
const profileId = ref<string>(route.params.id.toString());
const profileType = ref<string>("");
const employeeClass = ref<string>("temp");
const leaveDate = ref<Date>(new Date());
const leaveDetail = ref<string>("");
const leaveNumberOrder = ref<string>("");
const leaveDateOrder = ref<Date>(new Date());
const reason = ref<string>("");
const reasonStatus = ref<boolean>(false);
const leaveReason = ref<string>("");
const reasonOptions = ref<DataOption[]>([
  {
    id: "RETIRE",
    name: "เกษียณอายุราชการ",
  },
  {
    id: "RESIGN",
    name: "ลาออก",
  },
  {
    id: "TRANSFER",
    name: "ให้โอน",
  },
  {
    id: "DEATH",
    name: "ถึงแก่กรรม",
  },
  {
    id: "LAYOFF",
    name: "ให้ออก",
  },
  {
    id: "DISCHARGE",
    name: "ปลดออก",
  },
  {
    id: "DISMISS",
    name: "ไล่ออก",
  },
  //   {
  //     id: "change",
  //     name: "เปลี่ยนประเภทข้าราชการ",
  //   },
  {
    id: "OTHER",
    name: "อื่นๆ",
  },
]);

onMounted(async () => {
  //   await checkProfileData();
  await fetchData();
  await changeTab("information");
});

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.profileAvatarId(profileId.value))
    .then((res) => {
      const data = res.data.result;

      fullname.value = data.fullname;
      imageUrl.value = data.avatar;
      position.value = data.position;
      profileType.value = data.profileType;
      employeeClass.value =
        data.employeeClass == null ? "" : data.employeeClass;
      const reason = reasonOptions.value.filter(
        (r: DataOption) => r.id == data.leaveReason
      );
      if (reason.length > 0) {
        leaveReason.value = ` (พ้นจากราชการด้วยสาเหตุ: ${reason[0].name})`;
      } else {
        leaveReason.value = ` (พ้นจากราชการด้วยสาเหตุ: ${data.leaveReason})`;
      }
      reasonStatus.value = reason.length > 0 ? true : false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const checkProfileData = async () => {
  showLoader();
  await http
    .get(config.API.profileCheckId(profileId.value))
    .then((res) => {
      let data = res.data.result;
      if (data == false) router.push("/registry");
    })
    .catch((e) => {
      router.push("/registry");
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchAvatarHistory = async () => {
  showLoader();
  await http
    .get(config.API.profileAvatarHistoryId(profileId.value))
    .then((res) => {
      let data = res.data.result;
      images.value = [];
      data.map((e: any) => {
        images.value.push({
          id: e.id,
          avatar: e.avatar,
          avatarId: e.avatarId,
          createdDate: new Date(e.createdDate),
          isActive: e.isActive,
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const uploadImage = async (e: any) => {
  let input = e.target.files;
  if (input.length > 0) {
    const formData = new FormData();
    formData.append("FileData", input[0]);
    showLoader();
    await http
      .post(config.API.profileAvatarId(profileId.value), formData)
      .then((res) => {})
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        await fetchData();
        dialogImage.value = false;
      });
    return;
  }
};

const fetchDataDelete = async (id: string) => {
  showLoader();
  await http
    .delete(config.API.profileAvatarHistoryId(id))
    .then((res) => {
      success($q, "ลบรูปภาพสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
      await clickImage();
      //   dialogImage.value = false;
    });
};

const deletePhoto = async (id: string) => {
  dialogMessage(
    $q,
    "ลบข้อมูล",
    "ต้องการทำการลบข้อมูลนี้ใช่หรือไม่",
    "delete",
    undefined,
    "red",
    () => fetchDataDelete(id),
    undefined,
    false
  );
};

const selectAvatarHistory = async () => {
  if (activeImage.value == null) {
    dialogMessage(
      $q,
      "ไม่สามารถเปลี่ยนรูปได้",
      "กรุณาเลือกรูปที่ต้องการเปลี่ยน",
      "warning",
      undefined,
      "orange",
      undefined,
      undefined,
      true
    );
    return;
  }
  showLoader();
  await http
    .put(config.API.profileAvatarId(profileId.value), {
      avatar: activeImage.value.avatarId,
    })
    .then((res) => {
      dialogImage.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
    });
};

const imageActive = (n: any) => {
  activeImage.value = n;
};

const imageClass = (n: any) => {
  const val = n == activeImage.value;
  return {
    "rounded-borders bg-grey-2 image-size-default": val,
    "rounded-borders bg-grey-2 image-size-full": !val,
  };
};

const getClass = (n: any) => {
  const val = n == activeImage.value;
  return {
    "rounded-borders border-green shadow-1": val,
    "rounded-borders shadow-1": !val,
  };
};

const addNewImage = async () => {
  inputImage.value.click();
  await imageActive(null);
};

const clickImage = async () => {
  await fetchAvatarHistory();
  dialogImage.value = true;
};

const closeImage = () => {
  dialogImage.value = false;
};

const closePassaway = () => {
  dialogPassaway.value = false;
};

const closeLeave = () => {
  dialogLeave.value = false;
};

const closeKp7 = () => {
  dialog.value = false;
};

const closeKp7Short = () => {
  dialogShort.value = false;
};

const helpPost = () => {
  dialogConfirm($q, async () => {
    const formData = new FormData();
    formData.append("id", profileId.value);
    await http.post(config.API.placemenHelpGov, formData);
  });
};

const repatriationPost = async () => {
  dialogConfirm($q, async () => {
    const formData = new FormData();
    formData.append("id", profileId.value);
    await http.post(config.API.placemenRepatriation, formData);
  });
};

const appointPost = async () => {
  dialogConfirm($q, async () => {
    const formData = new FormData();
    formData.append("id", profileId.value);
    await http.post(config.API.placemenAppointment, formData);
  });
};

// const relocationPost = async () => {
//   dialogConfirm($q, async () => {
//     const formData = new FormData();
//     formData.append("id", profileId.value);
//     await http.post(config.API.placemenRelocation, formData);
//   });
// };

const outPost = async () => {
  dialogConfirm($q, async () => {
    const formData = new FormData();
    formData.append("id", profileId.value);
    await http.post(config.API.retirementOut, formData);
  });
};

const dischargePost = async () => {
  dialogConfirm($q, async () => {
    const formData = new FormData();
    formData.append("id", profileId.value);
    await http.post(config.API.retirementDischarge, formData);
  });
};

const expulsionPost = async () => {
  dialogConfirm($q, async () => {
    const formData = new FormData();
    formData.append("id", profileId.value);
    await http.post(config.API.retirementExpulsion, formData);
  });
};

const otherPost = async () => {
  dialogConfirm($q, async () => {
    const formData = new FormData();
    formData.append("id", profileId.value);
    await http.post(config.API.placemenOther, formData);
  });
};

const downloadKP7 = () => {};

const downloadKP7Short = () => {};

const clickKp7 = async () => {
  window.open(config.API.profileReportId(profileId.value));
  //   showLoader();
  //   await http
  //     .get(config.API.profileReportId(profileId.value))
  //     .then((res) => {
  //       if (res.data) {
  //         pdfSrc.value = "data:application/pdf;base64," + res.data;
  //         pdfCurrentPage.value = 1;
  //         pdfTotalPage.value = 7;
  //         dialog.value = true;
  //       }
  //     })
  //     .catch((e) => {messageError($q, e);})
  //     .finally(() => {
  //       hideLoader();
  //     });
};

/**
 * กดบันทึกใน dialog
 */
const clickSave = async () => {
  myForm.value!.validate().then(async (result: boolean) => {
    if (result) {
      if (modalEdit.value) {
        await editData();
      } else {
        await saveData();
      }
    }
  });
};

/**
 * บันทึกแก้ไขข้อมูล
 */
const editData = async () => {
  //   modal.value = false;
  //   showLoader();
  //   await http
  //     .put(config.API.getPositionMasterId(positionMasterId.value), {
  //       positionMasterId: positionMasterId.value,
  //       positionTypeId: positionTypeId.value,
  //       positionLineId: positionLineId.value,
  //       positionPathId: positionPathId.value,
  //       positionPathSideId: positionPathSideId.value,
  //       positionExecutiveId: positionExecutiveId.value,
  //       positionExecutiveSideId: positionExecutiveSideId.value,
  //       positionLevelId: positionLevelId.value,
  //       isDirector: isDirector.value,
  //       positionStatusId: positionStatusId.value,
  //       qualification: qualification.value,
  //       positionCondition: positionCondition.value,
  //       positionMasterUserNote: positionMasterUserNote.value,
  //     })
  //     .then((res) => {
  //       success($q, "บันทึกข้อมูลร่างสำเร็จ");
  //     })
  //     .catch((e) => {
  //       statusCode.value = e.response.data.status;
  //     })
  //     .finally(async () => {
  //       edit.value = false;
  //       await fetchData();
  //     });
};

/**
 * บันทึกเพิ่มข้อมูล
 */
const saveData = async () => {
  //   modal.value = false;
  //   showLoader();
  //   await http
  //     .post(config.API.getPositionMaster, {
  //       positionTypeId: positionTypeId.value,
  //       positionLineId: positionLineId.value,
  //       positionPathId: positionPathId.value,
  //       positionPathSideId: positionPathSideId.value,
  //       positionExecutiveId: positionExecutiveId.value,
  //       positionExecutiveSideId: positionExecutiveSideId.value,
  //       positionLevelId: positionLevelId.value,
  //       isDirector: isDirector.value,
  //       positionStatusId: positionStatusId.value,
  //       qualification: qualification.value,
  //       positionCondition: positionCondition.value,
  //       positionMasterUserNote: positionMasterUserNote.value,
  //     })
  //     .then((res) => {
  //       success($q, "บันทึกข้อมูลร่างสำเร็จ");
  //     })
  //     .catch((e) => {
  //       statusCode.value = e.response.data.status;
  //     })
  //     .finally(async () => {
  //       modal.value = false;
  //       await fetchData();
  //     });
};

/**
 * validate input ใน dialog
 */
const validateData = async () => {
  checkValidate.value = true;
  await myForm.value!.validate().then((result: boolean) => {
    if (result == false) {
      checkValidate.value = false;
    }
  });
};
const downloadFilePDF = async (res: string, fileName: string) => {
  const link = document.createElement("a");
  //   link.href = window.URL.createObjectURL(new Blob([res]));
  link.href = window.URL.createObjectURL(
    new Blob([res], {
      type: "application/vnd.ms-excel",
    })
  );
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
};

const clickKp7Short = async () => {
  window.open(config.API.profileKp7ShortId(profileId.value));
  //   showLoader();
  //   await http
  //     .get(config.API.profileKp7ShortId(profileId.value))
  //     .then((res) => {
  //       if (res.data) {
  //         pdfSrcShort.value = "g==";
  //         pdfCurrentPageShort.value = 1;
  //         pdfTotalPageShort.value = 7;
  //         dialogShort.value = true;
  //       }
  //     })
  //     .catch((e) => {messageError($q, e);})
  //     .finally(() => {
  //       hideLoader();
  //     });
};

const clickRetire = async () => {
  if (reasonStatus.value == true) {
    dialogMessage(
      $q,
      "โปรดยืนยัน",
      "ต้องการย้ายข้อมูลจากพ้นราชการไปถือครองใช่หรือไม่",
      "info",
      undefined,
      "primary",
      Retire,
      undefined,
      false
    );
  } else {
    leaveDate.value = new Date();
    leaveDetail.value = "";
    leaveNumberOrder.value = "";
    leaveDateOrder.value = new Date();
    reason.value = "";
    dialogLeave.value = true;
  }
};

const clickPassaway = async () => {
  dialogPassaway.value = true;
};

const Retire = async () => {
  if (reasonStatus.value == true) {
    showLoader();
    await http
      .put(config.API.profileReactive(profileId.value))
      .then((res) => {
        if (res.data) {
          dialogLeave.value = false;
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        router.push("/registry");
      });
  } else {
    showLoader();
    await http
      .put(config.API.profileDeactive(profileId.value), {
        leaveDate: dateToISO(leaveDate.value),
        leaveDetail: leaveDetail.value,
        leaveNumberOrder: leaveNumberOrder.value,
        leaveDateOrder: dateToISO(leaveDateOrder.value),
        reason: reason.value,
      })
      .then((res) => {
        if (res.data) {
          dialogLeave.value = false;
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        router.push("/registry");
      });
  }
};
const clickSaveDeceased = async () => {
  const formData = new FormData();
  formData.append("File", filePassaway.value);
  formData.append("Number", deathCertificateNo.value);
  formData.append("Date", dateToISO(dateDeath.value));
  formData.append("Location", placeDeathCertificate.value);
  formData.append("Reason", reasonDeath.value);
  formData.append("ProfileId", profileId.value);

  $q.dialog({
    title: "ยืนยันการบันทึกข้อมูล",
    message: "ต้องการบันทึกข้อมูลนี้ใช่หรือไม่?",
    cancel: {
      flat: true,
      color: "negative",
    },
    persistent: true,
  })
    .onOk(async () => {
      showLoader();
      await http
        .post(config.API.listDeceased(), formData)
        .then(() => {
          success($q, "บันทึกข้อมูลสำเร็จ");
          router.push("/deceased");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    })
    .onCancel(() => {})
    .onDismiss(() => {});
};
</script>
<style>
.image-size-default {
  height: 150px;
  max-width: 15vw;
}

.image-size-full {
  height: 160px;
  max-width: 15vw;
}

.border-green {
  border: 5px solid #52c688;
}

.area-div {
  background-color: transparent;
}

.text-header {
  font-size: 1.2em;
}

.containerimage {
  position: relative;
}

.containerimage:hover .overlay {
  opacity: 1;
}

.overlay {
  background-color: #e4f2ffd2 !important;
  opacity: 0;
  padding: 2px !important;
}

.information:target {
  padding-top: 84px;
}

.border-custom {
  border: 0.5px solid #c3c3c3;
}

.bg-active-image {
  background-color: #52c688;
}

.text-name {
  font-size: 1.25em;
  overflow: hidden;
}
</style>
