<script setup lang="ts">
import { ref, onMounted, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import { useQuasar, type QTableProps } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";
import genReportXLSX from "@/plugins/genreportxlsx";

/**importType*/
import type { NewPagination } from "@/modules/15_development/interface/index/Main";

/** importStore*/
import { useDevelopmentDataStore } from "@/modules/15_development/store/developmentStore";
import { useCounterMixin } from "@/stores/mixin";

const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const formFilter = reactive({
  root: null,
  page: 1,
  pageSize: 20,
  keyword: "",
  year: new Date().getFullYear(),
});

const maxPage = ref<number>(1);
const totalList = ref<number>(0); //จำนวนข้อมูลรายการ

/** use*/
const router = useRouter();
const store = useDevelopmentDataStore();
const $q = useQuasar();
const { showLoader, hideLoader, messageError } = useCounterMixin();
const rows = ref<any>([]);
const agencyOp = ref<[]>([]);
const visibleColumns = ref<string[]>([
  "citizenId",
  "name",
  "position",
  "type",
  "level",
  "positionSide",
  "projectName",
]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ - นามสกุล",
    sortable: true,
    field: "name",
    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: "type",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "type",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "level",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: true,
    field: "level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionSide",
    align: "left",
    label: "ตําแหน่งทางการบริหาร",
    sortable: true,
    field: "positionSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "projectName",
    align: "left",
    label: "ชื่อโครงการ/กิจกรรม/หลักสูตร",
    sortable: true,
    field: "projectName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** ดึงข้อมูลหน่วยงาน */
function fetchListOrg() {
  showLoader();
  http
    .get(config.API.developmentHistoryListOrg("officer", formFilter.year))
    .then((res) => {
      formFilter.root = null;
      formFilter.page = 1;
      rows.value = [];
      agencyOp.value = res.data.result;
      getData();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดึงข้อมูลรายการ */
function getData() {
  showLoader();
  http
    .post(config.API.developmentHistoryList("officer"), formFilter)
    .then((res) => {
      console.log(res.data.result.data);
      const data = res.data.result.data;
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
      totalList.value = res.data.result.total;
      rows.value = data.map((item: any) => ({
        id: item.id ? item.id : null,
        citizenId: item.citizenId ? item.citizenId : null,
        name: item.fullName ? item.fullName : null,
        position: item.position ? item.position : null,
        type: item.posType ? item.posType : null,
        level: item.posLevel ? item.posLevel : null,
        projectName: item.projectName ? item.projectName : null,
        positionSide: item.posExecutive ? item.posExecutive : null,
      }));
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** download file */
function onDownload() {
  showLoader();
  http
    .post(config.API.developmentReportHistory(), {
      year: formFilter.year,
      root: formFilter.root,
    })
    .then((res) => {
      const dataList = res.data.result;
      genReportXLSX(
        dataList,
        "รายการประวัติการฝึกอบรม/ดูงานของข้าราชการกรุงเทพมหานครสามัญ"
      );
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** edit page */
function onEdit(id: string) {
  store.statusEdit = true;
  router.push(`/development/history/${id}`);
}

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: NewPagination) {
  formFilter.page = 1;
  formFilter.pageSize = newPagination.rowsPerPage;
}

/** callbackFunction ทำเมื่อมีการอัปเดท pageSize*/
watch(
  () => formFilter.pageSize,
  () => {
    getData();
  }
);

/** ดึงข้อมูลเมื่ออยู่ในหน้า */
onMounted(() => {
  fetchListOrg();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการประวัติการฝึกอบรม/ดูงานของข้าราชการกรุงเทพมหานครสามัญ
  </div>
  <q-card flat bordered class="q-pa-md">
    <div class="row no-wrap shadow-1 justify-between">
      <q-toolbar class="row col-8 q-pa-none q-gutter-x-sm">
        <div class="col-3">
          <datepicker
            menu-class-name="modalfix"
            v-model="formFilter.year"
            :locale="'th'"
            autoApply
            year-picker
            :enableTimePicker="false"
            @update:model-value="fetchListOrg()"
          >
            <template #year="{ year }">{{ year + 543 }}</template>
            <template #year-overlay-value="{ value }">{{
              parseInt(value + 543)
            }}</template>
            <template #trigger>
              <q-input
                dense
                lazy-rules
                outlined
                :model-value="
                  formFilter.year === 0
                    ? 'ทั้งหมด'
                    : Number(formFilter.year) + 543
                "
                :label="`${'ปีงบประมาณ'}`"
              >
                <template v-if="formFilter.year" v-slot:append>
                  <q-icon
                    name="cancel"
                    @click.stop.prevent="(formFilter.year = 0), fetchListOrg()"
                    class="cursor-pointer"
                  />
                </template>
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    style="color: var(--q-primary)"
                  >
                  </q-icon>
                </template>
              </q-input>
            </template>
          </datepicker>
        </div>

        <div class="col-3">
          <q-select
            dense
            outlined
            label="หน่วยงาน"
            v-model="formFilter.root"
            :options="agencyOp"
            option-value="id"
            option-label="name"
            @update:model-value="(formFilter.page = 1), getData()"
          />
        </div>
      </q-toolbar>
      <q-toolbar class="col-4 text-white q-pa-none q-gutter-x-sm">
        <q-space />
        <q-btn
          flat
          round
          dense
          icon="mdi-arrow-down-bold-circle-outline"
          color="blue"
          @click="onDownload"
        >
          <q-tooltip>ดาวน์โหลด</q-tooltip>
        </q-btn>
        <div class="col-4">
          <q-input
            standout
            dense
            v-model="formFilter.keyword"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            @keydown.enter.prevent="(formFilter.page = 1), getData()"
          >
            <template v-slot:append>
              <q-icon v-if="formFilter.keyword == ''" name="search" />
              <q-icon
                v-if="formFilter.keyword !== ''"
                name="clear"
                class="cursor-pointer"
                @click="
                  formFilter.keyword = '';
                  getData();
                "
              />
            </template>
          </q-input>
        </div>
        <div class="col-4">
          <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>
      </q-toolbar>
    </div>
    <div class="col-12">
      <d-table
        for="table"
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="subject"
        flat
        bordered
        dense
        class="custom-header-table"
        :visible-columns="visibleColumns"
        v-model:pagination="pagination"
        :rows-per-page-options="[10, 25, 50, 100]"
        @update:pagination="updatePagination"
      >
        <template v-slot:pagination="scope">
          ทั้งหมด {{ totalList }} รายการ
          <q-pagination
            v-model="formFilter.page"
            active-color="primary"
            color="dark"
            :max="Number(maxPage)"
            :max-pages="5"
            size="sm"
            boundary-links
            direction-links
            @update:model-value="getData"
          ></q-pagination>
        </template>
        <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">{{ col.label }}</span>
            </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="onEdit(props.row.id)"
            >
              <div class="table_ellipsis">
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>
</template>
