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

import type { PropsTable } from "@/interface/PropsTable";
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 { dialogRemove, showLoader, hideLoader, success, messageError } = mixin;

const isLoading = defineModel<boolean>("isLoading", {
  default: false,
});
const pagination = defineModel<PropsTable.Pagination>("pagination", {
  required: true,
});

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

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

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

/**
 * function ลบรายการประเมิน
 * @param id รายการประเมิน
 */
async function onClickDelete(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}`);
}

/**
 * ฟังก์ชันรับ request จากตาราง เมื่อมีการเปลี่ยน pagination
 * @param requestProps ข้อมูลการร้องขอจากตาราง
 */
function onTableRequest(requestProps: PropsTable.RequestProps) {
  const newPagination = requestProps?.pagination || requestProps;
  if (!newPagination?.page || !newPagination?.rowsPerPage) return;
  pagination.value = { ...newPagination };
  props.fetchData?.();
}

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

<template>
  <d-table
    ref="table"
    flat
    bordered
    :columns="columns"
    :rows="store.row"
    dense
    :visible-columns="store.visibleColumns"
    :rows-per-page-options="[10, 25, 50, 100]"
    @request="onTableRequest"
    v-model: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" 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="onClickDelete(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="onClickDelete(props.row.id)"
            >
              <q-tooltip>ลบ</q-tooltip>
            </q-btn>
          </q-card-actions>
        </q-card>
      </div>
    </template>
  </d-table>
</template>

<style lang="scss" scoped></style>
