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

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

import type { ListCriteria } from "@/modules/08_KPI/interface/request/index";

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

const dataListCriteria = defineModel<ListCriteria[]>("dataListCriteria", {
  required: true,
});

const sortedDataListCriteria = computed(() => {
  return dataListCriteria.value.sort((a, b) => a.level - b.level);
});

const props = defineProps({
  getData: Function,
  default: () => console.log("not function"),
});
const { dialogConfirm, messageError, dialogMessageNotify } = useCounterMixin();

const $q = useQuasar();
const store = useKpiDataStore();
const modal = defineModel<boolean>("modal", { required: true });
const rows = defineModel<any>("data", { required: true });
const type = defineModel<string>("type", { required: true });

const visibleColumns = ref<string[]>([
  "name",
  "level",
  "point",
  "weight",
  "summary",
]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "รายการสมรรถนะ",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "level",
    align: "left",
    label: "ระดับที่คาดหวัง",
    sortable: true,
    field: "level",
    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: "summary",
    align: "left",
    label: "ผลการประเมิน",
    sortable: true,
    field: "summary",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

function closeDialog() {
  modal.value = false;
  props.getData?.(type.value);
}

function onSubmit() {
  const main = rows.value;
  const checkPoint = main.some((item: any) => item.point === 0);

  if (checkPoint) {
    dialogMessageNotify($q, "กรุณาเลือกระดับคะแนนตามเกณฑ์การประเมิน");
  } else {
    dialogConfirm($q, () => {
      store.isUpdate = true;
      const data = rows.value;
      const body = data.map((i: any) => ({
        id: i.id,
        point: i.point,
        summary: i.point * 20,
      }));
      http
        .post(config.API.kpiUserCapacity + `/point`, body)
        .then((res) => {
          closeDialog();
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {});
    });
  }
}
</script>

<template>
  <q-dialog v-model="modal" persistent style="width: 60vw">
    <q-card style="width: 1200px; max-width: 80vw">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader :tittle="'ประเมิน'" :close="closeDialog" />
        <q-separator />
        <q-card-section class="q-pt-none" style="min-height: 70vh">
          <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'">
                      <div>
                        <q-btn-group outline>
                          <q-btn
                            v-for="(i, index) in sortedDataListCriteria"
                            :key="index"
                            :class="props.row.point == i.level && 'active'"
                            outline
                            color="grey-6"
                            :label="i.level"
                            @click="props.row.point = i.level"
                          >
                            <q-tooltip>
                              <div class="text-body2">
                                <span v-html="i.description"></span>
                              </div>
                            </q-tooltip>
                          </q-btn>
                        </q-btn-group>
                      </div>
                    </div>
                    <div v-else-if="col.name === 'summary'">
                      {{ props.row.point !== 0 ? props.row.point * 20 : "-" }}
                    </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" class="q-pa-md">
          <q-btn unelevated label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </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>
