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

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

import type { FormListMainByRole } from "@/modules/01_masterdata/interface/request/Main";
import type {
  DataOption,
  KpiRoleData,
  IndicatorType,
  IndicatorTotal,
} from "@/modules/01_masterdata/interface/index/Main";
import type { DataKPIPosition } from "@/modules/01_masterdata/interface/response/Main";

import DialogHistory from "@/modules/01_masterdata/components/Indicators/DialogHistory.vue";
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
);

/** use*/
const dataHistory = ref<KpiRoleData[]>([]);
const modalHistory = ref<boolean>(false);

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

/** หัวตาราง */
const rows = ref<IndicatorType[]>([]);
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>({
  position: "",
  round: "",
  keyword: "",
  year: calculateFiscalYear(new Date()),
});

const indicatorTotal = ref<IndicatorTotal[]>([
  {
    value: "kpiPlan",
    label: "ตัวชี้วัดตามแผน",
    color: "edit",
  },
  {
    value: "kpiRole",
    label: "ตัวชี้วัดตามตำแหน่ง",
    color: "primary",
  },
  {
    value: "kpiSpecial",
    label: "ตัวชี้วัดงานอื่นๆ ที่ได้รับมอบหมาย",
    color: "blue",
  },
  {
    value: "total",
    label: "ทั้งหมด",
    color: "red",
  },
]);

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

async function fetchList() {
  showLoader();
  await http
    .post(config.API.kpiRoleMainList + `/search-edit`, {
      keyword: formFilter.keyword.trim(),
      position: formFilter.position,
      period: formFilter.round,
      node: 0,
      nodeId: "",
      year: formFilter.year?.toString(),
      ...params.value,
    })
    .then(async (res) => {
      const result = await res.data.result;
      pagination.value.rowsNumber = result.total;
      rows.value = result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

function onClickView(id: string = "") {
  router.push(`/masterdata/indicator-role/view/${id}`);
}

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

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

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

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

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

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

async function getTotal() {
  await http
    .post(config.API.indicatorSummary)
    .then(async (res) => {
      const data = await res.data.result;
      indicatorTotal.value = indicatorTotal.value.map((indicator) => {
        return {
          ...indicator,
          total: data[indicator.value],
        };
      });
    })
    .catch((e) => {
      messageError($q, e);
    });
}

onMounted(async () => {
  showLoader();
  try {
    await Promise.all([getTotal(), getOptions(), fetchList()]);
  } finally {
    hideLoader();
  }
});
</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-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="(pagination.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 = ''), (pagination.page = 1), fetchList()
            "
            class="cursor-pointer"
          />
        </template>
      </q-select>

      <datepicker
        style="width: 150px"
        v-model="formFilter.year"
        :locale="'th'"
        autoApply
        year-picker
        :enableTimePicker="false"
        @update:model-value="(pagination.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), (pagination.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="(pagination.page = 1), fetchList()"
        style="width: 160px"
      >
        <template v-if="formFilter.round !== ''" v-slot:append>
          <q-icon
            name="cancel"
            @click.stop.prevent="
              (formFilter.round = ''), (pagination.page = 1), fetchList()
            "
            class="cursor-pointer"
          />
        </template>
      </q-select>

      <q-btn
        v-if="checkPermission($route)?.attrIsCreate"
        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
        placeholder="ค้นหา"
        @keyup.enter="(pagination.page = 1), fetchList()"
      >
        <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>

    <div class="col-12">
      <p-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]"
        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 ||
                  checkPermission($route)?.attrIsUpdate ||
                  checkPermission($route)?.attrIsDelete
                "
                flat
                dense
                color="secondary"
                icon="mdi-dots-horizontal-circle-outline"
                round
              >
                <q-menu>
                  <q-list dense style="min-width: 180px">
                    <q-item
                      v-if="checkPermission($route)?.attrIsGet"
                      clickable
                      v-close-popup
                      @click="onClickHistory(props.row.id)"
                    >
                      <q-item-section style="min-width: 0px" avatar>
                        <q-tooltip>ประวัติการแก้ไข</q-tooltip>
                        <q-icon
                          color="deep-purple"
                          flat
                          dense
                          round
                          name="mdi-history"
                          size="xs"
                        />
                      </q-item-section>
                      <q-item-section>ประวัติการแก้ไข</q-item-section>
                    </q-item>
                    <q-item
                      v-if="checkPermission($route)?.attrIsGet"
                      clickable
                      v-close-popup
                      @click="onClickView(props.row.id)"
                    >
                      <q-item-section style="min-width: 0px" avatar>
                        <q-tooltip>รายละเอียด</q-tooltip>
                        <q-icon
                          flat
                          dense
                          round
                          color="info"
                          name="mdi-eye"
                          size="xs"
                        />
                      </q-item-section>
                      <q-item-section>รายละเอียด</q-item-section>
                    </q-item>
                    <q-item
                      v-if="
                        checkPermission($route)?.attrIsGet &&
                        checkPermission($route)?.attrIsUpdate
                      "
                      clickable
                      v-close-popup
                      @click="onClickAddOrView(true, props.row.id)"
                    >
                      <q-item-section style="min-width: 0px" avatar>
                        <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                        <q-icon
                          flat
                          dense
                          round
                          color="primary"
                          name="edit"
                          size="xs"
                        />
                      </q-item-section>
                      <q-item-section>แก้ไขข้อมูล</q-item-section>
                    </q-item>
                    <q-item
                      v-if="checkPermission($route)?.attrIsDelete"
                      clickable
                      v-close-popup
                      @click.stop.prevent="onClickDelete(props.row.id)"
                    >
                      <q-item-section style="min-width: 0px" avatar>
                        <q-tooltip>ลบข้อมูล</q-tooltip>
                        <q-icon
                          color="red"
                          flat
                          round
                          name="mdi-delete"
                          size="xs"
                        />
                      </q-item-section>
                      <q-item-section>ลบข้อมูล</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </q-btn>
            </q-td>
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </p-table>
    </div>
  </q-card>

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

<style scoped></style>
