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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useOrganizational } from "@/modules/02_organization/store/organizational";

/** import Type*/
import type { QTableProps } from "quasar";
import type { HistoryPos } from "@/modules/02_organization/interface/response/organizational";

/** import Components*/
import Header from "@/components/DialogHeader.vue";

/** Use*/
const $q = useQuasar();
const store = useOrganizational();
const { showLoader, hideLoader, messageError, date2Thai } = useCounterMixin();

/** props*/
const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  historyType: {
    type: String,
    default: "HISTORY",
  },
  rowId: {
    type: String,
  },
});

const rows = ref<HistoryPos[]>([]); //ข้อมูลรายการประวัติตำแหน่ง
const baseColumns = 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",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "shortName",
    align: "left",
    label: "อักษรย่อ",
    sortable: true,
    field: "shortName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posMasterNoPrefix",
    align: "left",
    label: " Prefix เลขที่ตำแหน่ง",
    sortable: true,
    field: "posMasterNoPrefix",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posMasterNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posMasterNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posMasterNoSuffix",
    align: "left",
    label: "Suffix เลขที่ตำแหน่ง",
    sortable: true,
    field: "posMasterNoSuffix",
    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: "posType",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "posType",
    format(val, row) {
      let name = "";
      if (row.posType && row.position) {
        name = `${row.posType} (${row.posLevel})`;
      } else if (row.posType) {
        name = `${row.posType}`;
      } else if (row.posLevel) {
        name = `(${row.posLevel})`;
      } else name = "-";
      return name;
    },
    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",
    format(val, row) {
      return !val ? "-" : val;
    },
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    field: "lastUpdatedAt",
    sortable: false,
    format(val) {
      return date2Thai(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const pagination = ref<QTableProps["pagination"]>({
  page: 1,
  rowsPerPage: 10,
});

const columns = computed(() =>
  props.historyType === "HISTORY"
    ? (baseColumns.value || []).filter((col: any) => col.name !== "fullname")
    : baseColumns.value || []
);

const titleName = computed(() =>
  props.historyType === "HISTORY" ? "ประวัติตำแหน่ง" : "ประวัติคนครอง"
);

/**
 *  function เรียกข้อมูลประวัติตำแหน่ง
 * @param id
 */
async function fetchHistoryPos(id: string) {
  showLoader();
  const pathAPI =
    props.historyType === "HISTORY"
      ? config.API.orgPosHistory(id)
      : config.API.orgPosHistoryUpdate(id);
  await http
    .get(pathAPI)
    .then((res) => {
      const data = res.data.result;
      rows.value =
        props.historyType === "HISTORY"
          ? formatHistoryData(data)
          : formatHistoryOwnerData(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function formatHistoryData(data: HistoryPos[]) {
  return data.map((item) => ({
    ...item,
    shortName: item.orgShortName ?? "-",
  }));
}

function formatHistoryOwnerData(data: HistoryPos[]) {
  return data.map((item) => ({
    ...item,
    fullname:
      item.firstName
        ? `${item.prefix}${item.firstName} ${item.lastName}`.trim()
        : "ว่าง",
  }));
}

/** ดูการเปลี่ยนแปลง  modal เมื่อเป็น true จะเรียกเรียกข้อมูลประวัติตำแหน่ง*/
watch(
  () => modal.value,
  () => {
    modal.value && props.rowId && fetchHistoryPos(props.rowId);

    if (!modal.value) {
      rows.value = [];
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 80%">
      <Header
        :tittle="titleName"
        :close="
          () => {
            modal = false;
            rows = [];
          }
        "
      />
      <q-separator />
      <q-card-section>
        <d-table
          flat
          bordered
          :rows="rows"
          :columns="columns"
          row-key="id"
          no-data-label="ไม่มีข้อมูล"
          v-model:pagination="pagination"
        >
          <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">{{ col.label }}</span>
              </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 v-if="col.name == 'no'">
                  {{
                    store.typeOrganizational === "current"
                      ? props.rowIndex + 1
                      : props.rowIndex + 1 == 1
                      ? "1 (แบบร่าง)"
                      : props.rowIndex + 1 == 2
                      ? "2 (ปัจจุบัน)"
                      : props.rowIndex + 1
                  }}
                </div>

                <div v-else>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
