<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 { DataOption } from "@/modules/14_KPI/interface/index/Main";
import type {
  ResRound,
  ResDevelopment,
} from "@/modules/14_KPI/interface/response/Index";

/** importComponents*/
import DialogIndividual from "@/modules/14_KPI/components/results/dialogIndividual.vue";

/** use*/
const $q = useQuasar();
const { showLoader, messageError, hideLoader } = useCounterMixin();
const store = useKpiDataStore();

/** props*/
const tab = defineModel<string>("tab", { required: true });

/**
 * ตัวแปร
 */
const rows = ref<ResDevelopment[]>([]); // ข่อมูลรายการ
const page = ref<number>(1);
const pageSize = ref<number>(10);
const maxPage = ref<number>(1);
const total = ref<number>(1);
const keyword = ref<string>("");
const modalDetail = ref<boolean>(false);
const devId = ref<string>("");

/** 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: "developmentName",
    align: "left",
    label: "ความรู้/ทักษะ/สมรรถนะ ที่ต้องได้รับการพัฒนา",
    sortable: true,
    field: "developmentName",
    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: "posTypeName",
    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",
  "name",
  "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 fetch รายการแผนพัฒนาการปฏิบัติราชการรายบุคคลย้อนหลัง*/
async function fetcDataList() {
  showLoader();
  await http
    .post(config.API.achievementDev, {
      page: page.value,
      pageSize: pageSize.value,
      keyword: keyword.value.trim(),
      kpiPeriodId: store.formQuery.round ? store.formQuery.round : "",
    })
    .then(async (res) => {
      const data = await res.data.result;
      rows.value = data.data;
      total.value = data.total;
      maxPage.value = Math.ceil(total.value / pageSize.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 fetcDataList();
      } else {
        roundOp.value = [];
        store.formQuery.round = "";
        rows.value = [];
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

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

/**
 * function รายละเอียดแผนพัฒนาการปฏิบัติราชการรายบุคคล
 * @param id แผนพัฒนาการปฏิบัติราชการรายบุคคล
 */
function onClickView(id: string) {
  modalDetail.value = true;
  devId.value = id;
}

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

/** HookLifecycle*/
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 name="search" />
        </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"
      :rows-per-page-options="[10, 25, 50, 100]"
      v-model:pagination="pagination"
      :paging="true"
      :visible-columns="visibleColumns"
    >
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th auto-width />
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            <span class="text-weight-medium">{{ col.label }}</span>
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td
            ><q-btn
              v-if="checkPermission($route)?.attrIsGet"
              flat
              dense
              round
              color="info"
              icon="mdi-eye"
              @click="onClickView(props.row.id)"
            >
              <q-tooltip>รายละเอียดแผนพัฒนาการปฏิบัติราชการรายบุคคล</q-tooltip>
            </q-btn></q-td
          >
          <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 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="fetcDataList()"
        ></q-pagination>
      </template>
    </d-table>
  </q-card-section>

  <DialogIndividual v-model:devId="devId" v-model:modal="modalDetail" />
</template>

<style scoped></style>
