<script setup lang="ts">
import { ref, watch } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/**
 * importType
 */
import type { QTableProps } from "quasar";
import type { ResResults } from "@/modules/14_KPI/interface/response/Main";

/**
 * importStore
 */
import { useCounterMixin } from "@/stores/mixin";
import { useKpiDataStore } from "@/modules/14_KPI/store";

/**
 * use
 */
const $q = useQuasar();
const {
  showLoader,
  success,
  messageError,
  dialogConfirm,
  hideLoader,
  date2Thai,
} = useCounterMixin();
const { convertResults, convertStatus } = useKpiDataStore();

/**
 * props
 */
const tab = defineModel<string>("tab", { required: true });
const rows = defineModel<ResResults[]>("row", { required: true });
const page = defineModel<number>("page", { required: true });
const pageSize = defineModel<number>("pageSize", { required: true });
const maxPage = defineModel<number>("maxPage", { required: true });
const total = defineModel<number>("total", { required: true });
const keyword = defineModel<string>("keyword", { required: true });
const porps = defineProps({
  fetchData: { type: Function, required: true },
});

/**
 * Table
 */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ผู้รับการประเมิน",
    sortable: true,
    field: "fullName",
    format: (val, row) => {
      return `${row.prefix ?? ""}${row.firstname ?? ""} ${row.lastname ?? ""}`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่สร้างแบบประเมิน",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    format(val, row) {
      return date2Thai(val);
    },
    style: "font-size: 14px",
  },
  {
    name: "evaluationStatus",
    align: "left",
    label: "สถานะการประเมิน",
    sortable: true,
    field: "evaluationStatus",
    format(val, row) {
      return val === "KP7" ? "ประการผลแล้ว" : convertStatus(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "evaluationResults",
    align: "left",
    label: "ผลการประเมิน",
    sortable: true,
    field: "evaluationResults",
    format(val, row) {
      return convertResults(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "fullName",
  "createdAt",
  "evaluationStatus",
  "evaluationResults",
]);
const pagination = ref({
  page: page.value,
  rowsPerPage: pageSize.value,
});
const selected = ref<ResResults[]>([]);

/**
 * function บันทึกการประกาศผล
 */
function onAnnounce() {
  const ids = selected.value.map((item) => item.id);
  dialogConfirm(
    $q,
    () => {
      showLoader();
      http
        .post(config.API.evaluationUserDone, {
          id: ids,
        })
        .then(() => {
          setTimeout(async () => {
            await porps.fetchData();
            await success($q, "ประกาศผลสำเร็จ");
            selected.value = [];
          }, 1500);
        })
        .catch((err) => {
          messageError($q, err);
          hideLoader();
        });
    },
    "ยืนยันการประกาศผล",
    "ต้องการยืนยันการประกาศผลใช่หรือไม่?"
  );
}

/**
 * ค้นหาข้อมูล
 */
function onSearchData() {
  page.value = 1;
  porps.fetchData();
}

/**
 * ทำงานเมื่อมีการเปลี่ยนแถวต่อหน้า
 */
watch(pagination, () => {
  page.value = 1;
  pageSize.value = pagination.value.rowsPerPage;
});
</script>

<template>
  <q-card-section>
    <div class="items-center col-12 row q-gutter-x-sm q-mb-sm">
      <q-space />

      <q-input
        borderless
        dense
        outlined
        v-model="keyword"
        placeholder="ค้นหา"
        @keydown.enter="onSearchData"
      >
        <template v-slot:append>
          <q-icon v-if="keyword === ''" name="search" />
          <q-icon
            v-else
            name="clear"
            class="cursor-pointer"
            @click="(keyword = ''), onSearchData()"
          />
        </template>
      </q-input>
      <q-select
        v-model="visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="columns"
        option-value="name"
        options-cover
      />
    </div>
    <d-table
      :columns="columns"
      :rows="rows"
      row-key="id"
      :selection="tab === 'COMPLETE' ? 'multiple' : null"
      v-model:selected="selected"
      :rows-per-page-options="[10, 25, 50, 100]"
      v-model:pagination="pagination"
      :paging="true"
    >
      <template v-slot:header-selection="scope" v-if="tab === 'COMPLETE'">
        <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="tab === 'COMPLETE'">
            <q-checkbox
              keep-color
              color="primary"
              dense
              v-model="props.selected"
            />
          </q-td>
          <q-td v-for="col in props.cols" :key="col.name" :props="props">
            <div v-if="col.name == 'no'">
              {{ (page - 1) * pageSize + props.rowIndex + 1 }}
            </div>
            <div v-else>
              {{ col.value ?? "-" }}
            </div>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="scope">
        ทั้งหมด {{ total }} รายการ
        <q-pagination
          v-model="page"
          active-color="primary"
          color="dark"
          :max="Number(maxPage)"
          size="sm"
          boundary-links
          direction-links
          :max-pages="5"
          @update:model-value="porps.fetchData()"
        ></q-pagination>
      </template>
    </d-table>
  </q-card-section>
  <q-separator v-if="tab === 'COMPLETE'" />

  <q-card-actions
    align="right"
    class="bg-white text-teal"
    v-if="tab === 'COMPLETE'"
  >
    <q-btn
      label="ประกาศผล"
      color="public"
      @click="onAnnounce"
      :disable="selected.length === 0"
    />
  </q-card-actions>
</template>

<style scoped></style>
