<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useCounterMixin } from "@/stores/mixin";

import http from "@/plugins/http";
import config from "@/app.config";
import { useQuasar } from "quasar";

import { checkPermission } from "@/utils/permissions";
import { useRoute } from "vue-router";

import type { DataKPIEvaluation } from "@/modules/01_masterdata/interface/response/Main";

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

const dataLevel = ref<DataKPIEvaluation[]>([]);
const fieldLabels = {
  score5: "5",
  score4: "4",
  score3: "3",
  score2: "2",
  score1: "1",
};

/** ฟังก์ชันดึงข้อมูลเกณฑ์การประเมิน */
async function getData() {
  showLoader();
  await http
    .get(config.API.kpiEvaluation + `/edit`)
    .then((res) => {
      dataLevel.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ฟังก์ชันบันทึกข้อมูลเกณฑ์การประเมิน */
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const body = {
      formScore: dataLevel.value.map((item: DataKPIEvaluation) => {
        const { level, ...rest } = item;
        return rest;
      }),
    };

    await http
      .put(config.API.kpiEvaluation, body.formScore)
      .then(async () => {
        await getData();
        success($q, "บันทึกสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

onMounted(() => {
  if (checkPermission(route)?.attrIsList) getData();
});
</script>

<template>
  <q-card flat bordered>
    <q-form greedy @submit.prevent @validation-success="onSubmit">
      <q-card-section>
        <q-card-section class="bg-grey-3">
          <div class="row text-dark text-body2 text-weight-medium">
            <div class="text-center col-8">เกณฑ์การประเมิน</div>
            <div class="text-center col-4">ระดับคะแนน</div>
          </div>
        </q-card-section>
        <q-card-section class="q-pa-none">
          <div v-for="(field, index) in dataLevel" :key="field.id">
            <div class="row q-pa-sm">
              <div class="col-8 text-left">
                <q-field
                  class="q_field_p_none"
                  ref="fieldRef"
                  v-model="field.description"
                  label-slot
                  borderless
                  :rules="[(val:string) => !!val || 'กรุณากรอกมาตรฐานพฤติกรรม']"
                  hide-bottom-space
                >
                  <template #control>
                    <q-editor
                      :readonly="checkPermission($route)?.attrIsUpdate == false"
                      class="full-width"
                      v-model="field.description"
                      :dense="$q.screen.lt.md"
                      min-height="5rem"
                      :toolbar="[
                        [
                          'bold',
                          'italic',
                          'strike',
                          'underline',
                          'subscript',
                          'superscript',
                        ],

                        ['unordered', 'ordered'],
                      ]"
                      :fonts="{
                        arial: 'Arial',
                        arial_black: 'Arial Black',
                        comic_sans: 'Comic Sans MS',
                        courier_new: 'Courier New',
                        impact: 'Impact',
                        lucida_grande: 'Lucida Grande',
                        times_new_roman: 'Times New Roman',
                        verdana: 'Verdana',
                      }"
                    />
                  </template>
                </q-field>
                <!-- <q-input
                  v-model="formScore[field]"
                  dense
                  outlined
                  class="inputgreen"
                  label="กรอกข้อความเพื่อไว้ใช้อ้างอิงเท่านั้น"
                  :rules="[(val:string) => !!val || `${'กรุณากรอกข้อความเพื่อไว้ใช้อ้างอิงเท่านั้น'}`,]"
                  hide-bottom-space
                /> -->
              </div>
              <div
                class="col-4 text-center text-body1 text-weight-bold self-center"
              >
                {{ field.level }}
              </div>
            </div>
            <div
              class="col-12"
              v-if="index !== Object.keys(fieldLabels).length - 1"
            >
              <q-separator />
            </div>
          </div>
        </q-card-section>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right">
        <q-btn
          v-if="
            checkPermission($route)?.attrIsList &&
            checkPermission($route)?.attrIsUpdate
          "
          label="บันทึก"
          color="secondary"
          type="submit"
        >
          <q-tooltip>บันทึกข้อมูล</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-form>
  </q-card>
</template>
