<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";
import { useDevelopmentDataStore } from "@/modules/15_development/store/developmentStore";
import { useCounterMixin } from "@/stores/mixin";
import { checkPermission } from "@/utils/permissions";

/**
 * importType
 */
import type {
  DataOption,
  DataHistory,
  NewPagination,
  ItemsMenu,
} from "@/modules/15_development/interface/index/Main";
import type { ResHistory } from "@/modules/15_development/interface/response/Main";

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

const formFilter = reactive({
  root: null,
  page: 1,
  pageSize: 10,
  keyword: "",
  year: new Date().getFullYear(),
});
const agencyOp = ref<DataOption[]>([]); // หน่วยงาน

/**
 * ข้อมูล Table
 */
const rows = ref<DataHistory[]>([]);
const maxPage = ref<number>(1); //จำนวนหน้าสูงสุด
const totalList = ref<number>(0); //จำนวนข้อมูลรายการ
const columns = ref<QTableProps["columns"]>([
  {
    name: "year",
    align: "left",
    label: "ปีงบประมาณ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => v + 543,
  },
  {
    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",
  },
]);
const pagination = ref({
  page: formFilter.page,
  rowsPerPage: formFilter.pageSize,
});
const visibleColumns = ref<string[]>([
  "year",
  "citizenId",
  "name",
  "position",
  "type",
  "level",
  "positionSide",
  "projectName",
]);

/** menuDownload*/
const itemMenu = ref<ItemsMenu[]>([
  {
    label: "ไฟล์ .xlsx",
    value: "xlsx",
    icon: "mdi-file-excel",
    color: "green",
  },
  {
    label: "ไฟล์ .pdf",
    value: "pdf",
    icon: "mdi-file-pdf",
    color: "red",
  },
]);

/**
 * function เรียกข้อมูหน่วยงาน
 */
function fetchListOrg() {
  showLoader();
  http
    .get(config.API.developmentHistoryListOrg("officer", formFilter.year))
    .then(async (res) => {
      formFilter.root = null;
      formFilter.page = 1;
      rows.value = [];
      const option = [{ name: "ทั้งหมด", id: null }];
      const optionNew = await res.data.result.map((e: string) => ({
        name: e,
        id: e,
      }));
      option.push(...optionNew);
      agencyOp.value = option;
      await getData();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function เรียกข้อมูลรายการประวัติการฝึกอบรม/ดูงานของข้าราชการกรุงเทพมหานครสามัญ
 */
async function getData() {
  showLoader();
  formFilter.keyword = formFilter.keyword.trim();
  await http
    .post(config.API.developmentHistoryList("officer"), formFilter)
    .then((res) => {
      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: ResHistory) => ({
        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,
        year: item.year ? item.year : null,
      }));
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

/**
 * function redirect รายละเอียด
 * @param id id ของ row
 */
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">
        <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>

        <q-select
          dense
          outlined
          label="หน่วยงาน"
          v-model="formFilter.root"
          :options="agencyOp"
          option-value="id"
          option-label="name"
          @update:model-value="(formFilter.page = 1), getData()"
          style="min-width: 150px"
          map-options
          emit-value
        >
          <template v-if="formFilter.root" v-slot:append>
            <q-icon
              name="cancel"
              @click.stop.prevent="(formFilter.root = null), fetchListOrg()"
              class="cursor-pointer"
            /> </template
        ></q-select>
      </q-toolbar>
      <q-toolbar class="col-4 q-pa-none q-gutter-x-sm">
        <q-space />

        <q-btn
          v-if="
            formFilter.root !== null &&
            checkPermission($route)?.attrIsGet !== false
          "
          flat
          round
          dense
          icon="mdi-arrow-down-bold-circle-outline"
          color="blue"
        >
          <q-menu>
            <q-list style="min-width: 150px">
              <q-item
                clickable
                v-close-popup
                v-for="items in itemMenu"
                @click="onDownload(items.value)"
              >
                <q-item-section avatar>
                  <q-icon :color="items.color" :name="items.icon" />
                </q-item-section>
                <q-item-section>{{ items.label }}</q-item-section>
                <q-tooltip>{{ items.label }}</q-tooltip>
              </q-item>
            </q-list>
          </q-menu>
          <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 name="search" />
            </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"
          />
        </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:header="props">
          <q-tr :props="props">
            <q-th auto-width></q-th>
            <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 auto-width>
              <q-btn
                v-if="checkPermission($route)?.attrIsGet"
                flat
                round
                dense
                icon="mdi-eye"
                color="info"
                @click="onEdit(props.row.id)"
              >
                <q-tooltip>รายละเอียด</q-tooltip>
              </q-btn>
            </q-td>
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div class="table_ellipsis">
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>

        <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>
      </d-table>
    </div>
  </q-card>
</template>
