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

import http from "@/plugins/http";
import config from "@/app.config";
import { useRouter } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { checkPermission } from "@/utils/permissions";
import { usePagination } from "@/composables/usePagination";
import { calculateFiscalYear } from "@/utils/function";

/** importType*/
import type {
  DataOption,
  DataAssignment,
} from "@/modules/01_masterdata/interface/index/Main";
import type { FormFilterAssignment } from "@/modules/01_masterdata/interface/request/Main";
import type { ResAssignment } from "@/modules/01_masterdata/interface/response/Main";

/** importComponents*/
import Summary from "@/modules/01_masterdata/components/Indicators/Summary.vue";

const $q = useQuasar();
const router = useRouter();
const { showLoader, hideLoader, dialogRemove, success, messageError } =
  useCounterMixin();
const { pagination, params, onRequest, checkAndUpdatePage } = usePagination(
  "",
  fetchList
);

/** table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "including",
    align: "left",
    label: "รหัสตัวชี้วัด",
    sortable: true,
    field: "including",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "includingName",
    align: "left",
    label: "ชื่อตัวชี้วัด",
    sortable: true,
    field: "includingName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>(["including", "includingName"]);

/** Option  รอบการประเมิน*/
const roundOp = ref<DataOption[]>([
  { id: "", name: "ทั้งหมด" },
  { id: "APR", name: "รอบเมษายน" },
  { id: "OCT", name: "รอบตุลาคม" },
]);
const rows = ref<DataAssignment[]>([]);

const formFilter = reactive<FormFilterAssignment>({
  keyword: "",
  period: "",
  year: calculateFiscalYear(new Date()),
});

/** ฟังก์ชันดึงข้อมูลรายการงานอื่นๆ ที่ได้รับมอบหมาย*/
async function fetchList() {
  showLoader();
  formFilter.year = formFilter.year ? formFilter.year.toString() : null;
  await http
    .post(config.API.kpiSpecial + `/search-edit`, {
      ...formFilter,
      ...params.value,
      keyword: formFilter.keyword.trim(),
    })
    .then((res: ResAssignment) => {
      const result = res.data.result;
      pagination.value.rowsNumber = result.total;
      rows.value = result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันเปิดดูรายละเอียดงานที่ได้รับมอบหมาย
 * @param id รหัสงานที่ได้รับมอบหมาย
 */
function onClickView(id: string = "") {
  router.push(`/masterdata/indicator-assignment/${id}`);
}

/**
 * ฟังก์ชันลบงานที่ได้รับมอบหมาย
 * @param id รหัสงานที่ได้รับมอบหมาย
 */
function onClickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.kpiSpecial + `/${id}`)
      .then(async () => {
        await checkAndUpdatePage(rows.value.length);
        await fetchList();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function fetchNewList() {
  pagination.value.page = 1;
  fetchList();
}

onMounted(async () => {
  await fetchList();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการงานอื่นๆ ที่ได้รับมอบหมาย
  </div>

  <Summary />

  <q-card flat bordered class="q-pa-md">
    <div class="row q-col-gutter-sm q-pl-sm">
      <q-toolbar style="padding: 0">
        <div class="row q-gutter-sm">
          <datepicker
            style="width: 150px"
            v-model="formFilter.year"
            :locale="'th'"
            autoApply
            year-picker
            :enableTimePicker="false"
            @update:model-value="(formFilter.period = ''), fetchNewList()"
          >
            <template #year="{ year }">{{ year + 543 }}</template>
            <template #year-overlay-value="{ value }">{{
              parseInt(value + 543)
            }}</template>
            <template #trigger>
              <q-input
                dense
                outlined
                :model-value="
                  formFilter.year === null
                    ? 'ทั้งหมด'
                    : Number(formFilter.year) + 543
                "
                :label="`${'ปีงบประมาณ'}`"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    style="color: var(--q-primary)"
                  >
                  </q-icon>
                </template>
                <template v-if="formFilter.year" v-slot:append>
                  <q-icon
                    name="cancel"
                    @click.stop.prevent="
                      (formFilter.year = null), fetchNewList()
                    "
                    class="cursor-pointer"
                  />
                </template>
              </q-input>
            </template>
          </datepicker>
          <q-select
            dense
            outlined
            v-model="formFilter.period"
            :options="roundOp"
            label="รอบการประเมิน"
            option-label="name"
            option-value="id"
            emit-value
            map-options
            @update:model-value="fetchNewList"
            style="width: 160px"
          >
            <template v-if="formFilter.period" v-slot:append>
              <q-icon
                name="cancel"
                @click.stop.prevent="(formFilter.period = ''), fetchNewList()"
                class="cursor-pointer"
              />
            </template>
          </q-select>
        </div>
        <q-space />
        <div class="row q-gutter-sm">
          <q-input
            dense
            outlined
            v-model="formFilter.keyword"
            label="ค้นหา"
            @keydown.enter.prevent="fetchNewList"
          >
            <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>
      </q-toolbar>
    </div>
    <div class="col-12">
      <d-table
        for="table"
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        flat
        bordered
        dense
        class="custom-header-table"
        :rows-per-page-options="[10, 25, 50, 100]"
        :visible-columns="visibleColumns"
        v-model:pagination="pagination"
        @request="onRequest"
      >
        <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 auto-width>
              <q-btn
                v-if="checkPermission($route)?.attrIsGet"
                flat
                round
                dense
                color="info"
                icon="mdi-eye"
                @click.prevent="onClickView(props.row.id)"
              >
                <q-tooltip>รายละเอียด</q-tooltip>
              </q-btn>
              <q-btn
                v-if="checkPermission($route)?.attrIsDelete"
                flat
                dense
                round
                color="red"
                icon="mdi-delete "
                @click.prevent="onClickDelete(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>
      </d-table>
    </div>
  </q-card>
</template>

<style scoped></style>
