<script setup lang="ts">
import { ref, onMounted } from "vue";
import type { QTableProps } from "quasar";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";

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

import type { DataOption } from "@/modules/06_retirement/interface/index/Main";
import type { ResponseDececased } from "@/modules/06_retirement/interface/response/Deceased";

/** Use */
const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,
  date2Thai,
  findOrgName,
  onSearchDataTable,
  findOrgNameHtml,
} = mixin;

/** คอลัมน์ */
const rows = ref<ResponseDececased[]>([]);
const rowsData = ref<ResponseDececased[]>([]);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});
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: true,
    field: "fullname",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.firstName
        ? ` ${row.prefix ?? ""}${row.firstName} ${row.lastName}`
        : "-";
    },
  },

  {
    name: "profileType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "profileType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return `${
        row.profileType === "OFFICER"
          ? "ข้าราชการ กทม. สามัญ"
          : row.profileType === "EMPLOYEE"
          ? "ลูกจ้างประจำ กทม."
          : "-"
      }  `;
    },
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionType",
    align: "left",
    label: "ตำแหน่งประเภท/กลุ่มงาน",
    sortable: true,
    field: "positionType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      let name = "";
      if (row.posTypeName && row.posLevelName) {
        name = `${row.posTypeName} (${row.posLevelName})`;
      } else if (row.posTypeName) {
        name = `${row.posTypeName}`;
      } else if (row.posLevelName) {
        name = `(${row.posLevelName})`;
      } else name = "-";
      return name;
    },
  },
  {
    name: "org",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "org",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return findOrgName(row);
    },
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่ดำเนินการ",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => date2Thai(val),
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "fullname",
  "positionType",
  "position",
  "positionLevel",
  "positionExecutive",
  "org",
  "createdAt",
  "profileType",
]);

const employeeClass = ref<string>("");
const employeeClassOp = ref<DataOption[]>([
  { id: "", name: "ทั้งหมด" },
  { id: "OFFICER", name: "ขรก.กทม. สามัญ" },
  { id: "EMPLOYEE", name: "ลูกจ้างประจำ กทม." },
]);

/**เรียกข้อมูลจาก APi */
async function fectListDecased() {
  showLoader();
  await http
    .get(config.API.listDeceased())
    .then((res) => {
      const data = res.data.result;

      rows.value = data;
      rowsData.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

//ค้นหา คอลัมน์ คอลัมน์ที่แสดง
const filterKeyword = ref<string>("");

/** Setting Pagination */
function nextPage(id: string) {
  router.push("/retirement/deceased/" + id);
}

function onSearch() {
  rows.value = onSearchDataTable(
    filterKeyword.value,
    rowsData.value,
    columns.value ? columns.value : []
  );

  if (employeeClass.value) {
    rows.value = rows.value.filter(
      (e: ResponseDececased) => e.profileType === employeeClass.value
    );
  }
}

/**Hook */
onMounted(() => {
  fectListDecased();
});
</script>
<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการบันทึกเวียนแจ้งการถึงแก่กรรม
  </div>
  <q-card flat bordered class="col-12 q-mt-sm">
    <q-separator />
    <div class="col-12 row q-pa-md">
      <div class="row col-12 q-col-gutter-sm">
        <div class="row col-12">
          <div>
            <q-select
              outlined
              dense
              v-model="employeeClass"
              :options="employeeClassOp"
              emit-value
              map-options
              option-value="id"
              option-label="name"
              label="ประเภทตำแหน่ง"
              :clearable="employeeClass !== ''"
              style="width: 200px"
              @clear="employeeClass = ''"
              @update:model-value="onSearch"
            >
            </q-select>
          </div>
          <q-space />
          <div class="row q-col-gutter-sm">
            <q-input
              standout
              dense
              v-model="filterKeyword"
              ref="filterRef"
              outlined
              placeholder="ค้นหา"
              @keydown.enter.prevent="onSearch"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>

            <q-select
              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"
            />
          </div>
        </div>
        <div class="col-12">
          <d-table
            ref="table"
            :columns="columns"
            :rows="rows"
            row-key="fullname"
            flat
            bordered
            :paging="true"
            dense
            :visible-columns="visibleColumns"
            v-model:pagination="pagination"
          >
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th auto-width></q-th>
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  <span class="text-weight-medium">{{ col.label }}</span>
                </q-th>
              </q-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td auto-width>
                  <q-btn
                    v-if="checkPermission($route)?.attrIsGet"
                    flat
                    dense
                    round
                    color="info"
                    icon="mdi-eye"
                    @click.stop.prevent="nextPage(props.row.id)"
                  >
                    <q-tooltip>รายละเอียด</q-tooltip>
                  </q-btn>
                </q-td>
                <q-td v-for="col in props.cols" :key="col.id">
                  <div v-if="col.name === 'no'">
                    {{ props.rowIndex + 1 }}
                  </div>

                  <div v-else-if="col.name == 'org'" class="text-html">
                    {{ props.row ? findOrgNameHtml(props.row) : "-" }}
                  </div>
                  <div v-else>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </div>
    </div>
  </q-card>
</template>
<style scoped lang="scss"></style>
