<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md q-mt-md">
    <HeaderTop
      v-model:edit="edit"
      header="ข้อมูลราชการ"
      icon="mdi-account-tie"
      :save="saveData"
      :history="true"
      :changeBtn="changeBtn"
      :disable="statusEdit"
      :cancel="refreshData"
      :historyClick="clickHistory"
    />
    <q-form ref="myform" class="col-12">
      <div class="row col-12 items-center q-col-gutter-x-xs q-col-gutter-y-xs">
        <div class="col-xs-12">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.ocId"
            :label="`${'สังกัด'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3" v-if="employeeClass != 'temp'">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.numberId"
            :label="`${'ตำแหน่งเลขที่'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.positionId"
            :label="`${'ตำแหน่ง'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.positionPathSide"
            :label="`${'ด้าน/สาขา'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.positionLine"
            :label="`${'สายงาน'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.positionType"
            :label="`${'ประเภท'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3" v-if="employeeClass != 'temp'">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.positionLevel"
            :label="`${'ระดับ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.positionExecutive"
            :label="`${'ตำแหน่งทางการบริหาร'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.positionExecutiveSide"
            :label="`${'ด้านตำแหน่งทางการบริหาร'}`"
          />
        </div>
        <div class="col-12 q-py-md"><q-separator /></div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <datepicker
            v-model="govermentData.containDate"
            :locale="'th'"
            autoApply
            :enableTimePicker="false"
            week-start="0"
            :max-date="new Date()"
            :disabled="!edit"
            @update:model-value="handleDate"
          >
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                :model-value="date2Thai(new Date(govermentData.containDate))"
                :rules="[
                  (val) =>
                    !!val ||
                    `${
                      profileType == 'officer'
                        ? 'กรุณาเลือกวันที่บรรจุ'
                        : 'กรุณาเลือกวันที่แต่งตั้ง'
                    }`,
                ]"
                :label="`${
                  profileType == 'officer' ? 'วันที่บรรจุ' : 'วันที่แต่งตั้ง'
                }`"
              >
                <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 class="col-xs-6 col-sm-3 col-md-3">
          <datepicker
            v-model="govermentData.workDate"
            :locale="'th'"
            autoApply
            :enableTimePicker="false"
            week-start="0"
            :max-date="new Date()"
            :disabled="!edit"
          >
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                :model-value="date2Thai(new Date(govermentData.workDate))"
                :rules="[
                  (val) =>
                    !!val ||
                    `${
                      profileType == 'officer'
                        ? 'กรุณาเลือกเริ่มปฎิบัติราชการ'
                        : 'กรุณาเลือกวันที่จ้างและแต่งตั้งมีผล'
                    }`,
                ]"
                :label="`${
                  profileType == 'officer'
                    ? 'เริ่มปฎิบัติราชการ'
                    : 'วันที่จ้างและแต่งตั้งมีผล'
                }`"
              >
                <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 class="col-xs-6 col-sm-6 col-md-6" v-if="profileType == 'officer'">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            stack-label
            :readonly="!edit"
            :borderless="!edit"
            v-model="govermentData.reasonSameDate"
            :label="`${'เหตุผลกรณีไม่ตรงวัน'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.retireDate"
            :label="`${'วันเกษียณอายุ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.ageAll"
            :label="`${'อายุราชการ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.absent"
            :label="`${'ขาดราชการ'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(false)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            :model-value="govermentData.age"
            :label="`${'อายุราชการเกื้อกูล'}`"
          />
        </div>
      </div>
    </q-form>
  </q-card>
  <HistoryTable
    :rows="rowsHistory"
    :columns="columnsHistory"
    :filter="filterHistory"
    :visible-columns="visibleColumnsHistory"
    v-model:modal="modalHistory"
    v-model:inputfilter="filterHistory"
    v-model:inputvisible="visibleColumnsHistory"
    v-model:tittle="tittleHistory"
  >
    <template #columns="props">
      <q-tr :props="props">
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div
            v-if="
              col.name == 'dateStart' ||
              col.name == 'dateAppoint' ||
              col.name == 'createdAt'
            "
            class="table_ellipsis"
          >
            {{ date2Thai(col.value) }}
          </div>
          <div v-else class="table_ellipsis">
            {{ col.value }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </HistoryTable>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useCounterMixin } from "@/stores/mixin";

import { useQuasar } from "quasar";
import type { Goverment } from "@/components/information/interface/profileType";
import { defaultGoverment } from "@/components/information/interface/profileType";
import HeaderTop from "@/components/information/top.vue";
import http from "@/plugins/http";
import config from "@/app.config";
import HistoryTable from "@/components/TableHistory.vue";
import type { RequestItemsHistoryObject } from "@/components/information/interface/request/Government";
import type { ResponseObject } from "@/components/information/interface/response/Government";
import { useRoute } from "vue-router";
import { useComponentProfileDataStore } from "@/components/information/store/store";
import { storeToRefs } from "pinia";
import type { QTableProps } from "quasar";

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
  profileType: {
    type: String,
    required: true,
  },
  employeeClass: {
    type: String,
    required: true,
  },
});
const emit = defineEmits(["update:statusEdit"]);

const route = useRoute();
const $q = useQuasar();

const mixin = useCounterMixin();
const { date2Thai, success, dateToISO, messageError, showLoader, hideLoader } =
  mixin;
const profileStore = useComponentProfileDataStore();
const { birthDate, retireText } = storeToRefs(profileStore);
const edit = ref<boolean>(false);
const govermentData = ref<Goverment>(defaultGoverment);
const myform = ref<any>();
const rowsHistory = ref<RequestItemsHistoryObject[]>([]); //select data history
const tittleHistory = ref<string>("ประวัติแก้ไขข้อมูลราชการ"); //
const filterHistory = ref<string>(""); //search data table history
const modalHistory = ref<boolean>(false); //modal ประวัติการแก้ไขข้อมูล
const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "oc",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "oc",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionPathSide",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "positionPathSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "position",
    align: "left",
    label: "ด้าน/สาขา",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posNo",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionLine",
    align: "left",
    label: "สายงาน",
    sortable: true,
    field: "positionLine",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionType",
    align: "left",
    label: "ประเภท",
    sortable: true,
    field: "positionType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionLevel",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionExecutive",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "positionExecutive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionExecutiveSide",
    align: "left",
    label: "ด้านทางการบริหาร",
    sortable: true,
    field: "positionExecutiveSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateAppoint",
    align: "left",
    label: "วันที่บรรจุ",
    sortable: true,
    field: "dateAppoint",
    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",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "retireDate",
    align: "left",
    label: "วันเกษียณอายุ",
    sortable: true,
    field: "retireDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "govAge",
    align: "left",
    label: "อายุราชการ",
    sortable: true,
    field: "govAge",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "govAgeAbsent",
    align: "left",
    label: "ขาดราชการ",
    sortable: true,
    field: "govAgeAbsent",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "govAgePlus",
    align: "left",
    label: "อายุราชการเกื้อกูล",
    sortable: true,
    field: "govAgePlus",
    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: "createdFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "createdFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumnsHistory = ref<String[]>([
  "oc",
  "position",
  "positionPathSide",
  "posNo",
  "positionLine",
  "positionType",
  "positionLevel",
  "positionexecutive",
  "positionExecutiveSide",
  "dateAppoint",
  "dateStart",
  "retireDate",
  "govAge",
  "govAgeAbsent",
  "govAgePlus",
  "reasonSameDate",
  "createdFullName",
  "createdAt",
]);

onMounted(async () => {
  await fetchData();
  emit("update:statusEdit", false);
});

watch(birthDate, async () => {
  await fetchData();
});

watch(retireText, async () => {
  govermentData.value.retireDate = retireText.value;
});

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.profileGovId(route.params.id.toString()))
    .then((res) => {
      const data: ResponseObject = res.data.result;
      govermentData.value.ocId = data.oc;
      govermentData.value.positionId = data.position;
      govermentData.value.positionPathSide = data.positionPathSide;
      govermentData.value.positionLine = data.positionLine;
      govermentData.value.positionType = data.positionType;
      govermentData.value.positionLevel = data.positionLevel;
      govermentData.value.numberId = data.posNo;
      govermentData.value.positionExecutive = data.positionExecutive;
      govermentData.value.positionExecutiveSide = data.positionExecutiveSide;
      govermentData.value.containDate = new Date(data.dateAppoint);
      govermentData.value.workDate = new Date(data.dateStart);
      govermentData.value.retireDate = data.retireDate;
      govermentData.value.absent = data.govAgeAbsent;
      govermentData.value.age = data.govAgePlus;
      govermentData.value.ageAll = data.govAge;
      govermentData.value.reasonSameDate = data.reasonSameDate;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
};

const refreshData = async () => {
  myform.value.reset();
  await fetchData();
};

const editData = async () => {
  showLoader();
  await http
    .put(config.API.profileGovId(route.params.id.toString()), {
      dateAppoint: dateToISO(govermentData.value.containDate),
      dateStart: dateToISO(govermentData.value.workDate),
      reasonSameDate: govermentData.value.reasonSameDate,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      emit("update:statusEdit", false);
      edit.value = false;
      await refreshData();
    });
};

const saveData = async () => {
  await myform.value.validate().then(async (success: boolean) => {
    if (success) {
      await editData();
    } else {
    }
  });
};

const handleDate = async (modelData: Date) => {
  govermentData.value.containDate = modelData;
  await fetchCalAgeGov(modelData);
};

const fetchCalAgeGov = async (date: Date) => {
  showLoader();
  const body = {
    dateAppoint: date,
  };
  await http
    .post(config.API.profileCalGovId(route.params.id.toString()), body)
    .then((res) => {
      const result = res.data.result;
      govermentData.value.ageAll = result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
};

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลที่เลือก
 */
const clickHistory = async () => {
  modalHistory.value = true;
  showLoader();
  await http
    .get(config.API.profileGovHisId(route.params.id.toString()))
    .then((res) => {
      let data = 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),
          retireDate: e.retireDate,
          govAge: e.govAge,
          govAgeAbsent: e.govAgeAbsent,
          govAgePlus: e.govAgePlus,
          reasonSameDate: e.reasonSameDate,
          createdFullName: e.createdFullName,
          createdAt: new Date(e.createdAt),
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const changeBtn = async () => {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      edit.value = false;
    } else {
      emit("update:statusEdit", true);
    }
  } else {
    emit("update:statusEdit", false);
  }
};

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