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

import config from "@/app.config";
import http from "@/plugins/http";
import { useEvaluateStore } from "@/modules/06_evaluate/store";
import { useCounterMixin } from "@/stores/mixin";

/** use*/
const $q = useQuasar();
const store = useEvaluateStore();
const mixin = useCounterMixin();
const router = useRouter();

const total = defineModel<number>("total", { required: true });
const totalList = defineModel<number>("totalList", { required: true });
const pagination = defineModel<any>("pagination", { required: true });
const { dialogRemove, showLoader, hideLoader, success, messageError } = mixin;

const props = defineProps({
  page: {
    type: Number,
    require: true,
  },
  pageSize: {
    type: Number,
    require: true,
  },
  maxPage: {
    type: Number,
    require: true,
  },
  fetchData: {
    type: Function,
    require: true,
  },
});

const emit = defineEmits(["update:pagination"]);

/** ค้นหาคอลัม */
const visibleColumns = ref<string[]>(["no", "type_th", "dateSend", "status"]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; ",
  },
  {
    name: "type_th",
    align: "left",
    label: "ระดับที่ยื่นขอ",
    sortable: true,
    field: "type_th",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; ",
  },
  {
    name: "dateSend",
    align: "left",
    label: "วันที่ยื่นขอ",
    sortable: true,
    field: "dateSend",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px;",
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/**
 * function ส่งข้อมูลไป Update Paging
 * @param newPagination ข้อมูล Paging ใหม่
 * @param page หน้า
 */
function updateProp(newPagination: any, page: number) {
  emit("update:pagination", newPagination, page);
}

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

/**
 * function ลบรายการประเมิน
 * @param id รายการประเมิน
 */
async function onCkilckDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.evaluationByid(id))
      .then(async () => {
        await props.fetchData?.();
        await success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
        hideLoader();
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * function redireact ไปยังหน้ารายละเอียด
 * @param data ข้อมูล row
 */
function redirectToDetail(data: any) {
  router.push(`/evaluate/detail/${data.typeparam.toLowerCase()}/${data.id}`);
}

/** Hook lifecycle*/
onMounted(() => {
  store.columns = columns.value;
  store.visibleColumns = visibleColumns.value;
});
</script>

<template>
  <d-table
    ref="table"
    flat
    bordered
    class="custom-header-table"
    :columns="columns"
    :rows="store.row"
    dense
    :visible-columns="store.visibleColumns"
    :rows-per-page-options="[10, 25, 50, 100]"
    @update:pagination="updatePagination"
  >
    <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" v-html="col.label" />
        </q-th>
        <q-th></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="redirectToDetail(props.row)"
        >
          <div v-if="col.name == 'no'">
            {{ props.rowIndex + 1 }}
          </div>
          <div>
            {{ col.value }}
          </div>
        </q-td>
        <q-td>
          <q-btn
            v-if="
              props.row.step === 'CHECK_SPEC' ||
              props.row.step === 'PREPARE_DOC_V1' ||
              props.row.step === 'CHECK_DOC_V1'
            "
            flat
            dense
            round
            color="red"
            icon="delete"
            @click.stop="onCkilckDelete(props.row.id)"
          >
            <q-tooltip>ลบ</q-tooltip>
          </q-btn>
        </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="redirectToDetail(props.row)">
            <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
            v-if="
              props.row.step === 'CHECK_SPEC' ||
              props.row.step === 'PREPARE_DOC_V1' ||
              props.row.step === 'CHECK_DOC_V1'
            "
          />
          <q-card-actions align="around">
            <q-btn
              v-if="
                props.row.step === 'CHECK_SPEC' ||
                props.row.step === 'PREPARE_DOC_V1' ||
                props.row.step === 'CHECK_DOC_V1'
              "
              flat
              dense
              round
              color="red"
              icon="delete"
              @click.stop="onCkilckDelete(props.row.id)"
            >
              <q-tooltip>ลบ</q-tooltip>
            </q-btn>
          </q-card-actions>
        </q-card>
      </div>
    </template>
    <template v-slot:pagination="scope">
      ทั้งหมด {{ total }} รายการ
      <q-pagination
        v-model="pagination.page"
        active-color="primary"
        color="dark"
        :max="Number(totalList)"
        size="sm"
        boundary-links
        direction-links
        :max-pages="5"
        @update:model-value="props.fetchData?.()"
      ></q-pagination>
    </template>
  </d-table>
</template>

<style lang="scss" scoped>
.custom-header-table {
  height: auto;
  .q-table tr:nth-child(odd) td {
    background: white;
  }
  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }
  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }
  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
