<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

import DialogHeader from "@/components/DialogHeader.vue";

import type {
  FormDataNewStructure,
  FormNewStructureRef,
  DataOption,
} from "@/modules/02_organizationalNew/interface/index/Main";

import { useCounterMixin } from "@/stores/mixin";
import { useOrganizational } from "@/modules/02_organizationalNew/store/organizational";

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

const modal = defineModel<boolean>("newStructure", { required: true });
const status = defineModel<boolean>("status", { required: true });

const typeOp = ref<DataOption[]>([
  {
    id: "NEW",
    name: "สร้างใหม่",
  },
  {
    id: "ORG",
    name: "ทำสำเนาเฉพาะโครงสร้าง",
  },
  {
    id: "ORG_POSITION",
    name: "ทำสำเนาโครงสร้างและตำแหน่ง",
  },
  {
    id: "ORG_POSITION_PERSON",
    name: "ทำสำเนาโครงสร้าง ตำแหน่ง และคนครอง",
  },
]);

const orgRevisionNameRef = ref<Object | null>(null);
const typeRef = ref<Object | null>(null);

const formData = reactive<FormDataNewStructure>({
  orgRevisionName: "",
  type: "",
});

/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const objectRef: FormNewStructureRef = {
  orgRevisionName: orgRevisionNameRef,
  type: typeRef,
};

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
function validateForm() {
  const hasError = [];
  for (const key in objectRef) {
    if (Object.prototype.hasOwnProperty.call(objectRef, key)) {
      const property = objectRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    onSubmit();
  } else {
  }
}

/** ฟังชั่น บันทึก */
function onSubmit() {
  dialogConfirm($q, () => {
    // http
    //   .post(config.API.createOrganization, formData)
    //   .then(() => {
    status.value = true;
    store.typeOrganizational = "draft";
    success($q, "บันทึกข้อมูลสำเร็จ");
    // })
    // .catch((err) => {
    //   messageError($q, err);
    // })
    // .finally(() => {});

    console.log(formData);
  });
  modal.value = false;
}

function close() {
  modal.value = false;
}

watch(
  () => modal.value,
  () => {
    modal.value && !status.value && (formData.type = "NEW");
  }
);
</script>
<template>
  <template>
    <q-dialog v-model="modal" persistent>
      <q-card style="min-width: 50vw">
        <form @submit.prevent="validateForm">
          <DialogHeader :tittle="`เพิ่มโครงสร้าง`" :close="close" />
          <q-separator />

          <q-card-section>
            <div class="row q-col-gutter-sm">
              <div class="col-6">
                <q-input
                  v-model="formData.orgRevisionName"
                  ref="orgRevisionNameRef"
                  dense
                  outlined
                  for="#orgRevisionName"
                  label="ชื่อโครงสร้าง"
                  hide-bottom-space
                  :rules="[(val) => !!val || `${'กรุณากรอกชื่อโครงสร้าง'}`]"
                />
              </div>
              <div class="col-6">
                <q-select
                  for="#type"
                  ref="typeRef"
                  :readonly="!status"
                  dense
                  hide-bottom-space
                  outlined
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  v-model="formData.type"
                  :options="typeOp"
                  label="ประเภทการโคลน"
                  :rules="[(val) => !!val || `${'กรุณาเลือกประเภทการโคลน'}`]"
                  lazy-rules
                />
              </div>
            </div>
          </q-card-section>
          <q-separator />
          <q-card-actions align="right" class="bg-white text-teal">
            <q-btn type="submit" :label="`บันทึก`" color="public" />
          </q-card-actions>
        </form>
      </q-card>
    </q-dialog>
  </template>
</template>
