<script setup lang="ts">
import { ref } from "vue";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useKpiDataStore } from "@/modules/08_KPI/store";
import { useCounterMixin } from "@/stores/mixin";

import type { QTableProps } from "quasar";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const store = useKpiDataStore();
const { showLoader, hideLoader, messageError, dialogConfirm, success } =
  useCounterMixin();

const props = defineProps({
  fetchList: { type: Function, required: true },
});

const modal = defineModel<boolean>("modal", { required: true });
const rows = defineModel<any>("data", { required: true });
const numpage = defineModel<number>("numpage", { required: true });

/** table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "includingName",
    align: "left",
    label: "ตัวชี้วัด",
    sortable: true,
    field: "includingName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "target",
    align: "left",
    label: "ค่าเป้าหมาย",
    sortable: true,
    field: "target",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "point",
    align: "left",
    label: "ระดับคะแนนตามเกณฑ์การประเมิน",
    sortable: false,
    field: "point",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "weight",
    align: "left",
    label: "น้ำหนัก (ร้อยละ)",
    sortable: true,
    field: "weight",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "achievement",
    align: "left",
    label: "ผลสำเร็จของงาน",
    sortable: true,
    field: "achievement",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "evaluationResults",
    align: "left",
    label: "ผลการประเมิน",
    sortable: true,
    field: "evaluationResults",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<string[]>([
  "includingName",
  "target",
  "point",
  "weight",
  "achievement",
  "evaluationResults",
]);

function closeDialog() {
  modal.value = false;
}

function updateAchievement(index: number, data: any) {
  switch (data.point) {
    case 1:
      rows.value[index].achievement = data.achievement1;
      break;
    case 2:
      rows.value[index].achievement = data.achievement2;
      break;
    case 3:
      rows.value[index].achievement = data.achievement3;
      break;
    case 4:
      rows.value[index].achievement = data.achievement4;
      break;
    case 5:
      rows.value[index].achievement = data.achievement5;
      break;
  }
}

function onSubmit() {
  dialogConfirm($q, async () => {
    try {
      showLoader();
      store.isUpdate = true;

      const formData = rows.value.map((e: any) => ({
        id: e.id,
        point: e.point,
        summary: ((e.point / 5) * e.weight).toFixed(2),
      }));

      const url =
        numpage.value === 1
          ? config.API.kpiAchievementPoint("planned")
          : numpage.value === 2
          ? config.API.kpiAchievementPoint("role")
          : numpage.value === 3
          ? config.API.kpiAchievementPoint("special")
          : "";
      await http.post(url, formData).then((res) => {
        props.fetchList();
      });
      success($q, "บันทึกข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
      closeDialog();
    }
  });
}
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 1200px; max-width: 80vw">
      <DialogHeader :tittle="'ประเมินผลสัมฤทธิ์ของงาน'" :close="closeDialog" />

      <q-separator />
      <q-card-section style="height: 80vh">
        <div class="col-12 q-pa-sm">
          <q-table
            ref="table"
            :columns="columns"
            :rows="rows"
            row-key="id"
            flat
            bordered
            dense
            hide-pagination
            class="custom-table2"
            :visible-columns="visibleColumns"
            :rows-per-page-options="[20]"
            no-data-label="ไม่มีข้อมูล"
          >
            <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.id">
                  <div v-if="col.name === 'point'">
                    <q-btn-group outline>
                      <q-btn
                        v-for="i in 5"
                        :class="props.row.point == i && 'active'"
                        outline
                        color="grey-6"
                        :label="i"
                        @click="
                          () => {
                            updateAchievement(props.rowIndex, props.row);
                            props.row.point = i;
                          }
                        "
                      >
                        <q-tooltip>
                          <div class="text-body2">
                            <span v-html="props.row[`achievement${i}`]"></span>
                          </div>
                        </q-tooltip>
                      </q-btn>
                    </q-btn-group>
                  </div>
                  <div v-else-if="col.name === 'achievement'">
                    {{ props.row.point ? `ระดับ ${props.row.point}` : "" }}
                  </div>
                  <div v-else-if="col.name === 'evaluationResults'">
                    {{
                      parseFloat(
                        Number(
                          (props.row.point / 5) * props.row.weight
                        ).toFixed(2)
                      )
                    }}
                  </div>
                  <div v-else>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </q-table>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn label="บันทึก" color="secondary" @click="onSubmit"
          ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.custom-table2 {
  max-height: 64vh;

  .q-table tr:nth-child(odd) td {
    background: white;
  }

  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
  }

  .q-table td:nth-of-type(2) {
    z-index: 3 !important;
  }

  .q-table th:nth-of-type(2),
  .q-table td:nth-of-type(2) {
    position: sticky;
    left: 0;
    z-index: 1;
  }

  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}
.q-btn-group--outline > .q-btn-item:not(:last-child):before {
  border-right: 1px solid #c4c4c4;
}
.q-btn-group--outline > .q-btn-item.active {
  color: #2196f3 !important;
  background-color: #cde6fb !important;
}
.q-btn-group--outline > .q-btn-item + .q-btn-item.active:before {
  border-left: 1px solid #2196f3 !important;
  background-color: #cde6fb;
}
.q-btn-group--outline > .q-btn-item.active:not(:last-child):before {
  border: 1px solid #2196f3;
  background-color: #cde6fb;
}
</style>
