<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useKPIDataStore } from "@/modules/01_masterdata/stores/KPIStore";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";

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

const router = useRouter;
const store = useKPIDataStore();
const formData = reactive({
  competencyType: "",
  competencyName: "",
  definition: "",
  level: ["", "", "", "", "", ""],
  form: [
    {
      posType: "",
      posLevel: "",
      description: "",
      description2: "",
    },
  ],
  evaluation: "",
});

const dataLevel = ref<any>([]);
const typeOp = ref<any>([]);
const levelOp = ref<any>([]);
const typeOpsMain = ref<any>([]);
const levelOpsMain = ref<any>([]);

function ocClickAdd() {
  if (formData.form.length !== 6) {
    const data = {
      posType: "",
      posLevel: "",
      description: "",
      description2: "",
    };
    formData.form.push(data);
  }
}

/** function เรียกรายการประเภทตำแหน่ง */
function fetchType() {
  showLoader();
  http
    .get(config.API.orgPosType)
    .then((res) => {
      const data = res.data.result;
      dataLevel.value = data;
      typeOpsMain.value = data.map((e: any) => ({
        id: e.id,
        name: e.posTypeName,
      }));
      typeOp.value = typeOpsMain.value;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function updateSelectType(val: string, index: number) {
  const listLevel = dataLevel.value.find((e: any) => e.id === val);
  levelOpsMain.value = listLevel.posLevels.map((e: any) => ({
    id: e.id,
    name: e.posLevelName,
  }));
  levelOp.value = levelOpsMain.value;
  formData.form[index].posLevel = "";
}

function onSubmit() {
  dialogConfirm($q, () => {
    const body = {
      competencyType: store.competencyTypeVal,
      competencyName: formData.competencyName,
      definition: formData.definition,
      postype: formData.form,
      evaluation: formData.evaluation,
    };
  });
}

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

<template>
  <q-form greedy @submit.prevent @validation-success="onSubmit" class="col-12">
    <div class="row q-col-gutter-sm">
      <div class="col-12">
        <q-input
          v-model="formData.competencyName"
          dense
          outlined
          label="ชื่อสมรรถนะ"
          :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อสมรรถนะ'}`,]"
          hide-bottom-space
        />
      </div>
      <div class="col-12">
        <q-input
          v-model="formData.definition"
          label="คำจำกัดความ"
          dense
          type="textarea"
          outlined
          :rules="[(val:string) => !!val || `${'กรุณากรอกคำจำกัดความ'}`,]"
          hide-bottom-space
        />
      </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
                      dense
                      flat
                      round
                      color="primary"
                      icon="add"
                      @click="ocClickAdd"
                    >
                      <q-tooltip>เพิ่ม</q-tooltip></q-btn
                    >
                  </div>
                  <div class="col-11 text-center">
                    <span>ประเภทตำแหน่ง</span>
                  </div>
                </div>
              </div>
              <div class="col-3 text-center">
                <span>ระดับ</span>
              </div>
              <div class="col-6">
                <span>มาตรฐานพฤติกรรม</span>
              </div>
            </div>
          </q-card-section>
          <q-card-section>
            <div
              class="row q-pa-sm q-col-gutter-sm"
              v-for="(items, index) in formData.form"
              key="index"
            >
              <div class="col-3 text-center">
                <q-select
                  v-model="formData.form[index].posType"
                  outlined
                  label="ประเภทตำแหน่ง"
                  dense
                  option-label="name"
                  option-value="id"
                  :options="typeOp"
                  emit-value
                  map-options
                  :rules="[(val:string) => !!val || `${'กรุณาเลือกประเภทตำแหน่ง'}`,]"
                  hide-bottom-space
                  @update:model-value="
                    updateSelectType(formData.form[index].posType, index)
                  "
                />
              </div>
              <div class="col-3 text-center">
                <q-select
                  v-model="formData.form[index].posLevel"
                  outlined
                  label="ระดับตำแหน่ง"
                  dense
                  option-label="name"
                  option-value="id"
                  :options="levelOp"
                  emit-value
                  map-options
                  :rules="[(val:string) => !!val || `${'กรุณาเลือกระดับตำแหน่ง'}`,]"
                  hide-bottom-space
                />
              </div>
              <div class="col-6">
                <q-field
                  class="q_field_p_none"
                  ref="fieldRef"
                  v-model="formData.form[index].description"
                  label-slot
                  borderless
                  :rules="[(val:string) => !!val || 'กรุณากรอกมาตรฐานพฤติกรรม']"
                  hide-bottom-space
                >
                  <template #control>
                    <q-editor
                      class="full-width"
                      v-model="formData.form[index].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-field
                  class="q_field_p_none"
                  ref="fieldRef"
                  v-model="formData.form[index].description2"
                  label-slot
                  borderless
                  :rules="[(val:string) => !!val || 'กรุณากรอกมาตรฐานพฤติกรรม']"
                  hide-bottom-space
                >
                  <template #control>
                    <q-editor
                      class="full-width"
                      v-model="formData.form[index].description2"
                      :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>
              </div>
              <div class="col-12"><q-separator /></div>
            </div>
          </q-card-section>
        </q-card>
      </div>
      <div class="col-12">
        <q-input
          v-model="formData.evaluation"
          label="กำหนดเกณฑ์การประเมิน"
          dense
          type="textarea"
          outlined
        />
      </div>
      <div class="col-12"><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>
