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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useKpiDataStore } from "@/modules/14_KPI/store";

import DialogHeader from "@/components/DialogHeader.vue";

const store = useKpiDataStore();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,
  findPosMasterNoOld,
  findOrgNameOld,
  date2Thai,
  onSearchDataTable,
} = mixin;

const modal = defineModel<boolean>("modal", { required: true });
const filterKeyword = ref<string>("");
const rows = ref<any[]>([]);
const rowsMain = ref<any[]>([]);

//หัวตาราง
const columns = ref<QTableProps["columns"]>([
  {
    name: "commandName",
    align: "left",
    label: "ประเภทคำสั่ง",
    sortable: true,
    field: "commandName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },

  {
    name: "agency",
    align: "left",
    label: "หน่วยงานที่ให้ช่วยราชการ/ส่งตัวกลับ",
    sortable: true,
    field: "agency",
    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: "commandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "commandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "document",
    align: "left",
    label: "เอกสารอ้างอิง",
    sortable: true,
    field: "document",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    format: (v) => date2Thai(v, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const visibleColumns = ref<string[]>([
  "commandName",
  "agency",
  "dateStart",
  "dateEnd",
  "commandNo",
  "document",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

/** แปลง สถานะเป็น text */
function statusText(val: string) {
  switch (val) {
    case "WAITTING":
      return "รอดำเนินการ";
    case "PENDING":
      return "เลือกตำแหน่งแล้ว";
    case "APPROVE":
      return "อนุมัติ";
    case "REJECT":
      return "ไม่อนุมัติ";
    case "REPORT":
      return "ส่งรายชื่อไปออกคำสั่ง";
    case "WAITING":
      return "รอออกคำสั่ง";
    case "DONE":
      return "ออกคำสั่งเสร็จสิ้น";

    default:
      return "-";
  }
}

/** ปิด popup  */
function close() {
  modal.value = false;
}

/** ดึงข้อมูล */
function getData() {
  showLoader();
  http
    // .get(config.API.placementKeycloak + `/${store.dataProfile.profileId}`)
    .get(config.API.orgAssistance(store.dataEvaluation.profileId))
    .then((res) => {
      const data = res.data.result;
      rows.value = data;
      rowsMain.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

watch(
  () => modal.value,
  (n) => {
    if (n == true) {
      getData();
    } else {
      rows.value = [];
      rowsMain.value = [];
      filterKeyword.value = "";
    }
  }
);
</script>
<template>
  <q-dialog persistent v-model="modal">
    <q-card bordered style="min-width: 80vw">
      <DialogHeader tittle="ข้อมูลการช่วยราชการ" :close="close" />
      <q-separator />
      <q-card-section>
        <div class="row q-col-gutter-sm">
          <div class="col-12 row">
            <q-space />
            <div class="row q-col-gutter-sm">
              <q-input
                dense
                outlined
                v-model="filterKeyword"
                label="ค้นหา"
                @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"
              />
            </div>
          </div>

          <div class="col-12">
            <d-table
              ref="table"
              :columns="columns"
              :rows="rows"
              row-key="id"
              flat
              bordered
              :paging="true"
              dense
              :rows-per-page-options="[10, 25, 50, 100]"
              :visible-columns="visibleColumns"
            >
              <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" class="cursor-pointer">
                  <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 == 'organizationPositionOld'"
                      class="text-html"
                    >
                      {{
                        props.row.organizationPositionOld
                          ? props.row.organizationPositionOld
                          : "-"
                      }}
                    </div>
                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
            </d-table>
          </div>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>
