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

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

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

/** use*/
const $q = useQuasar();
const {
  showLoader,
  success,
  messageError,
  dialogConfirm,
  hideLoader,
  date2Thai,
} = useCounterMixin();
const { convertResults, convertStatus } = useKpiDataStore();
const store = 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 }, // function เรีนกข้อมูลประกาศผล
});

/** Table*/
const selected = ref<ResResults[]>([]);
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, false, true);
    },
    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",
  },
  {
    name: "organization",
    align: "left",
    label: "หน่วยงาน/ส่วนราชการ",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posTypeName",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevelName",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: true,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "root",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "root",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "fullName",
  "createdAt",
  // "evaluationStatus",
  "evaluationResults",
  "organization",
  "position",
  "posTypeName",
  "posLevelName",
  "root",
]);
const pagination = ref({
  page: page.value,
  rowsPerPage: pageSize.value,
});

/** ตัวแปร*/
const year = ref<number | null>(new Date().getFullYear()); //ปีงบประมาณ
const roundOp = ref<DataOption[]>([]); // รายการรอบการประเมิน

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

/** function fetch รอบการประเมิน*/
async function fetchRoundOption() {
  showLoader();
  await http
    .get(
      config.API.kpiPeriod +
        `?page=${1}&pageSize=${10}&keyword=${""}&year=${year.value}`
    )
    .then(async (res) => {
      const data = await res.data.result.data;
      if (res.data.result.data.length > 0) {
        const list = await data.map((e: ResRound) => ({
          id: e.id,
          name:
            e.durationKPI === "OCT"
              ? "รอบที่ 2 ตุลาคม"
              : e.durationKPI === "APR"
              ? "รอบที่ 1 เมษายน"
              : "",
        }));

        roundOp.value = list;
        store.formQuery.round = list[0].id;
        await porps.fetchData();
      } else {
        roundOp.value = [];
        store.formQuery.round = "";
        rows.value = [];
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เปลี่ยนรอบการประเมิน และ เรียกข้อมูลรายการแผนพัฒนาการปฏิบัติราชการรายบุคคลย้อนหลัง*/
function changRound() {
  store.formQuery.page = 1;
  porps.fetchData();
}

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

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

/** ทำงานเมื่อมีการเปลี่ยนแถวต่อหน้า*/
onMounted(async () => {
  store.formQuery.round = "";
  await fetchRoundOption();
});
</script>

<template>
  <q-card-section>
    <div class="items-center col-12 row q-gutter-x-sm q-mb-sm">
      <div class="row q-gutter-sm">
        <datepicker
          menu-class-name="modalfix"
          v-model="year"
          style="width: 150px"
          :locale="'th'"
          autoApply
          year-picker
          :enableTimePicker="false"
          @update:model-value="fetchRoundOption()"
        >
          <template #year="{ year }">{{ year + 543 }}</template>
          <template #year-overlay-value="{ value }">{{
            parseInt(value + 543)
          }}</template>
          <template #trigger>
            <q-input
              dense
              outlined
              hide-bottom-space
              :model-value="!!year ? year + 543 : null"
              :label="`${'ปีงบประมาณ'}`"
            >
              <template v-slot:prepend>
                <q-icon
                  name="event"
                  class="cursor-pointer"
                  style="color: var(--q-primary)"
                >
                </q-icon>
              </template>
            </q-input>
          </template>
        </datepicker>

        <q-select
          v-model="store.formQuery.round"
          outlined
          label="รอบการประเมิน"
          dense
          option-label="name"
          option-value="id"
          :options="roundOp"
          style="min-width: 150px"
          emit-value
          map-options
          @update:model-value="changRound"
        />
      </div>

      <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"
        style="min-width: 140px"
      />
    </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"
      :visible-columns="visibleColumns"
    >
      <template v-slot:header-selection="scope" v-if="tab === 'COMPLETE'">
        <q-checkbox
          v-if="tab === 'COMPLETE' && checkPermission($route)?.attrIsUpdate"
          keep-color
          color="primary"
          dense
          v-model="scope.selected"
        />
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td v-if="tab === 'COMPLETE'">
            <q-checkbox
              v-if="tab === 'COMPLETE' && checkPermission($route)?.attrIsUpdate"
              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 class="table_ellipsis2">
              {{ 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' && checkPermission($route)?.attrIsUpdate"
  />

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

<style scoped></style>
