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

import { useRouter } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useTransferDataStore } from "@/modules/05_placement/store";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";
import type { ResponseData } from "@/modules/05_placement/interface/response/Transfer";

import DialogOrders from "@/modules/05_placement/components/Transfer/DialogOrders.vue"; //ส่งไปออกคำสั่งขอโอน

const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const { statusText } = useTransferDataStore();
const { date2Thai, messageError, showLoader, hideLoader } = mixin;

const modal = ref<boolean>(false); //ส่งไปออกคำสั่ง
const dataTransfer = ref<ResponseData[]>([]); //ช่อมูลรายการขอโอน

//Table
const rows = ref<ResponseData[]>([]); //รายการขอโอน
const filterMain = ref<string>(""); //คำค้นหารายการขอโอน
const rowsOrder = ref<ResponseData[]>([]); //รายการส่งไปออกคำสั่ง
const filterOrder = ref<string>(""); //คำค้นหารายการส่งไปออกคำสั่ง
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.prefix ?? ""}${row.firstName ?? ""} ${row.lastName ?? ""}`;
    },
  },
  {
    name: "posType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "posType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.positionTypeOld
        ? `${row.positionTypeOld}${
            row.positionLevelOld ? `(${row.positionLevelOld})` : ""
          }`
        : "";
    },
  },
  {
    name: "organizationPositionOld",
    align: "left",
    label: "ตำแหน่ง/สังกัดเดิม",
    sortable: true,
    field: "organizationPositionOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "หน่วยงานที่ขอโอนไป",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่ดำเนินการ",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val) {
      return date2Thai(val);
    },
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => statusText(val),
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "fullname",
  "posType",
  "organizationPositionOld",
  "organization",
  "status",
  "createdAt",
]);

/**
 * ฟังก์ชันดึงข้อมูรายการขอโอน
 */
async function fetchData() {
  showLoader();
  await http
    .get(config.API.transfer)
    .then(async (res) => {
      const data = await res.data.result;
      rows.value = data;
      dataTransfer.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันส่งไปออกคำสั่ง
 *
 * ค้นหารายชื่อออกคำสั่งตามสถานะ อนุมัติ (APPROVE)
 */
function openModalOrder() {
  const row = dataTransfer.value.filter(
    (r: ResponseData) =>
      r.status == "APPROVE" &&
      r.organizationPositionOld &&
      r.positionTypeOld &&
      r.positionLevelOld &&
      r.positionNumberOld &&
      r.organization &&
      r.date
  );
  rowsOrder.value = row;
  modal.value = true;
}

/**
 * ฟังก์ชันปิด popup ส่งไปออกคำสั่ง
 *
 */
function closeModal() {
  modal.value = false;
  filterOrder.value = "";
}

/**
 * ฟังก์ชันคืนค่าตัวแปรค้นหา
 *
 * กำหนด filterMain และ filterOrder เป็นค่าว่าง
 */
function resetFilter() {
  filterMain.value = "";
  filterOrder.value = "";
}

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 *
 * จะเรียกใช้ fetchData เพื่อดึงข้อมูลรายการขอโอน
 */
onMounted(async () => {
  await fetchData();
});

const filter = ref("");

const filterAndApply = () => {
  const searchText = filter.value.trim().toLowerCase();

  if (!searchText) {
    rows.value = dataTransfer.value; // คืนค่าทั้งหมดถ้าไม่มีข้อความค้นหา
    return;
  }

  rows.value = dataTransfer.value.filter((row: any) => {
    return columns.value?.some((col: any) => {
      const rawValue = row[col.field];
      const formattedValue = col.format
        ? col.format(rawValue, row) // ใช้ `format` ถ้ามี
        : rawValue;

      return String(formattedValue).toLowerCase().includes(searchText);
    });
  });
};
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">รายการขอโอน</div>
  <q-card flat bordered class="col-12 q-mt-sm">
    <div class="row q-pa-md">
      <div class="col-12">
        <div class="row col-12">
          <q-btn
            v-if="checkPermission($route)?.attrIsUpdate"
            @click="openModalOrder"
            flat
            round
            color="add"
            icon="mdi-account-arrow-right"
          >
            <q-tooltip>ส่งไปออกคำสั่ง</q-tooltip>
          </q-btn>

          <q-space />
          <q-input
            class="col-xs-12 col-sm-3 col-md-2"
            standout
            dense
            v-model="filter"
            ref="filterRef"
            outlined
            debounce="300"
            placeholder="ค้นหา"
            @keyup.enter="filterAndApply"
          >
            <template v-slot:append>
              <q-icon name="search" />
              <!-- <q-icon
                v-if="filterMain !== ''"
                name="clear"
                class="cursor-pointer"
                @click="resetFilter"
              /> -->
            </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"
            class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
          />
        </div>

        <div class="col-12 q-pt-sm">
          <!-- :filter="filterMain" -->
          <d-table
            :columns="columns"
            :rows="rows"
            row-key="id"
            :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
                    v-if="checkPermission($route)?.attrIsGet"
                    flat
                    dense
                    round
                    color="info"
                    icon="mdi-eye"
                    @click.stop.prevent="
                      router.push(`/placement/transfer/${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
                    :class="
                      col.name === 'organizationPositionOld' ||
                      col.name === 'organization'
                        ? 'table_ellipsis2'
                        : ''
                    "
                  >
                    {{
                      col.value == null ? "" : col.value == "" ? "-" : col.value
                    }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </div>
    </div>
  </q-card>

  <DialogOrders
    v-model:modal="modal"
    v-model:filter-order="filterOrder"
    :fetch-data="fetchData"
    :close-modal="closeModal"
    :rows="rowsOrder"
  />
</template>
<style scoped lang="scss"></style>
