<script setup lang="ts">
import avatar from "@/assets/avatar_user.jpg";
import { ref, reactive, onMounted } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useRegistryInFormationStore } from "@/modules/10_registry/store/registry";
import keycloak from "@/plugins/keycloak";

//หน้าเมนู
import InformationPage from "@/modules/10_registry/tabs/01_information.vue";
import GovernmentPage from "@/modules/10_registry/tabs/02_government.vue";
import SalaryPage from "@/modules/10_registry/tabs/03_salary.vue";
import Certificate from "@/modules/10_registry/tabs/04_Achievement.vue";
import OtherPage from "@/modules/10_registry/tabs/05_other.vue";

import { useRouter } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";

const store = useRegistryInFormationStore();
const $q = useQuasar();
const mixin = useCounterMixin();
const { messageError, dialogConfirm, showLoader, hideLoader } = mixin;
const profileImg = ref<string>("");
const router = useRouter();
const tab = ref<string>("information");
const formData = reactive<any>({
  prefix: "",
  firstName: "",
  lastName: "",
  position: "",
  posExecutiveName: "",
  posTypeName: "",
  posLevelName: "",
});
const sizeImg = ref<string>("");
function onResize(size: any) {
  const width = size.width > 100 ? 100 : size.width;
  sizeImg.value = `${width}px`;
}

function onMobile(type: string) {
  router.push(`/registry/${type}`);
}

function getMain() {
  http.get(config.API.profilePosition()).then((res) => {
    const data = res.data.result;
    formData.prefix = data.prefix;
    formData.firstName = data.firstName;
    formData.lastName = data.lastName;
    formData.position = data.position;

    formData.posTypeName = data.posTypeName;
    formData.posExecutiveName = data.posExecutiveName;
    formData.posLevelName = data.posLevelName;
    store.profileId = data.profileId;
    if (data.avatarName) {
      getImg(data.profileId, data.avatarName);
    } else {
      profileImg.value = avatar;
    }
  });
}

function getImg(id: string, pathName: string) {
  http
    .get(config.API.fileByFile("ทะเบียนประวัติ", "โปรไฟล์", id, pathName))
    .then((res) => {
      profileImg.value = res.data.downloadUrl;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {});
}

function getType() {
  http
    .get(config.API.proFileType)
    .then((res) => {
      store.typeProfile = res.data.result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {});
}

function onClickDownloadKp7(type: string) {
  showLoader();
  const url =
    type === "FULL"
      ? config.API.profileReportId(store.profileId)
      : config.API.profileKp7ShortId(store.profileId);
  const fileName = type === "FULL" ? "ก.พ.7/ก.ก.1" : "ประวัติแบบย่อ";
  http
    .get(url, {
      responseType: "arraybuffer", //
    })
    .then((res) => {
      const data = res.data;
      const blob = new Blob([data], { type: "application/pdf" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `${fileName}.pdf`;
      document.body.appendChild(link);
      link.click();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * logout keycloak
 * confirm ก่อนออกจากระบบ
 */
const doLogout = () => {
  dialogConfirm(
    $q,
    () => {
      keycloak.logout();
    },
    "ยืนยันการออกจากระบบ",
    "ต้องการออกจากระบบใช่หรือไม่"
  );
};

onMounted(async () => {
  store.typeProfile = "OFFICER";
  await getType();
  await getMain();
});
</script>
<template>
  <div class="row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-11">
      <div class="toptitle text-white col-12 row items-center">
        ข้อมูลทะเบียนประวัติ
      </div>
      <div v-if="$q.screen.gt.xs" class="row q-col-gutter-md">
        <div class="col-3">
          <q-card bordered>
            <q-resize-observer @resize="onResize" />
            <q-card-section>
              <div class="relative-position" style="height: 120px">
                <div class="absolute-center">
                  <q-avatar size="120px" class="bg-grey-2">
                    <q-img :src="profileImg" />
                  </q-avatar>
                </div>
              </div>

              <div class="column text-center q-mt-md q-mb-sm">
                <span class="text-teal text-weight-medium">{{
                  formData.firstName
                    ? `${formData.prefix}${formData.firstName} ${formData.lastName}`
                    : "-"
                }}</span>
                <span class="text-grey text-weight-medium">{{
                  formData.position ? `${formData.position}` : "-"
                }}</span>
              </div>
            </q-card-section>

            <q-list separator class="q-mt-md">
              <q-separator />
              <q-item>
                <q-item-section class="text-grey-6">{{
                  store.typeProfile == "OFFICER" ? "ตำแหน่งในสายงาน" : "ตำแหน่ง"
                }}</q-item-section>
                <q-item-section>{{ formData.posExecutiveName }}</q-item-section>
              </q-item>
              <q-item>
                <q-item-section class="text-grey-6">{{
                  store.typeProfile == "OFFICER" ? "ตำแหน่งประเภท" : "กลุ่มงาน"
                }}</q-item-section>
                <q-item-section>{{
                  formData.posTypeName ? formData.posTypeName : "-"
                }}</q-item-section>
              </q-item>
              <q-item>
                <q-item-section class="text-grey-6">{{
                  store.typeProfile == "OFFICER" ? "ระดับ" : "ระดับชั้นงาน"
                }}</q-item-section>
                <q-item-section>{{
                  formData.posLevelName ? formData.posLevelName : "-"
                }}</q-item-section>
              </q-item>
            </q-list>

            <q-card-section class="q-gutter-y-sm">
              <q-btn
                class="full-width"
                unelevated
                color="blue-6"
                @click="onClickDownloadKp7('FULL')"
                ><q-icon left size="2em" name="mdi-file-download-outline" />
                <div>ดาวน์โหลดประวัติแบบย่อ</div></q-btn
              >
              <q-btn
                class="full-width"
                unelevated
                color="primary"
                @click="onClickDownloadKp7('SHORT')"
                ><q-icon left size="2em" name="mdi-folder-download-outline" />
                <div>ดาวน์โหลด ก.พ.7/ก.ก. 1</div></q-btn
              >
            </q-card-section>
          </q-card>
        </div>
        <div class="col-9">
          <q-card bordered>
            <q-tabs
              v-model="tab"
              inline-label
              active-color="blue-6"
              class="bg-grey-1 text-grey-6 shadow-2"
              align="left"
            >
              <q-tab
                name="information"
                label="ข้อมูลส่วนตัว"
                class="bg-active"
              />
              <q-tab name="government" label="ข้อมูลราชการ" />
              <q-tab name="salary" label="ข้อมูลเงินเดือน/ค่าจ้าง" />
              <q-tab name="insignia" label="ข้อมูลผลงาน" />
              <q-tab name="other" label="ข้อมูลอื่นๆ" />
            </q-tabs>

            <q-separator />

            <!-- รายการเเต่ละหน้า -->

            <q-tab-panels v-model="tab" animated>
              <q-tab-panel name="information">
                <InformationPage />
              </q-tab-panel>

              <q-tab-panel name="government">
                <GovernmentPage />
              </q-tab-panel>

              <q-tab-panel name="salary">
                <SalaryPage />
              </q-tab-panel>

              <q-tab-panel name="insignia">
                <Certificate />
              </q-tab-panel>

              <q-tab-panel name="other">
                <OtherPage />
              </q-tab-panel>
            </q-tab-panels>
          </q-card>
        </div>
      </div>

      <div v-else>
        <q-card bordered>
          <q-resize-observer @resize="onResize" />
          <q-card-section>
            <div class="text-center q-mt-md">
              <q-avatar :size="sizeImg">
                <img
                  :src="profileImg"
                  style="border-radius: 50%; object-fit: cover"
                />
              </q-avatar>
            </div>
            <div class="column text-center q-mt-md q-mb-lg">
              <span class="text-teal text-weight-medium">{{
                formData.firstName
                  ? `${formData.prefix}${formData.firstName} ${formData.lastName}`
                  : "-"
              }}</span>
              <span class="text-grey text-weight-medium">{{
                formData.position ? `${formData.position}` : "-"
              }}</span>
            </div>
            <div class="row justify-center q-gutter-x-lg">
              <q-btn
                color="light-blue-1"
                dense
                round
                unelevated
                text-color="light-blue-5"
                size="14px"
                icon="mdi-file-download-outline"
                @click="onClickDownloadKp7('FULL')"
              ></q-btn>
              <q-btn
                color="teal-1"
                text-color="primary"
                dense
                unelevated
                round
                size="14px"
                icon="mdi-folder-download-outline"
                @click="onClickDownloadKp7('SHORT')"
              ></q-btn>
              <q-btn
                color="red-1"
                text-color="red-12"
                unelevated
                dense
                round
                size="14px"
                icon="mdi-logout"
                @click="doLogout"
              ></q-btn>
            </div>
          </q-card-section>

          <q-list separator class="q-mt-md">
            <q-item clickable v-ripple @click="onMobile('information')">
              <q-item-section>ข้อมูลส่วนตัว</q-item-section>
              <q-item-section avatar>
                <q-avatar text-color="info" icon="mdi-chevron-right" />
              </q-item-section>
            </q-item>
            <q-item clickable v-ripple @click="onMobile('government')">
              <q-item-section>ข้อมูลราชการ</q-item-section>
              <q-item-section avatar>
                <q-avatar text-color="info" icon="mdi-chevron-right" />
              </q-item-section>
            </q-item>
            <q-item clickable v-ripple @click="onMobile('salary')">
              <q-item-section>ข้อมูลเงินเดือน/ค่าจ้าง</q-item-section>
              <q-item-section avatar>
                <q-avatar text-color="info" icon="mdi-chevron-right" />
              </q-item-section>
            </q-item>
            <q-item clickable v-ripple @click="onMobile('achievement')">
              <q-item-section>ข้อมูลผลงาน</q-item-section>
              <q-item-section avatar>
                <q-avatar text-color="info" icon="mdi-chevron-right" />
              </q-item-section>
            </q-item>
            <q-item clickable v-ripple @click="onMobile('other')">
              <q-item-section>ข้อมูลอื่นๆ</q-item-section>
              <q-item-section avatar>
                <q-avatar text-color="info" icon="mdi-chevron-right" />
              </q-item-section>
            </q-item>
            <q-item clickable v-ripple disabled>
              <q-item-section>เปลี่ยนรหัสผ่าน</q-item-section>
              <q-item-section avatar>
                <q-avatar text-color="info" icon="mdi-chevron-right" />
              </q-item-section>
            </q-item>
          </q-list>
        </q-card>
      </div>
    </div>
  </div>
</template>
