<script setup lang="ts">
import { onMounted, ref } from "vue";
import Dialog from "@/modules/08_KPI/components/Tab/Dialog/04_FormCompetency.vue";
import DialogEvaluate from "@/modules/08_KPI/components/Tab/DialogEvaluate/02_Competenct.vue";

import { useQuasar, type QTableProps } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useKpiDataStore } from "@/modules/08_KPI/store";
import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";

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

const modalEvaluate = ref<boolean>(false);
const point = ref<number>(0);
const store = useKpiDataStore();

const route = useRoute();
const id = ref<string>(route.params.id as string);
const idCapacity = ref<string | null>(null);

const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
  dialogRemove,
  success,
} = mixin;

const type = defineModel<string>("type", { required: true });
const name = defineModel<any>("name", { required: true });

const filterKeyword = ref<string>("");
const modal = ref<boolean>(false);

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: true,
    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 onAdd() {
  modal.value = true;
}

const rows = ref<FormCapacityList[]>([]);

function getData() {
  showLoader();
  http
    .get(config.API.kpiUserCapacity + `?id=${id.value}&type=${type.value}`)
    .then((res) => {
      const data = res.data.result.data;
      rows.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function onEdit(data: FormCapacityList) {
  modal.value = true;
  idCapacity.value = data.id;
}

function onDelete(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.kpiUserCapacity + `/${id}`)
      .then((res) => {
        success($q, "ลบข้อมูลสำเร็จ");
        getData();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function onEvaluate() {
  modalEvaluate.value = true;
}

onMounted(() => {
  getData();
});
</script>

<template>
  <q-card bordered style="border-radius: 5px" class="no-shadow">
    <q-card-section class="bg-grey-2 q-py-sm">
      <div class="row items-center">
        <div class="col">
          <span class="text-weight-medium">{{ name }}</span>
          <q-btn
            class="q-ml-xs"
            flat
            round
            icon="mdi-plus"
            color="primary"
            size="12px"
            dense
            @click="onAdd"
          >
            <q-tooltip>เพิ่มข้อมูล</q-tooltip>
          </q-btn>
        </div>

        <q-space />
        <q-btn
          flat
          round
          icon="mdi-clipboard-check-outline"
          color="blue-5"
          size="12px"
          dense
          @click="onEvaluate"
        >
          <q-tooltip>ประเมิน</q-tooltip>
        </q-btn>
      </div>
    </q-card-section>
    <q-card-section class="q-pa-sm">
      <q-table
        ref="table"
        :columns="columns"
        :rows="rows"
        :filter="filterKeyword"
        row-key="id"
        flat
        bordered
        :paging="true"
        dense
        hide-pagination
        class="custom-table2"
        :visible-columns="visibleColumns"
        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-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.id">
              <div v-if="col.name == 'createDate'">
                {{ col.value ? date2Thai(col.value) : "-" }}
              </div>
              <div v-else-if="col.name == 'point'">
                <div v-if="type == 'HEAD' || type == 'GROUP'">
                  <q-rating
                    v-model="props.row.point"
                    max="5"
                    size="sm"
                    color="grey"
                    :color-selected="store.ratingColors"
                    label="ระดับการประเมินพฤติกรรม"
                    disable
                  >
                    <template v-slot:tip-1>
                      <q-tooltip>ต่ำกว่าระดับที่คาดหวังมาก (1)</q-tooltip>
                    </template>
                    <template v-slot:tip-2>
                      <q-tooltip>ต่ำกว่าระดับที่คาดหวัง (2)</q-tooltip>
                    </template>
                    <template v-slot:tip-3>
                      <q-tooltip>อยู่ในระดับที่คาดหวัง (3)</q-tooltip>
                    </template>
                    <template v-slot:tip-4>
                      <q-tooltip>อยู่ในระดับสูงกว่าที่คาดหวัง (4)</q-tooltip>
                    </template>
                    <template v-slot:tip-5>
                      <q-tooltip>เป็นแบบอย่างที่ดีให้กับผู้อื่น (5)</q-tooltip>
                    </template>
                  </q-rating>
                </div>
                <div v-else>
                  รอ ทำ select
                </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-td auto-width>
              <q-btn
                flat
                round
                icon="edit"
                color="edit"
                @click.stop.pervent="onEdit(props.row)"
              >
                <q-tooltip>แก้ไข </q-tooltip>
              </q-btn>
              <q-btn
                flat
                round
                icon="delete"
                color="red"
                @click.stop.pervent="onDelete(props.row.id)"
              >
                <q-tooltip>ลบข้อมูล </q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </q-card-section>
  </q-card>

  <Dialog
    v-model:modal="modal"
    v-model:competency-type="type"
    v-model:id="idCapacity"
    :get-data-list="getData"
  />

  <DialogEvaluate
    v-model:modal="modalEvaluate"
    v-model:data="rows"
    v-model:type="type"
    :get-data="getData"

  />
</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;
  }
}
</style>
