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

import http from "@/plugins/http";
import config from "@/app.config";
import { useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";

import type { PortfolioRowsType } from "@/modules/13_portfolio/interface/Main";
const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader, dialogRemove, success } = mixin;

const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
/**
 * เพิ่มหัวข้อตาราง
 */
const filter = ref<string>("");
const rows = ref<PortfolioRowsType[]>([]);
const visibleColumns = ref<String[]>(["no", "name", "detail"]);
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: "name",
    align: "left",
    label: "ชื่อเอกสาร/ผลงาน",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:5px;",
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียดเอกสาร/ผลงาน",
    sortable: true,
    field: "detail",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:5px;",
  },
]);

//นำข้อมูลมาแสดง
async function fecthList() {
  showLoader();
  await http
    .get(config.API.portfolio+`?keyword=${filter.value}`)
    .then((res) => {
      rows.value = res.data.result;
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

/**
 * ฟังก์ชั่นกดย้อนกลับ
 */
function clickBack() {
  router.push(`/`);
}

/**
 * ฟั่งชั้น ลบ ข้อมูล
 * @param id id row
 */
function onDelete(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.portfolioId(id))
      .then((res) => {
        success($q, "ลบข้อมูลสำเร็จ");
        fecthList();
      })
      .catch((err) => {
        messageError($q, err);
        hideLoader();
      });
  });
}

/**
 * เรียกฟังก์ชันทั้งหมดตอนเรียกใช้ไฟล์นี้
 */
onMounted(async () => {
  await fecthList();
});
</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
                size="14px"
                flat
                dense
                color="blue"
                @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="fecthList()"
              >
                <template v-slot:append>
                  <q-icon v-if="filter == ''" name="search" />
                  <q-icon
                    v-if="filter !== ''"
                    name="clear"
                    class="cursor-pointer"
                    @click="filter = '',fecthList()"
                  />
                </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: 150px"
                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-th auto-width />
                </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(`/portfolio/` + props.row.id)"
                  >
                    <div v-if="col.name == 'no'">
                      {{ props.rowIndex + 1 }}
                    </div>
                    <div v-else class="table_ellipsis2">
                      {{ col.value }}
                    </div>
                  </q-td>
                  <q-td>
                    <q-btn
                      dense
                      flat
                      round
                      color="red"
                      icon="delete"
                      @click.pervent="onDelete(props.row.id)"
                    />
                  </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>
                    <q-list @click="router.push(`/portfolio/` + props.row.id)">
                      <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-separator />

                    <q-card-actions vertical align="center">
                      <q-btn
                        dense
                        flat
                        round
                        color="red"
                        icon="delete"
                        @click.pervent="onDelete(props.row.id)"
                      />
                    </q-card-actions>
                  </q-card>
                </div>
              </template>
            </d-table>
          </div>
        </q-card>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss"></style>
