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

import { useCounterMixin } from "@/stores/mixin";

/** import type */
import type { QTableProps } from "quasar";

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

const { date2Thai, onSearchDataTable, findOrgNameHtml } = useCounterMixin();

/** define model */
const modal = defineModel<boolean>("modal", { required: true }); // modal visibility
const isLoading = defineModel<boolean>("isLoading", { required: true }); // loading state
const title = defineModel<string>("title", { required: true }); // dialog title
const rows = defineModel<any[]>("rows"); // data rows for the table
const rowsData = defineModel<any[]>("rowsData"); // raw data for the table
const columns = defineModel<QTableProps["columns"]>("columns"); // table columns definition
const visibleColumns = defineModel<string[]>("visibleColumns"); // visible columns in the table

/** define props */
const props = defineProps({
  getData: Function, // function to fetch data
  type: String, // type of data (e.g., "Leave", "insignia")
});

const type = ref<string>(""); // ประเภทของข้อมูล
const filter = ref<string>(""); // filter input for searching
const pagination = ref({
  sortBy: "lastUpdatedAt",
});

/** ปิด Dialog และรีเซ็ตค่า */
function close() {
  modal.value = false;
  filter.value = "";
}

/**
 * ฟังก์ชันแปลงวันที่เป็นรูปแบบไทย
 * @param val - date range value
 */
function dateThaiRange(val: [Date, Date]) {
  if (val === null) {
  } else if (date2Thai(val[0]) === date2Thai(val[1])) {
    return `${date2Thai(val[0])}`;
  } else {
    return `${date2Thai(val[0])} - ${date2Thai(val[1])} `;
  }
}

/**
 * ฟังก์ชันแปลงสถานะการลาเป็นข้อความที่
 * @param val  สถานะการลา
 */
function statusLeave(val: string) {
  switch (val) {
    case "waitting":
      return "รออนุมัติ";
    case "reject":
      return "ไม่ผ่านการอนุมัติ";
    case "approve":
      return "ผ่านการอนุมัติ";
    case "cancel":
      return "ยกเลิก";
    default:
      return "-";
  }
}

/** ฟังก์ชันค้นหาข้อมูลในตาราง */
function onSearch() {
  rows.value = onSearchDataTable(
    filter.value,
    rowsData.value ? rowsData.value : [],
    columns.value ? columns.value : []
  );
}

watch(
  () => modal.value,
  (n) => {
    if (n) {
      if (props.type) {
        type.value = props.type;
      }
      props.getData?.();
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 80%">
      <DialogHeader :tittle="title" :close="close" />
      <q-separator />
      <q-card-section style="max-height: 80vh" class="scroll">
        <div class="row justify-end q-col-gutter-sm q-mb-sm">
          <div class="col-12 col-sm-3">
            <q-input
              class="inputgreen"
              outlined
              dense
              v-model="filter"
              label="ค้นหา"
              @keydown.enter.prevent="onSearch"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
          </div>
          <div class="col-12 col-sm-2">
            <q-select
              dense
              multiple
              outlined
              emit-value
              map-options
              options-dense
              option-value="name"
              v-model="visibleColumns"
              :options="columns"
              :display-value="$q.lang.table.columns"
              style="min-width: 140px"
            />
          </div>
        </div>

        <div class="col-12">
          <d-table
            flat
            dense
            bordered
            virtual-scroll
            :rows="rows"
            :columns="columns"
            :rows-per-page-options="[10, 25, 50, 100]"
            :visible-columns="visibleColumns"
            :virtual-scroll-sticky-size-start="48"
            :pagination="pagination"
            :loading="isLoading"
            row-key="id"
          >
            <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, index) in props.cols" :key="col.name">
                  <div v-if="col.name == 'no'">
                    {{ props.rowIndex + 1 }}
                  </div>
                  <div v-else-if="col.name == 'insignia' && type == 'insignia'">
                    {{ props.row.insignia ? `${props.row.insignia.name} ` : "-"
                    }}{{
                      props.row.insignia.shortName
                        ? `(${props.row.insignia.shortName})`
                        : ""
                    }}
                  </div>

                  <div v-else-if="col.name == 'dateLeave' && type == 'Leave'">
                    {{
                      dateThaiRange([
                        props.row.dateStartLeave,
                        props.row.dateEndLeave,
                      ])
                    }}
                  </div>
                  <div v-else-if="col.name == 'status' && type == 'Leave'">
                    {{ props.row.status ? statusLeave(props.row.status) : "-" }}
                  </div>
                  <div v-else-if="col.name == 'organization'">
                    {{
                      props.row
                        ? findOrgNameHtml({
                            root: props.row.orgRoot,
                            child1: props.row.orgChild1,
                            child2: props.row.orgChild2,
                            child3: props.row.orgChild3,
                            child4: props.row.orgChild4,
                          })
                        : "-"
                    }}
                  </div>
                  <div v-else>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
            <template v-slot:item="props">
              <div
                class="q-pa-xs col-xs-12 col-sm-6 col-md-4 col-lg-3 grid-style-transition"
              >
                <q-card bordered flat class="q-pt-md">
                  <q-list dense>
                    <q-item v-for="col in props.cols" :key="col.name">
                      <q-item-section class="fix_top">
                        <q-item-label class="text-grey-6 text-weight-medium">{{
                          col.label
                        }}</q-item-label>
                      </q-item-section>
                      <q-item-section
                        v-if="col.name == 'insignia' && type == 'insignia'"
                        class="fix_top"
                      >
                        <q-item-label class="text-dark text-weight-medium">
                          {{
                            props.row.insignia
                              ? `${props.row.insignia.name} `
                              : "-"
                          }}{{
                            props.row.insignia.shortName
                              ? `(${props.row.insignia.shortName})`
                              : ""
                          }}</q-item-label
                        >
                      </q-item-section>
                      <q-item-section
                        v-else-if="col.name == 'dateLeave' && type == 'Leave'"
                        class="fix_top"
                      >
                        <q-item-label class="text-dark text-weight-medium">
                          {{
                            dateThaiRange([
                              props.row.dateStartLeave,
                              props.row.dateEndLeave,
                            ])
                          }}</q-item-label
                        >
                      </q-item-section>
                      <q-item-section
                        v-else-if="col.name == 'status' && type == 'Leave'"
                        class="fix_top"
                      >
                        <q-item-label class="text-dark text-weight-medium">
                          {{
                            props.row.status
                              ? statusLeave(props.row.status)
                              : "-"
                          }}</q-item-label
                        >
                      </q-item-section>
                      <q-item-section v-else class="fix_top">
                        <q-item-label class="text-dark text-weight-medium">{{
                          col.value ? col.value : "-"
                        }}</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-card>
              </div>
            </template>
          </d-table>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>
<style scoped>
.fix_top {
  justify-content: start !important;
}
</style>
