<script setup lang="ts">
import { ref, watch, computed, onMounted } from "vue";

import { checkPermission } from "@/utils/permissions";
import { useRoute, useRouter } from "vue-router";
import { useRegistryNewDataStore } from "@/modules/04_registryPerson/store";
import { useCounterMixin } from "@/stores/mixin";
import { calculateFiscalYear } from "@/utils/function";

/** importType*/
import { useQuasar, type QTableProps } from "quasar";
import type {
  FormFilter,
  RangeAge,
} from "@/modules/04_registryPerson/interface/request/Main";

/** importComponent*/
import DialogHistory from "@/modules/04_registryPerson/components/DialogHistory.vue";

/* use*/
const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const mixin = useCounterMixin();
const { date2Thai } = mixin;
const store = useRegistryNewDataStore();

//props
const formFilter = defineModel<FormFilter>("formFilter", { required: true }); //ข้อมูลการค้นหา
const maxPage = defineModel<Number>("maxPage", { required: true }); //จำนวนหน้าทั้งหมด
const empType = defineModel<string>("empType", { required: true }); //ประเภท ข้ารายการ,ลูกจ้าง
const isFilter = defineModel<boolean>("isFilter", { required: true }); //แสดงการค้นหา
const props = defineProps({
  rows: { type: Array },
  fetchData: { type: Function },
  fetchType: { type: Function },
  total: { type: Number, default: 0 },
});

const rangeAge = ref<RangeAge>({
  min: 18,
  max: 60,
});

const objMarkerLabel = computed(() => {
  return { 39: `ช่วงอายุ ${rangeAge.value.min}-${rangeAge.value.max} ปี` };
});
const year = ref<number>(calculateFiscalYear(new Date()));

//ตัวแปร
const modalHistory = ref<boolean>(false); //ประวัติถือครองตำแหน่ง
const modalReport = ref<boolean>(false);
//ข้อมูล Table
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: false,
    field: "fullName",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px",
  },
  {
    name: "posNo",
    align: "left",
    label: empType.value === "officer" ? "เลขที่ตำแหน่ง" : "ตำแหน่งเลขที่",
    sortable: false,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: false,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posPath",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: false,
    field: "posType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevel",
    align: "left",
    label: "ระดับ",
    sortable: false,
    field: "posLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.posTypeShortName
        ? row.posTypeShortName + " " + row.posLevel
        : row.posLevel;
    },
  },
  {
    name: "org",
    align: "left",
    label: "สังกัด",
    sortable: false,
    field: "org",
    format(val, row) {
      return val.replace(/(.*)\s(.*)$/, "$1\n$2");
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateAppoint",
    align: "left",
    label: "วันที่บรรจุ",
    sortable: true,
    field: "dateAppoint",
    headerStyle: "font-size: 14px;pointer-events: none;",
    format(val) {
      return date2Thai(val);
    },
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "fullName",
  "posNo",
  "position",
  "posPath",
  "posType",
  "posLevel",
  "org",
  "dateAppoint",
]);
const pagination = ref({
  page: formFilter.value.page,
  rowsPerPage: formFilter.value.pageSize,
  sortBy: "",
  descending: false,
});

watch(
  () => store.formFilter.dateAppoint,
  () => {
    checkFilterDateAppoint();
  }
);

function checkFilterDateAppoint() {
  if (store.formFilter.dateAppoint) {
    pagination.value.sortBy = "dateAppoint";
    pagination.value.descending =
      formFilter.value.dateAppoint === "DESC" ? true : false;
  } else {
    pagination.value.sortBy = "";
  }
}

/**  function เปลี่ยนหน้า Table*/
function updatePagePagination() {
  props.fetchData?.();
}

/**
 * function เปลี่ยนแถวต่อหน้า
 * @param newPagination ข้อมูล Pagination
 */
function updatePageSizePagination(newPagination: any) {
  formFilter.value.page = 1;
  formFilter.value.pageSize = newPagination.rowsPerPage;
}

/**  function เปิด popup ประวัติถือครองตำแหน่ง*/
function onClickHistory() {
  modalHistory.value = !modalHistory.value;
}

/**
 * function rediract หน้ารายละเอียด
 * @param id รายการ
 */
function onClickViewDetail(id: string) {
  if (empType.value === "officer") {
    window.open(`/registry-officer/${id}`, "_blank");
  } else {
    window.open(`/registry-employee/${id}`, "_blank");
  }
}

/** function redirect ไปหน้ารายการคำร้องขอแก้ไขข้อมูล*/
function redirectToPagePetition() {
  if (empType.value === "officer") {
    router.push(`/registry-officer/request-edit`);
  } else {
    router.push(`/registry-employee/request-edit`);
  }
}

/**
 * ดูการเปลี่ยนแปลงของ formFilter.value.pageSize
 * เมื่อมีการเปลี่ยนแปลงจำทำการดึงข้อมูลรายการทะเบียนประวัติใหม่ตามจำนวน  formFilter.value.pageSize
 */
watch(
  () => formFilter.value.pageSize,
  () => {
    props.fetchData?.();
  }
);

const isPageRetired = ref<boolean>(false); // หน้าทะเบียนประวัติข้าราชการพ้นจากราชการ
onMounted(() => {
  checkFilterDateAppoint();
  if (
    route.name === "registryRetireOfficer" ||
    route.name === "registryRetireEmployee"
  ) {
    isPageRetired.value = true;
  }
});
</script>

<template>
  <div class="col-12 row q-pb-sm q-col-gutter-sm items-center">
    <div v-if="!isPageRetired" class="row q-gutter-sm">
      <q-btn
        v-if="
          empType === 'officer' ||
          (empType === 'perm' && checkPermission($route)?.attrIsUpdate)
        "
        color="primary"
        label="รายการคำร้องขอแก้ไข"
        @click="redirectToPagePetition()"
      >
        <q-tooltip>รายการคำร้องขอแก้ไข</q-tooltip></q-btn
      >
      <q-btn
        v-if="checkPermission($route)?.attrIsGet"
        round
        flat
        dense
        color="deep-purple"
        icon="mdi-history"
        @click="onClickHistory"
      >
        <q-tooltip>ประวัติถือครองตำแหน่ง</q-tooltip></q-btn
      >
    </div>
    <q-space />
    <div v-if="total > 0" class="text-teal">
      พบข้อมูลทั้งหมด {{ total.toLocaleString() }} รายการ
    </div>
    <!-- empType === "officer" ? -->
    <!-- <div>
      <q-btn
        flat
        dense
        icon="download"
        color="primary"
        round
        @click="onGovernment"
        ><q-tooltip
          >รายงานสถิติข้อมูล{{
            empType == "officer" ? "ข้าราชการ กทม. สามัญ" : "ลูกจ้างประจำ กทม."
          }}</q-tooltip
        ></q-btn
      >
    </div> -->
    <q-select
      v-if="store.mode === 'table'"
      v-model="visibleColumns"
      multiple
      outlined
      dense
      options-dense
      :display-value="$q.lang.table.columns"
      emit-value
      map-options
      :options="columns"
      option-value="name"
      style="min-width: 140px"
      class="full-height"
      hide-bottom-space
    />
    <div>
      <q-btn-toggle
        v-model="store.mode"
        dense
        class="my-custom-toggle no-shadow"
        toggle-color="grey-4"
        :options="[
          { value: 'table', slot: 'table' },
          { value: 'card', slot: 'card' },
        ]"
      >
        <template v-slot:table>
          <q-icon
            name="format_list_bulleted"
            class="q-px-sm q-py-xs"
            size="22px"
            :style="{
              color: store.mode === 'table' ? '#787B7C' : '#C9D3DB',
            }"
          />
        </template>

        <template v-slot:card>
          <q-icon
            name="mdi-view-grid-outline"
            size="22px"
            class="q-px-sm q-py-xs"
            :style="{
              color: store.mode === 'card' ? '#787B7C' : '#C9D3DB',
            }"
          />
        </template>
      </q-btn-toggle>
    </div>
  </div>

  <d-table
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :card-container-class="store.mode === 'card' ? 'q-col-gutter-md' : ''"
    :columns="columns"
    :rows="props.rows"
    :grid="store.mode === 'card'"
    :paging="true"
    v-model:pagination="pagination"
    :rows-per-page-options="[20, 50, 100]"
    :visible-columns="visibleColumns"
    @update:pagination="updatePageSizePagination"
  >
    >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th v-for="col in props.cols" :key="col.name" :props="props">
          <span class="text-weight-medium" v-if="col.name === 'posLevel'">{{
            empType === "officer" ? col.label : "ระดับชั้นงาน"
          }}</span>
          <span class="text-weight-medium" v-else-if="col.name === 'posPath'">{{
            empType === "officer" ? col.label : "กลุ่มงาน"
          }}</span>
          <span
            class="text-weight-medium"
            v-else-if="col.name === 'position'"
            >{{ empType === "officer" ? col.label : "ตำแหน่ง" }}</span
          >

          <span class="text-weight-medium" v-else>{{ col.label }}</span>
        </q-th>
      </q-tr>
    </template>
    <template v-slot:body="props" v-if="store.mode === 'table'">
      <q-tr :props="props">
        <q-td v-for="col in props.cols" :key="col.id">
          <div v-if="col.name === 'no'">
            {{
              (
                (formFilter.page - 1) * formFilter.pageSize +
                props.rowIndex +
                1
              )?.toLocaleString()
            }}
          </div>
          <div v-else-if="col.name == 'fullName'">
            <div class="row col-12 wrap items-center">
              <q-item>
                <q-item-section avatar>
                  <q-avatar size="50px" class="bg-grey-2">
                    <q-img :src="props.row.avatar" />
                  </q-avatar>
                </q-item-section>
                <q-item-section>
                  <div
                    v-if="!checkPermission($route)?.attrIsGet"
                    class="text-weight-medium"
                  >
                    {{
                      `${
                        props.row.rank
                          ? props.row.rank
                          : props.row.prefix
                          ? props.row.prefix
                          : ""
                      }${props.row.firstName} ${props.row.lastName}`
                    }}
                  </div>
                  <div
                    v-else
                    class="text-weight-medium text-blue-4 cursor-pointer"
                    @click="
                      checkPermission($route)?.attrIsGet &&
                        onClickViewDetail(props.row.id)
                    "
                  >
                    <q-tooltip>รายละเอียด</q-tooltip>
                    {{
                      `${
                        props.row.rank
                          ? props.row.rank
                          : props.row.prefix
                          ? props.row.prefix
                          : ""
                      }${props.row.firstName} ${props.row.lastName}`
                    }}
                    <q-icon name="mdi-open-in-new" size="xs"></q-icon>
                  </div>
                  <div class="text-weight-light">
                    {{ props.row.citizenId }}
                  </div>
                </q-item-section>
              </q-item>
            </div>
          </div>

          <div v-else-if="col.name === 'org'" class="text-html">
            {{ col.value ? col.value : "-" }}
          </div>
          <div v-else-if="col.name === 'posNo'">
            {{ col.value && col.value != "undefined" ? col.value : "-" }}
          </div>
          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:item="props" v-else>
      <div class="col-xs-12 col-sm-4 col-md-3">
        <q-card flat bordered>
          <q-card-section class="text-center q-pb-none">
            <q-avatar size="80px" class="bg-grey-2">
              <q-img :src="props.row.avatar" />
            </q-avatar>

            <div
              v-if="!checkPermission($route)?.attrIsGet"
              class="text-weight-medium q-mt-sm"
            >
              {{
                `${
                  props.row.rank
                    ? props.row.rank
                    : props.row.prefix
                    ? props.row.prefix
                    : ""
                }${props.row.firstName} ${props.row.lastName}`
              }}
            </div>
            <div
              v-else
              class="text-weight-medium q-mt-md text-blue-4 cursor-pointer"
              @click="
                checkPermission($route)?.attrIsGet &&
                  onClickViewDetail(props.row.id)
              "
            >
              <q-tooltip>รายละเอียด</q-tooltip>
              {{
                `${
                  props.row.rank
                    ? props.row.rank
                    : props.row.prefix
                    ? props.row.prefix
                    : ""
                }${props.row.firstName} ${props.row.lastName}`
              }}
              <q-icon name="mdi-open-in-new" size="xs"></q-icon>
            </div>
            <div class="text-weight-light full-width text-center">
              {{ props.row.citizenId }}
            </div>
          </q-card-section>

          <q-card-section class="q-pa-sm">
            <q-card bordered class="bg-grey-13">
              <q-card-section>
                <div class="text-grey">
                  {{
                    empType === "officer" ? `เลขที่ตำแหน่ง` : `ตำแหน่งเลขที่`
                  }}
                </div>
                <div class="text-subtitle2 text-black q-ml-sm">
                  {{
                    props.row.posNo && props.row.posNo != "undefined"
                      ? props.row.posNo
                      : "-"
                  }}
                </div>

                <div class="text-grey">
                  {{ empType === "officer" ? `ตำแหน่งในสายงาน` : `ตำแหน่ง` }}
                </div>
                <div class="text-subtitle2 text-black q-ml-sm">
                  {{ props.row.position ? props.row.position : "-" }}
                </div>

                <div class="text-grey">
                  {{ empType === "officer" ? "ตำแหน่งประเภท" : "กลุ่มงาน" }}
                </div>
                <div class="text-subtitle2 text-black q-ml-sm">
                  {{ props.row.posType ? props.row.posType : "-" }}
                </div>

                <div class="text-grey">
                  {{ empType === "officer" ? "ระดับ" : "ระดับชั้นงาน" }}
                </div>
                <div class="text-subtitle2 text-black q-ml-sm">
                  {{
                    props.row.posLevel
                      ? props.row.posTypeShortName
                        ? `${props.row.posTypeShortName} ${props.row.posLevel}`
                        : props.row.posLevel
                      : "-"
                  }}
                </div>
              </q-card-section>
            </q-card>
          </q-card-section>
        </q-card>
      </div>
    </template>
    <template v-slot:pagination="scope">
      ทั้งหมด {{ props.total.toLocaleString() }} รายการ
      <q-pagination
        v-model="formFilter.page"
        active-color="primary"
        color="dark"
        :max="Number(maxPage)"
        :max-pages="5"
        size="sm"
        boundary-links
        direction-links
        @update:model-value="updatePagePagination()"
      ></q-pagination>
    </template>
    <template v-slot:no-data="{ icon, message, filter }">
      <div class="full-width row flex-center text-accent q-gutter-sm">
        <span
          ><div
            style="
              height: 50vh;
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
            "
            class="text-grey-5"
          >
            <q-icon name="search" size="4rem" />

            <span>{{ isFilter ? "ไม่พบข้อมูล" : "ค้นหาข้อมูล" }}</span>
          </div>
        </span>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="modalReport" persistent>
    <q-card class="col-12" style="width: 40%">
      <!-- <DialogHeader
        :tittle="
          empType == 'officer'
            ? 'รายงานสถิติข้อมูลข้าราชการ กทม. สามัญ'
            : 'รายงานสถิติข้อมูลลูกจ้างประจำ กทม.'
        "
        :close="closeDialog"
      /> -->
      <q-separator />
      <q-card-section class="q-pa-lg">
        <div class="column q-pa-sm q-gutter-y-sm">
          <datepicker
            menu-class-name="modalfix"
            v-model="year"
            :locale="'th'"
            autoApply
            year-picker
            :enableTimePicker="false"
          >
            <template #year="{ year }">{{ year + 543 }}</template>
            <template #year-overlay-value="{ value }">{{
              parseInt(value + 543)
            }}</template>
            <template #trigger>
              <q-input
                dense
                outlined
                :model-value="year === 0 ? 'ทั้งหมด' : Number(year) + 543"
                :label="`${'ปีงบประมาณ'}`"
                bg-color="white"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    style="color: var(--q-primary)"
                  >
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>

          <span class="text-body1 q-pt-sm text-weight-medium"
            >เลือกช่วงอายุ</span
          >
          <div class="q-px-lg q-pt-lg">
            <q-range
              v-model="rangeAge"
              :min="18"
              :max="60"
              label
              :marker-labels="objMarkerLabel"
              color="primary"
            >
            </q-range>
          </div>
        </div>
      </q-card-section>
      <q-separator />
      <!-- <q-card-actions align="right" class="q-ma-xs">
        <q-btn
          :loading="loadingBtn"
          :disable="loadingBtn"
          color="primary"
          icon="download"
          label="ดาวน์โหลดรายงาน"
          @click="getReport"
          style="width: 200px"
        >
          <q-tooltip>ดาวน์โหลดรายงาน</q-tooltip>
        </q-btn>
      </q-card-actions> -->
    </q-card>
  </q-dialog>

  <!-- ประวัติถือครองตำแหน่ง -->
  <DialogHistory v-model:modal="modalHistory" />
</template>

<style scoped>
.hover-button:hover {
  background-color: #089cfc;
  color: white !important;
}

.my-card {
  width: 100%;
  height: 100%;
}

.bg-grey-13 {
  background: #f1f2f496 !important;
}

.my-custom-toggle {
  border: 1px solid #d0d0d2;
}
.cardRO {
  border-radius: 10px;
}

.cardRO:hover {
  cursor: pointer;
  background: #dcdcdc33 !important;
}
.cardRO:hover .textName {
  color: #02a998;
}
</style>
