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

import { useRoute } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";
import type {
  RequestItemsHistoryObject,
  FormMain,
} from "@/modules/04_registryPerson/interface/index/government";

import DialogHeader from "@/components/DialogHeader.vue";

const route = useRoute();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  dateToISO,
  dialogConfirm,
  messageError,
  showLoader,
  hideLoader,
  success,
  pathRegistryEmp,
} = mixin;

/**
 * props
 */
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});
const profileId = ref<string>(route.params.id.toString());
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));
/** ตัวแปรข้อมูลหลัก */
const formMain = reactive<FormMain>({
  ocId: "", //สังกัด
  positionId: "", //ตำแหน่ง
  positionLine: "", //สายงาน
  positionLevel: "", //ระดับ
  numberId: "", //ตำแหน่งเลขที่
  positionExecutive: "", //ตำแหน่งทางการบริหาร
  positionExecutiveSide: "", //ด้านตำแหน่งทางการบริหาร
  positionType: "", //ประเภท
  positionPathSide: "", //ด้าน/สาขา
  containDate: null, //วันที่สั่งบรรจุ
  workDate: null, //วันที่เริ่มปฏิบัติราชการ
  reasonSameDate: "",
  retireDate: null, //วันเกษียณอายุ
  ageAll: {
    year: 0,
    month: 0,
    day: 0,
  }, //อายุราชการ
  absent: 0, //ขาดราชการ
  age: 0, //อายุราชการเกื้อกูล
});

const modalEdit = ref<boolean>(false); //แสดง popup แก้ไขข้อมูลราชการ
const containDate = ref<Date | null>(null);
const workDate = ref<Date | null>(null);
const reasonSameDate = ref<string | null>(null);
const containDateRef = ref<object | null>(null);
const workDateRef = ref<object | null>(null);
const reasonSameDateRef = ref<object | null>(null);

//ประวัติแก้ไขข้อมูลราชการ
const filterKeyword = ref<string>(""); //คำค้นหา
const modalHistory = ref<boolean>(false); //แสดง popup ประวัติแก้ไขข้อมูลราชการ;
const rowsHistory = ref<RequestItemsHistoryObject[]>([]); //ข้อมูลรายการประวัติแก้ไขข้อมูลราชการ
const visibleColumnsHistory = ref<String[]>([
  "dateAppoint",
  "dateStart",
  "reasonSameDate",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "dateAppoint",
    align: "left",
    label: "วันที่บรรจุ",
    sortable: true,
    field: "dateAppoint",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateStart",
    align: "left",
    label: "เริ่มปฎิบัติราชการ",
    sortable: true,
    field: "dateStart",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "reasonSameDate",
    align: "left",
    label: "เหตุผลกรณีไม่ตรงวัน",
    sortable: true,
    field: "reasonSameDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    format: (v) => date2Thai(v, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

/**
 * เปิด dialog *
 */
function openDialogEdit() {
  modalEdit.value = true;
  containDate.value = formMain.containDate ? formMain.containDate : null;
  workDate.value = formMain.workDate ? formMain.workDate : null;
  reasonSameDate.value = formMain.reasonSameDate
    ? formMain.reasonSameDate
    : null;
}

/**
 * เปิด dialog  ประวัติแก้ไขข้อมูลราชการ
 */
function openDialogHistory() {
  modalHistory.value = true;
  filterKeyword.value = "";
  getDataHistory();
}

/**
 * ปิด dialog
 */
function closeDialog() {
  modalEdit.value = false;
  containDate.value = null;
  workDate.value = null;
  reasonSameDate.value = null;
}

/**
 * function ยืนยันการบันทึกข้อมูลราชการ
 */
function onSubmit() {
  dialogConfirm($q, () => {
    showLoader();
    http
      .patch(
        config.API.profileNewGovernmentById(profileId.value, empType.value),
        {
          dateAppoint: containDate.value,
          dateStart: workDate.value,
          reasonSameDate:
            dateToISO(containDate.value as Date) ===
            dateToISO(workDate.value as Date)
              ? ""
              : reasonSameDate.value,
        }
      )
      .then(async () => {
        await getData();
        await success($q, "บันทึกข้อมูลสำเร็จ");
        closeDialog();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * ดึงข้อมูลราชการ
 */
async function getData() {
  showLoader();
  await http
    .get(config.API.profileNewGovernmentById(profileId.value, empType.value))
    .then(async (res) => {
      const data = await res.data.result;
      console.log(data);

      formMain.ocId = data.org ?? "-"; //สังกัด
      formMain.positionId = data.position ?? "-"; //ตำแหน่ง
      formMain.positionLine = data.positionField ?? "-"; //สายงาน
      formMain.positionLevel = data.posLevel ?? "-"; //ระดับ
      formMain.numberId = data.posMasterNo ?? "-"; //ตำแหน่งเลขที่
      formMain.positionType = data.posType ?? "-"; //ประเภท
      formMain.positionExecutive = data.posExecutive ?? "-"; //ตำแหน่งทางการ บริหาร
      formMain.positionPathSide = data.positionArea ?? "-"; //ด้านสาขา
      formMain.positionExecutiveSide = data.positionExecutiveField ?? "-"; //ด้านทางการบริหาร

      formMain.containDate = data.dateAppoint;
      formMain.workDate = data.dateStart;
      formMain.reasonSameDate = data.reasonSameDate;
      formMain.retireDate = data.dateLeave;
      formMain.dateRetireLaw = data.dateRetireLaw;
      formMain.ageAll = data.govAge;
      formMain.absent = data.govAgeAbsent;
      formMain.age = data.govAgePlus;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ดึงข้อมูลประวัติ
 */
async function getDataHistory() {
  showLoader();
  await http
    .get(config.API.profileNewGovernmentHistory(profileId.value, empType.value))
    .then(async (res) => {
      let data = await res.data.result;
      rowsHistory.value = [];
      data.map((e: RequestItemsHistoryObject) => {
        rowsHistory.value.push({
          oc: e.oc,
          position: e.position,
          positionPathSide: e.positionPathSide,
          posNo: e.posNo,
          positionLine: e.positionLine,
          positionType: e.positionType,
          positionLevel: e.positionLevel,
          positionExecutive: e.positionExecutive,
          positionExecutiveSide: e.positionExecutiveSide,
          dateAppoint: new Date(e.dateAppoint),
          dateStart: new Date(e.dateStart),
          dateRetire: e.dateRetire,
          dateRetireLaw: e.dateRetireLaw,
          govAge: e.govAge,
          govAgeAbsent: e.govAgeAbsent,
          govAgePlus: e.govAgePlus,
          reasonSameDate: e.reasonSameDate,
          createdFullName: e.createdFullName,
          createdAt: new Date(e.createdAt),
          lastUpdatedAt: e.lastUpdatedAt,
          lastUpdateFullName: e.lastUpdateFullName,
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 */
onMounted(() => {
  getData();
});
</script>

<template>
  <div class="row">
    <q-space />
    <div class="q-gutter-x-sm">
      <q-btn
        v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
        flat
        dense
        round
        color="edit"
        icon="edit"
        @click="openDialogEdit()"
        ><q-tooltip>แก้ไขข้อมูล</q-tooltip></q-btn
      >
      <q-btn
        flat
        dense
        round
        color="deep-purple"
        icon="mdi-history"
        @click="openDialogHistory()"
        ><q-tooltip>ประวิติข้อมูลราชการ</q-tooltip></q-btn
      >
    </div>
  </div>

  <q-card bordered class="bg-grey-1 q-pa-md q-mt-sm">
    <div class="row q-col-gutter-md">
      <div class="col-12 col-sm-6 col-md-6 q-gutter-y-sm">
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>สังกัด</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ formMain.ocId ? formMain.ocId : "-" }}
          </div>
        </div>
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>{{ empType === "" ? `ตำแหน่งในสายงาน` : `ตำแหน่ง` }}</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ formMain.positionId ? formMain.positionId : "-" }}
          </div>
        </div>
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>ตำแหน่งเลขที่</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ formMain.numberId ? formMain.numberId : "-" }}
          </div>
        </div>
        <div class="row items-center" v-if="empType === ''">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>ตำแหน่งทางการบริหาร</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ formMain.positionExecutive ? formMain.positionExecutive : "-" }}
          </div>
        </div>
        <div class="row items-center" v-if="empType === ''">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>ด้านทางการบริหาร</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{
              formMain.positionExecutiveSide
                ? formMain.positionExecutiveSide
                : "-"
            }}
          </div>
        </div>
      </div>
      <div class="col-12 col-sm-6 col-md-6 q-gutter-y-sm">
        <div class="row items-center" v-if="empType === ''">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>สายงาน</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ formMain.positionLine ? formMain.positionLine : "-" }}
          </div>
        </div>
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>{{ empType === "" ? "ตำแหน่งประเภท" : "กลุ่มงาน" }}</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ formMain.positionType ? formMain.positionType : "-" }}
          </div>
        </div>
        <div class="row items-center">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>{{ empType === "" ? "ระดับ" : "ระดับชั้นงาน" }}</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ formMain.positionLevel ? formMain.positionLevel : "-" }}
          </div>
        </div>
        <div class="row items-center" v-if="empType === ''">
          <div class="col-12 col-sm-12 col-md-5 text-grey-6 text-weight-medium">
            <div>ด้าน/สาขา</div>
          </div>
          <div class="col-12 col-sm-12 col-md-7">
            {{ formMain.positionPathSide ? formMain.positionPathSide : "-" }}
          </div>
        </div>
      </div>
    </div>
    <q-separator color="grey-4" class="q-my-md" />
    <div class="row q-col-gutter-md">
      <div class="col-12 col-sm-6 col-md-6 q-gutter-y-sm">
        <div class="col-12 col-sm-6 col-md-6">
          <div class="row">
            <div class="col-12 col-sm-12 col-md-5">
              <span class="text-grey-6 text-weight-medium"
                >วันที่สั่งบรรจุ</span
              >
            </div>
            <div class="col-12 col-sm-12 col-md-7">
              <span>{{
                formMain.containDate ? date2Thai(formMain.containDate) : "-"
              }}</span>
            </div>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-6">
          <div class="row">
            <div class="col-12 col-sm-12 col-md-5">
              <span class="text-grey-6 text-weight-medium"
                >วันที่เริ่มปฏิบัติราชการ</span
              >
            </div>
            <div class="col-12 col-sm-12 col-md-7">
              <span>{{
                formMain.workDate !== null
                  ? date2Thai(formMain.workDate as Date)
                  : "-"
              }}</span>
            </div>
          </div>
        </div>
        <div
          v-if="dateToISO(formMain.containDate as Date) !== dateToISO(formMain.workDate as Date)"
          class="col-12 col-sm-6 col-md-6"
        >
          <div class="row">
            <div class="col-12 col-sm-12 col-md-5">
              <span class="text-grey-6 text-weight-medium"
                >เหตุผลที่วันที่ไม่ตรงกัน</span
              >
            </div>
            <div class="col-12 col-sm-12 col-md-7">
              <span>{{
                formMain.reasonSameDate !== "" ? formMain.reasonSameDate : "-"
              }}</span>
            </div>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-6">
          <div class="row">
            <div class="col-12 col-sm-12 col-md-5">
              <span class="text-grey-6 text-weight-medium"
                >วันครบเกษียณอายุ</span
              >
            </div>
            <div class="col-12 col-sm-12 col-md-7">
              <span>{{
                formMain.retireDate
                  ? date2Thai(formMain.retireDate as Date)
                  : "-"
              }}</span>
            </div>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-6">
          <div class="row">
            <div class="col-12 col-sm-12 col-md-5">
              <span class="text-grey-6 text-weight-medium"
                >วันที่เกษียณอายุราชการตามกฏหมาย</span
              >
            </div>
            <div class="col-12 col-sm-12 col-md-7">
              <span>{{
                formMain.dateRetireLaw
                  ? date2Thai(formMain.dateRetireLaw as Date)
                  : "-"
              }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="col-12 col-sm-6 col-md-6 q-gutter-y-sm">
        <div class="col-12 col-sm-6 col-md-6">
          <div class="row">
            <div class="col-12 col-sm-12 col-md-5">
              <span class="text-grey-6 text-weight-medium">อายุราชการ</span>
            </div>
            <div class="col-12 col-sm-12 col-md-7">
              <span>{{
                formMain.ageAll
                  ? `${formMain.ageAll.year} ปี ${formMain.ageAll.month} เดือน ${formMain.ageAll.day} วัน`
                  : "-"
              }}</span>
            </div>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-6">
          <div class="row">
            <div class="col-12 col-sm-12 col-md-5">
              <span class="text-grey-6 text-weight-medium">ขาดราชการ</span>
            </div>
            <div class="col-12 col-sm-12 col-md-7">
              <span>{{ formMain.absent ? formMain.absent : 0 }}</span>
            </div>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-6">
          <div class="row">
            <div class="col-12 col-sm-12 col-md-5">
              <span class="text-grey-6 text-weight-medium"
                >อายุราชการเกื้อกูล</span
              >
            </div>
            <div class="col-12 col-sm-12 col-md-7">
              <span>{{ formMain.age ? formMain.age : 0 }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </q-card>

  <!-- dialog edit -->
  <q-dialog v-model="modalEdit" persistent>
    <q-card>
      <q-form @submit.prevent greedy @validation-success="onSubmit">
        <DialogHeader tittle="แก้ไขข้อมูลราชการ" :close="closeDialog" />
        <q-separator color="grey-4" />

        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-xs-12 col-md-6">
              <datepicker
                v-model="containDate"
                :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
                    ref="containDateRef"
                    class="full-width inputgreen cursor-pointer"
                    hide-bottom-space
                    dense
                    outlined
                    :model-value="containDate !== null
          ? date2Thai(containDate as Date)
          : null
        "
                    :rules="[
                      (val:string) => !!val || 'กรุณาเลือก วัน/เดือน/ปี ที่บรรจุ',
                    ]"
                    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-12 col-md-6">
              <datepicker
                v-model="workDate"
                :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
                    ref="workDateRef"
                    class="full-width inputgreen cursor-pointer"
                    hide-bottom-space
                    dense
                    outlined
                    :model-value="workDate !== null
                      ? date2Thai(workDate as Date)
                      : null
                    "
                    :rules="[(val:string) => !!val || 'กรุณาเลือกเริ่มปฎิบัติราชการ']"
                    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-12"
              v-if="containDate && workDate ? dateToISO(containDate as Date) !== dateToISO(workDate as Date) : false"
            >
              <q-input
                ref="reasonSameDateRef"
                class="full-width inputgreen cursor-pointer"
                label="เหตุผลกรณีไม่ตรงกัน"
                type="textarea"
                outlined
                dense
                hide-bottom-space
                :rules="[(val:string) => !!val || 'กรุณากรอก เหตุผลกรณีไม่ตรงกัน']"
                v-model="reasonSameDate"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" id="onSubmit" type="submit" color="public">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <!-- dialog History -->
  <q-dialog v-model="modalHistory" persistent>
    <q-card style="min-width: 80%">
      <DialogHeader
        tittle="ประวัติแก้ไขข้อมูลราชการ"
        :close="() => (modalHistory = !modalHistory)"
      />
      <q-separator color="grey-4" />

      <q-card-section style="max-height: 50vh" class="scroll">
        <div class="row q-pb-sm q-gutter-x-sm">
          <q-space />
          <q-input
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            class="col-2"
            debounce="300"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
          <q-select
            v-model="visibleColumnsHistory"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="columnsHistory"
            option-value="name"
            style="min-width: 140px"
          />
        </div>
        <d-table
          ref="table"
          :columns="columnsHistory"
          :rows="rowsHistory"
          flat
          bordered
          :paging="true"
          dense
          class="custom-header-table"
          :filter="filterKeyword.trim()"
          :visible-columns="visibleColumnsHistory"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                style="color: #000000; font-weight: 500"
              >
                <span class="text-weight-medium">{{ col.label }}</span>
              </q-th>
              <q-th auto-width></q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <div>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
