<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,
  onSearchDataTable,
} = mixin;

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

const isLoading = ref<boolean>(false);
const filter = ref<string>("");
const rows = ref<PortfolioRowsType[]>([]);
const rowsData = 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() {
  isLoading.value = true;
  await http
    .get(config.API.portfolio)
    .then((res) => {
      rows.value = res.data.result;
      rowsData.value = res.data.result;
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(() => {
      isLoading.value = false;
    });
}

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

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

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

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

/** Hook Lifecycle */
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
                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 class="col-12">
            <d-table
              flat
              bordered
              dense
              :paging="true"
              row-key="id"
              :rows="rows"
              :columns="columns"
              :visible-columns="visibleColumns"
              :rows-per-page-options="[10, 25, 50, 100]"
              :pagination="pagination"
              :loading="isLoading"
            >
              <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>
