div
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import { useKPIDataStore } from "@/modules/14_KPI/store/KPIStore";

/**use*/
const $q = useQuasar();
const mixin = useCounterMixin();
const { dialogConfirm, showLoader, hideLoader, success, messageError } = mixin;
const router = useRouter();
const route = useRoute();
const store = useKPIDataStore();

const competencyId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);

const formData = reactive({
  competencyType: "",
  competencyName: "",
  definition: "",
  levels: [
    {
      level: "1",
      description: "",
    },
  ],
});

function fetchDetail() {
  showLoader();
  http
    .get(config.API.kpiCapacity + `/${competencyId.value}`)
    .then((res) => {
      const data = res.data.result;
      formData.competencyType = data.type;
      formData.competencyName = data.name;
      formData.definition = data.description;
      formData.levels = data.capacityDetails;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onClickAddLevels() {
  const levelName = formData.levels.length + 1;
  const data = {
    level:
      store.competencyType === "HEAD" || store.competencyType === "GROUP"
        ? (formData.levels[formData.levels.length].level = levelName.toString())
        : "",
    description: "",
  };
  formData.levels.push(data);
}

function onSubmit() {
  dialogConfirm($q, async () => {
    const formBody = {
      type: store.competencyType,
      name: formData.competencyName,
      description: formData.definition,
      capacityDetails: formData.levels,
    };
    try {
      const url = competencyId.value
        ? config.API.kpiCapacity + `/${competencyId.value}`
        : config.API.kpiCapacity;
      const method = competencyId.value ? "put" : "post";
      await http[method](url, formBody);
      if (!competencyId.value) {
        router.push(`/KPI-competency`);
      } else {
        fetchDetail();
      }
      success($q, "บันทึกข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

function onDeleteLevels(index: number) {
  formData.levels.splice(index, 1);
}
onMounted(() => {
  if (competencyId.value) {
    fetchDetail();
  }
});
</script>

<template>
  <q-form greedy @submit.prevent @validation-success="onSubmit" class="col-12">
    <div class="row">
      <div class="col-12">
        <q-input
          v-model="formData.competencyName"
          dense
          outlined
          label="ชื่อสมรรถนะ"
          :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อสมรรถนะ'}`,]"
          hide-bottom-space
        />
      </div>
      <q-card-section class="col-12 q-px-none">
        <div>
          <q-field
            class="q_field_p_none"
            ref="fieldRef"
            v-model="formData.definition"
            label-slot
            borderless
            :rules="[(val) => !!val || 'กรุณากรอกคำจำกัดความสมรรถนะ']"
            hide-bottom-space
          >
            <template #control>
              <q-editor
                class="full-width"
                v-model="formData.definition"
                :dense="$q.screen.lt.md"
                min-height="7rem"
                placeholder="คำจำกัดความสมรรถนะ"
                :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>
        </div>
      </q-card-section>
      <div class="col-12">
        <q-card flat bordered>
          <q-card-section class="bg-grey-4">
            <div
              class="row items-center text-dark text-body2 text-weight-medium"
            >
              <div class="col-3">
                <div class="row items-center">
                  <div class="col-1">
                    <q-btn
                      dense
                      flat
                      round
                      color="primary"
                      icon="add"
                      @click="onClickAddLevels"
                    >
                      <q-tooltip>เพิ่ม</q-tooltip></q-btn
                    >
                  </div>
                  <div class="col-11 text-center">
                    <span>ระดับสมรรถนะ</span>
                  </div>
                </div>
              </div>
              <div class="col-4">
                <span>พฤติกรรมที่คาดหวัง/พฤติกรรมย่อย</span>
              </div>
            </div>
          </q-card-section>
          <q-card-section>
            <div
              class="row q-pa-sm"
              v-for="(items, index) in formData.levels"
              key="index"
            >
              <div class="col-3 align-center q-pr-lg">
                <q-input
                  :readonly="
                    store.competencyType === 'HEAD' ||
                    store.competencyType === 'GROUP'
                  "
                  v-model="formData.levels[index].level"
                  dense
                  outlined
                  :rules="[(val:string) => !!val || `${'กรุณากรอกระดับสมรรถนะ'}`,]"
                  hide-bottom-space
                />
              </div>
              <div class="col-9">
                <div class="row q-col-gutter-md">
                  <div class="col-11">
                    <q-field
                      class="q_field_p_none"
                      ref="fieldRef"
                      v-model="formData.levels[index].description"
                      label-slot
                      borderless
                      :rules="[
                        (val) =>
                          !!val || 'กรุณากรอกพฤติกรรมที่คาดหวัง/พฤติกรรมย่อย',
                      ]"
                      hide-bottom-space
                    >
                      <template #control>
                        <q-editor
                          class="full-width"
                          v-model="formData.levels[index].description"
                          :dense="$q.screen.lt.md"
                          min-height="5rem"
                          :toolbar="[
                            [
                              'bold',
                              'italic',
                              'strike',
                              'underline',
                              'subscript',
                              'superscript',
                            ],

                            ['unordered', 'ordered'],
                          ]"
                        />
                      </template>
                    </q-field>
                  </div>
                  <div class="col-1 text-center">
                    <q-btn
                      dense
                      flat
                      round
                      color="red"
                      icon="delete"
                      @click="onDeleteLevels(index)"
                      v-if="
                        (store.competencyType === 'HEAD' && index > 4) ||
                        (store.competencyType === 'GROUP' && index > 4) ||
                        ((store.competencyType === 'EXECUTIVE' ||
                          store.competencyType === 'DIRECTOR' ||
                          store.competencyType === 'INSPECTOR') &&
                          index > 0)
                      "
                    >
                      <q-tooltip>ลบ</q-tooltip></q-btn
                    >
                  </div>
                </div>
              </div>
            </div>
          </q-card-section>
        </q-card>
      </div>
      <div class="col-12 q-my-sm"><q-separator /></div>
      <div class="col-12 row justify-end">
        <q-btn
          dense
          unelevated
          label="บันทึก"
          color="public"
          class="q-px-md"
          type="submit"
        >
          <q-tooltip>บันทึกข้อมูล</q-tooltip>
        </q-btn>
      </div>
    </div>
  </q-form>
</template>

<style scoped></style>
