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

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

import type { QTableProps } from "quasar";
import type { ResRecord } from "@/modules/15_development/interface/response/Main";

const $q = useQuasar();
const {
  date2Thai,
  onSearchDataTable,
  showLoader,
  hideLoader,
  success,
  messageError,
  dialogRemove,
} = useCounterMixin();

//prosp
const isProfile = defineModel<boolean>("isProfile", { required: true });
const listPerson = defineModel<ResRecord[]>("listPerson", { required: true });

//ข้อมุล Table
const keyword = ref<string>("");
const rows = ref<ResRecord[]>([]);
const rowsMain = ref<ResRecord[]>([]);

// baseColumns
const baseColumns = ref<QTableProps["columns"]>([
  {
    name: "isDone",
    align: "left",
    label: "ลงทะเบียนประวัติ",
    sortable: true,
    field: "isDone",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
  },
  {
    name: "isDoneIDP",
    align: "left",
    label: "IDP ลงทะเบียนประวัติ",
    sortable: true,
    field: "isDoneIDP",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
  },
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
  },
  {
    name: "type",
    align: "left",
    label: "ประเภท",
    sortable: true,
    field: "type",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
    format: (v) => formBmaofficer(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "idcard",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "idcard",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    format(val, row) {
      return row.firstName
        ? `${row.prefix}${row.firstName} ${row.lastName}`
        : "-";
    },
    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: "posTypeName",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "posTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posLevelName",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: true,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posExecutive",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "posExecutive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "org",
    align: "left",
    label: "หน่วยงานที่สังกัด",
    sortable: true,
    field: "org",
    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: "dateEnd",
    align: "left",
    label: "วันที่สิ้นสุด",
    sortable: true,
    field: "dateEnd",
    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: "trainingDays",
    align: "left",
    label: "จำนวนวันที่อบรม",
    sortable: true,
    field: "trainingDays",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandNumber",
    align: "left",
    label: "เลขที่คำสั่ง/เลขที่หนังสืออนุมัติ",
    sortable: true,
    field: "commandNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandDate",
    align: "left",
    label: "คำสั่งลงวันที่/หนังสืออนุมัติลงวันที่",
    sortable: true,
    field: "commandDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const columns = computed(() => {
  if (!isProfile.value) {
    if (baseColumns.value) {
      return baseColumns.value.filter(
        (column) => column.name !== "isDone" && column.name !== "isDoneIDP"
      );
    }
  }
  return baseColumns.value;
});

const visibleColumns = ref<string[]>([
  "isDone",
  "isDoneIDP",
  "no",
  "type",
  "idcard",
  "fullName",
  "position",
  "posTypeName",
  "posLevelName",
  "posExecutive",
  "dateStart",
  "dateEnd",
  "trainingDays",
  "org",
  "commandNumber",
  "commandDate",
]);

/**
 * convert status to text
 * @param  val ประเภท
 */
function formBmaofficer(val: string) {
  switch (val) {
    case "OFFICER":
      return "ขรก.กทม. สามัญ";
    case "EMPLOYEE":
      return "ลูกจ้างประจำ";
    default:
      return "อิ่นๆ";
  }
}

/** function เรียกข้อมูลโครงการ*/
function fetchDataProject() {
  const data = listPerson.value.filter(
    (e: ResRecord) => e.isProfile === isProfile.value
  );
  rowsMain.value = data;
  serchDataTable();
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    keyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

function handleDelete(id: string) {
  dialogRemove($q, async () => {
    try {
      showLoader();
      await http.delete(config.API.developmentMain + `/delete/${id}`);
      success($q, "ลบข้อมูลสำเร็จ");
      rowsMain.value = rowsMain.value.filter((e: ResRecord) => e.id !== id);
      listPerson.value = listPerson.value.filter((e: ResRecord) => e.id !== id);
      serchDataTable();
    } catch (error) {
      messageError($q, error);
    } finally {
      hideLoader();
    }
  });
}

/** ดึงข้อมูลเมื่อคอมโพเนนต์โหลดเสร็จสมบูรณ์  */
onMounted(() => {
  fetchDataProject();
});
</script>

<template>
  <q-toolbar style="padding: 0px" class="q-mb-xs">
    <q-space />
    <q-input
      dense
      outlined
      v-model="keyword"
      label="ค้นหา"
      class="q-mr-sm"
      @keydown.enter.prevent="serchDataTable"
    >
      <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"
    />
  </q-toolbar>

  <div class="col-12">
    <d-table
      ref="table"
      row-key="id"
      flat
      bordered
      dense
      :columns="columns"
      :rows="rows"
      :paging="true"
      :rows-per-page-options="[20, 50, 100]"
      :visible-columns="visibleColumns"
    >
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th auto-width />
          <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
              flat
              round
              color="red"
              @click="handleDelete(props.row.id)"
              icon="mdi-delete"
            >
              <q-tooltip>ลบข้อมูล</q-tooltip>
            </q-btn>
          </q-td>

          <q-td v-for="col in props.cols" :key="col.id">
            <div v-if="col.name === 'isDone'" class="text-center">
              <q-icon
                v-if="props.row.isDone"
                name="mdi-check"
                color="green"
                size="xs"
              >
                <q-tooltip>ส่งไปบันทึกที่ทะเบียนประวัติแล้ว</q-tooltip>
              </q-icon>
            </div>

            <div v-else-if="col.name === 'isDoneIDP'" class="text-center">
              <q-icon
                v-if="props.row.isDoneIDP"
                name="mdi-check"
                color="blue"
                size="xs"
              >
                <q-tooltip>ส่งไปบันทึก IDP ที่ทะเบียนประวัติแล้ว</q-tooltip>
              </q-icon>
            </div>

            <div
              v-else-if="col.name === 'org'"
              class="text-html"
              style="min-width: 200px"
            >
              {{ col.value ? col.value : "-" }}
            </div>
            <div v-else>
              {{ col.value ? col.value : "-" }}
            </div>
          </q-td>
        </q-tr>
      </template>
    </d-table>
  </div>
</template>

<style scoped></style>
