<script setup lang="ts">
import { ref, onMounted } from "vue";
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 { useTransferDataStore } from "@/modules/02_transfer/store";

import type { QTableProps } from "quasar";
import type {
  TransferList,
  TransferMain,
} from "@/modules/02_transfer/interface/Main";

const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const transferData = useTransferDataStore();

const { statusText } = transferData;
const { date2Thai, messageError, showLoader, hideLoader, onSearchDataTable } =
  mixin;

const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

const rows = ref<TransferMain[]>([]);
const rowsData = ref<TransferMain[]>([]);
const filter = ref<string>("");
const visibleColumns = ref<String[]>([
  "no",
  "date",
  "position",
  "noPos",
  "level",
  "salary",
  "transfer",
  "statustext",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:5px;",
  },
  {
    name: "date",
    align: "left",
    label: "วันที่",
    sortable: true,
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
  {
    name: "noPos",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: true,
    field: "noPos",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "level",
    align: "left",
    label: "อันดับ/ระดับ",
    sortable: true,
    field: "level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "salary",
    align: "left",
    label: "เงินเดือน",
    sortable: true,
    field: "salary",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "transfer",
    align: "left",
    label: "หน่วยงานที่ขอโอนไป",
    sortable: true,
    field: "transfer",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "statustext",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "statustext",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:10%;",
  },
]);

//นำข้อมูลมาแสดง
async function fecthListTransfer() {
  showLoader();
  await http
    .get(config.API.listUserTransfer())
    .then((res) => {
      let data = res.data.result;
      const listData = data.map((e: TransferList) => ({
        id: e.id,
        date: date2Thai(e.createdAt),
        status: e.status,
        statustext: statusText(e.status),
        position: e.organizationPositionOld,
        noPos: e.positionNumberOld,
        rootShortNameOld: e.rootShortNameOld,
        level: e.positionLevelOld,
        salary: e.salary,
        transfer: e.organization,
      }));
      rows.value = listData;
      rowsData.value = listData;
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชั่นกดเพิ่มไปหน้าเพิ่มขอโอน
 */
async function clickAdd() {
  router.push(`/transfer/add`);
}

/**
 * กดเพื่อย้อนกลับ
 */
function clickBack() {
  router.push(`/`);
}

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

/**
 * เรียกฟังก์ชันทั้งหมดตอนเรียกใช้ไฟล์นี้
 */
onMounted(async () => {
  await fecthListTransfer();
});
</script>
<template>
  <div class="col-12 row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-11">
      <div class="toptitle text-white col-12 row items-center">
        <q-btn
          icon="mdi-arrow-left"
          unelevated
          round
          dense
          flat
          color="primary"
          class="q-mr-sm"
          @click="clickBack"
        />
        เรื่องขอโอน
      </div>
      <div class="col-12">
        <q-card bordered class="q-pa-md">
          <div class="q-pb-sm row">
            <div>
              <q-btn
                flat
                dense
                color="primary"
                @click="clickAdd"
                icon="mdi-plus"
              >
                <q-tooltip>เพิ่มข้อมูล</q-tooltip>
              </q-btn>
            </div>
            <q-space />
            <div class="items-center q-gutter-sm" style="display: flex">
              <!-- ค้นหาข้อความใน table -->
              <q-input
                standout
                dense
                v-model="filter"
                ref="filterRef"
                outlined
                debounce="300"
                placeholder="ค้นหา"
                style="max-width: 200px"
                @keydown.enter.prevent="onSearch"
              >
                <template v-slot:append>
                  <q-icon name="search" />
                </template>
              </q-input>
              <!-- แสดงคอลัมน์ใน table -->
              <q-select
                v-model="visibleColumns"
                :display-value="$q.lang.table.columns"
                multiple
                outlined
                dense
                :options="columns"
                options-dense
                option-value="name"
                map-options
                emit-value
                style="min-width: 140px"
                class="gt-xs"
              >
                <template> </template>
              </q-select>
            </div>
          </div>
          <div>
            <d-table
              flat
              bordered
              dense
              :paging="true"
              row-key="id"
              class="custom-table2"
              style="max-height: 80vh"
              :rows="rows"
              :columns="columns"
              :visible-columns="visibleColumns"
              :rows-per-page-options="[10, 25, 50, 100]"
              v-model:pagination="pagination"
            >
              <template v-slot:pagination="scope">
                ทั้งหมด {{ rows.length }} รายการ
                <q-pagination
                  v-model="pagination.page"
                  active-color="primary"
                  color="dark"
                  :max="scope.pagesNumber"
                  :max-pages="5"
                  size="sm"
                  boundary-links
                  direction-links
                ></q-pagination>
              </template>
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                    style="color: #000000; font-weight: 500"
                  >
                    <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.name"
                    :props="props"
                    @click="router.push(`/transfer/` + props.row.id)"
                  >
                    <div v-if="col.name == 'no'">
                      {{ props.rowIndex + 1 }}
                    </div>

                    <div v-else-if="col.name == 'salary'">
                      {{
                        props.row.salary
                          ? props.row.salary.toLocaleString()
                          : "-"
                      }}
                    </div>

                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
              <template #item="props">
                <div class="q-pa-xs col-xs-12 col-sm-6 col-md-4 col-lg-3">
                  <q-card
                    bordered
                    flat
                    @click="router.push(`/transfer/` + props.row.id)"
                  >
                    <q-list>
                      <q-item
                        v-for="col in props.cols.filter((col:any) => col.name !== 'desc')"
                        :key="col.name"
                      >
                        <q-item-section>
                          <q-item-label caption>{{ col.label }}</q-item-label>

                          <q-item-label v-if="col.name === 'no'">
                            {{ props.rowIndex + 1 }}
                          </q-item-label>

                          <q-item-label v-else>{{
                            col.value ?? "-"
                          }}</q-item-label>
                        </q-item-section>
                      </q-item>
                    </q-list>
                  </q-card>
                </div>
              </template>
            </d-table>
          </div>
        </q-card>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss"></style>
