<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,
  HistoryType,
} 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 type = defineModel<string>("type", { default: "NEW" });

const props = defineProps({
  fetchActive: {
    type: Function,
    require: true,
  },
});

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

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

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

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

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
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, () => {
    showLoader();
    http
      .post(config.API.createOrganization, formData)
      .then(() => {
        // status.value = true;
        // store.typeOrganizational = "draft";
        success($q, "บันทึกข้อมูลสำเร็จ");
        props.fetchActive?.();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(async () => {
        modal.value = await false;
        await close();
        await hideLoader();
      });
  });
}

function close() {
  modal.value = false;
  formData.orgRevisionId = "";
  formData.orgRevisionName = "";
  formData.typeDraft = "";
}

async function fetchOrgRevision() {
  showLoader();
  await http
    .get(config.API.organizationHistoryNew)
    .then((res) => {
      const data = res.data.result.filter(
        (e: HistoryType) => e.orgRevisionIsDraft === false
      );
      if (data) {
        const listOption = data.map((e: HistoryType) => ({
          id: e.orgRevisionId,
          name: e.orgRevisionName,
        }));
        orgRevisionOpMain.value = listOption;
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function filterSelector(val: any, update: Function, refData: string) {
  switch (refData) {
    case "orgRevisionId":
      update(() => {
        orgRevisionOp.value = orgRevisionOpMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    default:
      break;
  }
}

watch(
  () => modal.value,
  () => {
    modal.value && (formData.typeDraft = type.value);
    modal.value && type.value !== "NEW" && fetchOrgRevision();
  }
);
</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
                  dense
                  hide-bottom-space
                  outlined
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  v-model="formData.typeDraft"
                  :options="typeOp"
                  label="ประเภทการโคลน"
                  :rules="[(val) => !!val || `${'กรุณาเลือกประเภทการโคลน'}`]"
                  lazy-rules
                />
              </div>
              <div class="col-6" v-if="type !== 'NEW'">
                <q-select
                  for="#orgRevisionId"
                  ref="orgRevisionIdRef"
                  dense
                  hide-bottom-space
                  outlined
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  v-model="formData.orgRevisionId"
                  :options="orgRevisionOp"
                  label="เลือกโครงสร้าง"
                  :rules="[(val) => !!val || `${'กรุณาเลือกโครงการสร้าง'}`]"
                  lazy-rules
                  use-input
                  @filter="(inputValue:any,
                  doneFn:Function) => filterSelector(inputValue, doneFn,'orgRevisionId'
                  ) "
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey-5">
                        ไม่พบข้อมูล
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </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>
