<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="router.push(`/registry/${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 />
      <q-btn
        v-if="!roleAdmin"
        outline
        color="primary"
        dense
        icon-right="arrow_forward"
        class="q-px-sm"
        label="ส่งคำร้องไปยัง สกจ."
        @click="confirmMessage"
      />
      <q-btn
        v-else
        outline
        color="primary"
        dense
        icon-right="download"
        class="q-px-sm"
        label="ดาวน์โหลด"
      />
    </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-3 row items-center">
          <div class="col-12">
            <div class="col-12 text-top">หน่วยงานที่ไล่ออก</div>
            <div class="col-12 text-detail">
              {{ responseData.organization }}
            </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.reason }}
            </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>
    </div>
    <div class="col-12"><q-separator /></div>
    <div class="col-12">
      <d-table
        :rows="rows"
        :columns="columns"
        row-key="fileName"
        hide-header
        hide-bottom
      >
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td key="no" :props="props">
              {{ props.rowIndex + 1 }}
            </q-td>
            <q-td key="fileName" :props="props">
              {{ props.row.fileName }}
            </q-td>
            <q-td key="btnMicrosoft" :props="props">
              <q-btn flat dense round color="red" icon="picture_as_pdf">
                <q-tooltip>ไฟล์ PDF</q-tooltip>
              </q-btn>
              <q-btn flat dense round color="blue" icon="mdi-file-word">
                <q-tooltip>ไฟล์ WORD</q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </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 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="edit = !edit"
        />
      </div>
    </div>
    <div class="col-12"><q-separator /></div>
  </q-card>
</template>
<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 http from "@/plugins/http";
import config from "@/app.config";
import keycloak from "@/plugins/keycloak";

import type { QTableProps, QForm } from "quasar";
import type {
  TypeFile,
  ResponseDataDetail,
} from "@/modules/06_retirement/interface/response/expulsion";

const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const mixin = useCounterMixin();

const personId = route.params.id;
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 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>({
  avataPath: "",
  createdAt: new Date(),
  date: new Date(),
  id: "",
  organization: "",
  organizationPositionOld: "",
  positionLevelOld: "",
  positionNumberOld: "",
  positionTypeOld: "",
  reason: "",
  salary: 0,
  status: "",
  fullname: "",
});

const rows = ref<TypeFile[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fileName",
    align: "left",
    label: "ชื่อไฟล์",
    sortable: true,
    field: "fileName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "btnMicrosoft",
    align: "right",
    label: "ปุ่ม",
    sortable: true,
    field: "btnMicrosoft",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

onMounted(async () => {
  if (keycloak.tokenParsed != null) {
    roleAdmin.value = await keycloak.tokenParsed.role.includes("placement1");
    console.log("roleAdmin===>", roleAdmin.value);
  }
  await getData();
});

const getData = async () => {
  showLoader();
  await http
    .get(config.API.expulsionByid(personId.toString()))
    .then((res: any) => {
      const data = res.data.result;
      //   console.log(data);
      let list: TypeFile[] = [];
      if (data.docs.length > 0) {
        data.docs.map((doc: TypeFile) => {
          list.push({
            pathName: doc.pathName ?? "",
            fileName: doc.fileName ?? "",
          });
        });
      }
      rows.value = list;
      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.avataPath ?? "";
      responseData.value.fullname = `${data.prefix ?? "-"} ${
        data.firstName ?? "-"
      } ${data.lastName ?? "-"}`;

      organizationPositionOld.value = data.organizationPositionOld ?? "";
      positionTypeOld.value = data.positionTypeOld ?? "";
      positionLevelOld.value = data.positionLevelOld ?? "";
      posNo.value = data.posNo ?? "";
      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();
    });
};

const confirmMessage = async () => {
  dialogMessage(
    $q,
    "ต้องการยืนยันส่งคำร้องไปยัง สกจ หรือไม่?",
    "ข้อมูลจะถูกนำส่งคำร้องไปยัง สกจ ทันที",
    "mdi-help-circle-outline",
    "ยืนยัน",
    "primary",
    () => sendConfirm(),
    undefined
  );
};

const sendConfirm = async () => {
  showLoader();
  await http;
  //   .get(config.API.transferConfirmId(personId.toString()))
  //   .then((res: any) => {
  //     //   const data = res.data.result;
  //     //   console.log(data);
  //     success($q, "ส่งคำร้องข้อมูลสำเร็จ");
  //   })
  //   .catch((e) => {
  //     messageError($q, e);
  //   })
  //   .finally(async () => {
  //     await getData();
  //     hideLoader();
  //   });
};

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

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.expulsionByid(personId.toString()), body)
    .then((res: any) => {
      //   const data = res.data.result;
      //   console.log(data);
      success($q, "แก้ไขข้อมูลเพื่อลงบัญชีแนบท้ายสำเร็จ");
      edit.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await getData();
      hideLoader();
    });
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>
<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>
