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

import config from "@/app.config";
import http from "@/plugins/http";
import { useCounterMixin } from "@/stores/mixin";
import { useKpiDataStore } from "@/modules/08_KPI/store";

import type { FormQuery } from "@/modules/08_KPI/interface/request/index";
import type { ResEvaluatorAssessor } from "@/modules/08_KPI/interface/response/index";

const $q = useQuasar();
const router = useRouter();
const store = useKpiDataStore();
const {
  showLoader,
  hideLoader,
  messageError,
  dialogConfirm,
  dialogMessageNotify,
  success,
} = useCounterMixin();

const visibleColumns = defineModel<string[]>("visibleColumns", {
  required: true,
});
const columns = defineModel<QTableProps["columns"]>("columns", {
  required: true,
});
const rows = defineModel<ResEvaluatorAssessor[]>("rows", { required: true });
const formQuery = defineModel<FormQuery>("formQuery", { required: true });
const total = defineModel<number>("total", { required: true });
const maxPage = defineModel<number>("maxPage", { required: true });

const props = defineProps({
  updatePagination: { type: Function },
  fetchList: { type: Function },
});

function redirectViewDetail(id: string) {
  router.push(`/KPI-evaluator/${id}`);
}

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

async function onClickApprove(type: string = "") {
  if (store.selected.length !== 0) {
    const userIds = await store.selected.map(
      (user: ResEvaluatorAssessor) => user.id
    );
    dialogConfirm(
      $q,
      async () => {
        showLoader();
        const url =
          store.tabMainevaluator === "2" || store.tabMainevaluator === "4"
            ? "change-status"
            : store.tabMainevaluator === "3"
            ? "req-edit"
            : "result-status";
        const body = {
          status:
            store.tabMainevaluator === "2"
              ? "APPROVE"
              : store.tabMainevaluator === "3"
              ? "DONE"
              : store.tabMainevaluator === "4"
              ? "EVALUATING"
              : store.tabMainevaluator === "5" || store.tabMainevaluator === "6"
              ? type
              : undefined,
          id: userIds,
        };
        await http
          .post(config.API.kpiEvaluation + `/admin/${url}`, body)
          .then(async () => {
            store.selected = [];
            await props.fetchList?.();
            success(
              $q,
              store.tabMainevaluator === "5"
                ? "ยืนยันการประเมินสำเร็จ"
                : "อนุมัติสำเร็จ"
            );
          })
          .catch((err) => {
            messageError($q, err);
          })
          .finally(() => {
            hideLoader();
          });
      },
      store.tabMainevaluator === "5" ? "ยืนยันการประเมิน" : "ยืนยันการอนุมัติ"
    );
  } else {
    dialogMessageNotify($q, "เลือกอย่างน้อย 1 รายการ");
  }
}
</script>

<template>
  <div class="col-12">
    <d-table
      ref="table"
      :columns="columns"
      :rows="rows"
      row-key="id"
      flat
      bordered
      :paging="true"
      dense
      :rows-per-page-options="[10, 25, 50, 100]"
      :visible-columns="visibleColumns"
      v-model:pagination="pagination"
      @update:pagination="props.updatePagination"
      :selection="
        store.tabMainevaluator === '5' || store.tabMainevaluator === '6'
          ? 'none'
          : 'multiple'
      "
      v-model:selected="store.selected"
    >
      <template v-slot:header-selection="scope">
        <q-checkbox keep-color color="primary" dense v-model="scope.selected" />
      </template>

      <template v-slot:body="props">
        <q-tr :props="props" class="cursor-pointer">
          <q-td
            v-if="
              store.tabMainevaluator !== '5' && store.tabMainevaluator !== '6'
            "
          >
            <q-checkbox
              keep-color
              color="primary"
              dense
              v-model="props.selected"
            />
          </q-td>
          <q-td
            v-for="col in props.cols"
            :key="col.id"
            @click="redirectViewDetail(props.row.id)"
          >
            <div v-if="col.name === 'name'">
              {{
                `${props.row.prefix}${props.row.firstname}  ${props.row.lastname}`
              }}
            </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"
          :style="props.selected ? 'transform: scale(0.95);' : ''"
        >
          <q-card
            bordered
            flat
            :class="
              props.selected
                ? $q.dark.isActive
                  ? 'bg-grey-9'
                  : 'bg-grey-2'
                : ''
            "
          >
            <q-card-section>
              <q-checkbox
                dense
                v-model="props.selected"
                :label="props.row.name"
              />
            </q-card-section>
            <q-separator />
            <q-list @click="redirectViewDetail(props.row.id)">
              <q-item
                v-for="col in props.cols"
                :key="col.name"
              >
                <q-item-section>
                  <q-item-label caption>{{ col.label }}</q-item-label>

                  <q-item-label>
                    <div v-if="col.name === 'name'">
                      {{
                        `${props.row.prefix}${props.row.firstname}  ${props.row.lastname}`
                      }}
                    </div>
                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div></q-item-label
                  >
                </q-item-section>
              </q-item>
            </q-list>
          </q-card>
        </div>
      </template>
      <template v-slot:pagination="scope">
        ทั้งหมด {{ total }} รายการ
        <q-pagination
          v-model="formQuery.page"
          active-color="primary"
          color="dark"
          :max="Number(maxPage)"
          size="sm"
          boundary-links
          direction-links
          :max-pages="5"
          @update:model-value="props.fetchList?.()"
        ></q-pagination>
      </template>
    </d-table>
  </div>

  <div class="row justify-end q-mt-md q-gutter-sm" v-if="rows.length !== 0">
    <q-btn
      v-if="store.tabMainevaluator !== '5' && store.tabMainevaluator !== '6'"
      color="public"
      label="อนุมัติ"
      @click="onClickApprove('PASSED')"
    />
  </div>
</template>

<style scoped></style>
