<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/01_masterdata/stores/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 checkRoute = ref<boolean>(route.name == "KPICompetencyDetailByid");
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 + `/edit/${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.competencyTypeVal === "HEAD" ||
        store.competencyTypeVal === "GROUP") &&
      levelName <= 6
        ? levelName.toString()
        : "",
    description: "",
  };
  levelName <= 6 && formData.levels.push(data);
}

/** บันทึกข้อมูล */
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const formBody = {
      type: store.competencyTypeVal,
      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(`/masterdata/competency`);
      } else {
        fetchDetail();
      }
      success($q, "บันทึกข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

/** ลบ ระดับ สมรรถนะ*/
function onDeleteLevels(index: number) {
  formData.levels.splice(index, 1);
}

/** ทำงานเมื่อ โหลด component */
onMounted(() => {
  if (competencyId.value) {
    fetchDetail();
  }
});
</script>

<template>
  <q-form greedy @submit.prevent @validation-success="onSubmit" class="col-12">
    <q-card-section class="q-pt-none">
      <div class="row q-col-gutter-sm">
        <div class="col-12">
          <q-input
            :readonly="checkRoute"
            v-model="formData.competencyName"
            dense
            outlined
            label="ชื่อสมรรถนะ"
            :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อสมรรถนะ'}`,]"
            hide-bottom-space
            class="inputgreen"
          />
        </div>

        <div class="col-12">
          <q-field
            class="q_field_p_none"
            ref="fieldRef"
            v-model="formData.definition"
            label-slot
            borderless
            :rules="[(val:string) => !!val || 'กรุณากรอกคำจำกัดความสมรรถนะ']"
            hide-bottom-space
          >
            <template #control>
              <q-editor
                :readonly="checkRoute"
                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>

        <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
                        v-if="!checkRoute"
                        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.competencyTypeVal === 'HEAD' ||
                      store.competencyTypeVal === '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:string) =>
                            !!val || 'กรุณากรอกพฤติกรรมที่คาดหวัง/พฤติกรรมย่อย',
                        ]"
                        hide-bottom-space
                      >
                        <template #control>
                          <q-editor
                            :readonly="checkRoute"
                            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
                        v-if="
                          ((!checkRoute &&
                            store.competencyTypeVal === 'HEAD' &&
                            index > 4) ||
                            (store.competencyTypeVal === 'GROUP' &&
                              index > 4) ||
                            ((store.competencyTypeVal === 'EXECUTIVE' ||
                              store.competencyTypeVal === 'DIRECTOR' ||
                              store.competencyTypeVal === 'INSPECTOR') &&
                              index > 0)) &&
                          !checkRoute
                        "
                        dense
                        flat
                        round
                        color="red"
                        icon="delete"
                        @click="onDeleteLevels(index)"
                      >
                        <q-tooltip>ลบ</q-tooltip></q-btn
                      >
                    </div>
                  </div>
                </div>
              </div>
            </q-card-section>
          </q-card>
        </div>
      </div>
    </q-card-section>

    <div class="col-12"><q-separator /></div>

    <q-card-actions align="right">
      <q-btn
        v-if="!checkRoute"
        label="บันทึก"
        color="public"
        class="q-px-md"
        type="submit"
      >
        <q-tooltip>บันทึกข้อมูล</q-tooltip>
      </q-btn>
    </q-card-actions>
  </q-form>
</template>

<style scoped></style>
