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

import type { FormListMainByRole } from "@/modules/01_metadataNew/interface/request/Main";
import type {
  DataOption,
  NewPagination,
} from "@/modules/01_metadataNew/interface/index/Main";

import DialogHistory from "@/modules/01_metadataNew/components/Indicators/DialogHistory.vue";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

/** use*/
const dataHistory = ref<any[]>([]);
const modalHistory = ref<boolean>(false);
const total = ref<number>();
const $q = useQuasar();
const router = useRouter();
const { showLoader, hideLoader, dialogRemove, success, messageError } =
  useCounterMixin();

const positionOp = ref<DataOption[]>([{ id: "", name: "ทั้งหมด" }]);
const positionMainOp = ref<DataOption[]>([{ id: "", name: "ทั้งหมด" }]);

const maxPage = ref<number>(1);

/** หัวตาราง */
const rows = ref<any[]>([]);
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"]);

const formFilter = reactive<FormListMainByRole>({
  page: 1,
  pageSize: 10,
  position: "",
  round: "",
  keyword: "",
  year: new Date().getFullYear(),
});
const pagination = ref({
  page: formFilter.page,
  rowsPerPage: formFilter.pageSize,
});

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

function fetchList() {
  http
    .post(config.API.kpiRoleMainList + `/search`, {
      // ?page=${formFilter.page}&pageSize=${formFilter.pageSize}&period=${formFilter.round}&position=${formFilter.position}&keyword=${formFilter.keyword}&year=${formFilter.year}
      keyword: formFilter.keyword,
      position: formFilter.position,
      period: formFilter.round,
      node: 0,
      nodeId: "",
      year: formFilter.year?.toString(),
      pageSize: formFilter.pageSize,
      page: formFilter.page,
    })
    .then((res) => {
      const data = res.data.result.data;
      total.value = res.data.result.total;
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
      rows.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onClickAddOrView(status: boolean = false, id: string = "") {
  status
    ? router.push(`/KPI-indicator-role/${id}`)
    : router.push("/KPI-indicator-role/add");
}

function onClickDelete(id: number) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.kpiRoleMainList + `/${id}`)
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
        fetchList();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function updatePage(val: number) {
  formFilter.page = val;
  fetchList();
}

function updatePageSize(newPagination: NewPagination) {
  formFilter.page = 1;
  formFilter.pageSize = newPagination.rowsPerPage;
}

watch(
  () => formFilter.pageSize,
  () => {
    fetchList();
  }
);

/**
 * function ต้นหาข้อมูลของ Option
 * @param val ค่าที่ต้องการฟิลเตอร์
 * @param update  อัพเดทค่า
 * @param refData ดาต้าที่ต้องการฟิลเตอร์
 */
function filterOption(val: any, update: Function) {
  update(() => {
    positionOp.value = positionMainOp.value.filter(
      (v: any) => v.name.indexOf(val) > -1
    );
  });
}

/** ดึงข้อมูลตำแหน่ง */
function getOptions() {
  showLoader();
  http
    .get(config.API.orgSalaryPosition)
    .then((res) => {
      const dataOp = res.data.result;
      const uniqueNames = new Set();

      const filteredData = dataOp
        .filter((item: any) => {
          if (!uniqueNames.has(item.positionName)) {
            uniqueNames.add(item.positionName);
            return true;
          }
          return false;
        })
        .map((item: any) => ({
          id: item.positionName,
          name: item.positionName,
        }));

      positionMainOp.value.push(...filteredData);
      positionOp.value.push(...filteredData);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function setModel(val: string) {
  formFilter.position = val;
}

/**
 * เปิด dialog history
 * @param id
 */
function onClickHistory(id: string) {
  showLoader();
  http
    .get(config.API.kpiRoleMainList + `/history/${id}`)
    .then((res) => {
      const data = res.data.result;
      dataHistory.value = data;
      modalHistory.value = true;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการตัวชี้วัดตามตำแหน่ง
  </div>
  <q-card flat bordered class="q-pa-md">
    <div class="row q-gutter-sm no-wrap q-mb-sm">
      <q-select
        dense
        v-model="formFilter.position"
        label="ตำแหน่ง"
        outlined
        emit-value
        map-options
        fill-input
        hide-selected
        hide-bottom-space
        option-label="name"
        option-value="id"
        :options="positionOp"
        use-input
        @filter="(inputValue:any,doneFn:Function) => filterOption(inputValue, doneFn) "
        @update:model-value="(formFilter.page = 1), fetchList()"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
          </q-item>
        </template>
        <template v-if="formFilter.position !== ''" v-slot:append>
          <q-icon
            name="cancel"
            @click.stop.prevent="
              (formFilter.position = ''), (formFilter.page = 1), fetchList()
            "
            class="cursor-pointer"
          />
        </template>
      </q-select>

      <datepicker
        style="width: 150px"
        menu-class-name="modalfix"
        v-model="formFilter.year"
        :locale="'th'"
        autoApply
        year-picker
        :enableTimePicker="false"
        @update:model-value="(formFilter.page = 1), fetchList()"
      >
        <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), (formFilter.page = 1), fetchList()
                "
                class="cursor-pointer"
              />
            </template>
          </q-input>
        </template>
      </datepicker>

      <q-select
        dense
        outlined
        v-model="formFilter.round"
        :options="roundOp"
        label="รอบการประเมิน"
        option-label="name"
        option-value="id"
        emit-value
        map-options
        @update:model-value="(formFilter.page = 1), fetchList()"
        style="width: 160px"
      >
        <template v-if="formFilter.round !== ''" v-slot:append>
          <q-icon
            name="cancel"
            @click.stop.prevent="
              (formFilter.round = ''), (formFilter.page = 1), fetchList()
            "
            class="cursor-pointer"
          />
        </template>
      </q-select>

      <q-btn
        flat
        round
        dense
        icon="add"
        color="primary"
        @click="onClickAddOrView()"
      >
        <q-tooltip>เพิ่ม</q-tooltip>
      </q-btn>

      <q-space />
      <q-input
        standout
        dense
        v-model="formFilter.keyword"
        ref="filterRef"
        outlined
        debounce="300"
        placeholder="ค้นหา"
        @keyup.enter="(formFilter.page = 1), fetchList()"
      >
        <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 = ''"
          />
        </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"
        options-cover
        style="min-width: 150px"
      />
    </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"
        :rows-per-page-options="[10, 20, 50, 100]"
        @update:pagination="updatePageSize"
      >
        <template v-slot:pagination="scope">
          ทั้งหมด {{ total }} รายการ
          <q-pagination
            v-model="formFilter.page"
            active-color="primary"
            color="dark"
            :max="maxPage"
            :max-pages="5"
            size="sm"
            boundary-links
            direction-links
            @update:model-value="updatePage"
          ></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-th auto-width />
          </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">
              <div v-if="col.name === 'no'">
                {{
                  (formFilter.page - 1) * Number(pagination.rowsPerPage) +
                  props.rowIndex +
                  1
                }}
              </div>

              <div v-else class="table_ellipsis">
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
            <q-td auto-width>
              <q-btn
                flat
                round
                color="grey"
                @click.stop
                size="14px"
                icon="more_vert"
              >
                <q-menu>
                  <q-list style="min-width: 180px">
                    <q-item
                      clickable
                      v-close-popup
                      @click.stop.pervent="onClickAddOrView(true, props.row.id)"
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                        <q-icon
                          color="primary"
                          size="xs"
                          name="mdi-pencil-outline"
                        />
                      </q-item-section>
                      <q-item-section>แก้ไขข้อมูล</q-item-section>
                    </q-item>
                    <q-item
                      clickable
                      v-close-popup
                      @click="onClickHistory(props.row.id)"
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-tooltip>ประวัติการแก้ไข</q-tooltip>
                        <q-icon color="info" size="xs" name="mdi-history" />
                      </q-item-section>
                      <q-item-section>ประวัติการแก้ไข</q-item-section>
                    </q-item>
                    <q-item
                      clickable
                      v-close-popup
                      @click.stop.pervent="onClickDelete(props.row.id)"
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-tooltip>ลบข้อมูล</q-tooltip>
                        <q-icon color="red" size="xs" name="mdi-delete" />
                      </q-item-section>
                      <q-item-section>ลบข้อมูล</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogHistory v-model:modal="modalHistory" :rows="dataHistory" />
</template>

<style scoped></style>
