<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 type {
  FormDataAgency,
  FormAgencyRef,
  DataOption,
} from "@/modules/02_organizationalNew/interface/index/Main";

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

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

const level = defineModel<number>("orgLevel", { required: true });
const actionType = defineModel<string>("actionType", { required: true });
const props = defineProps({
  modal: {
    type: Boolean,
    require: true,
  },
  close: {
    type: Function,
    require: true,
  },
  fetchDataTree: {
    type: Function,
    require: true,
  },
  dataNode: {
    type: Object,
    require: true,
  },
});

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

const orgLevelOptionMain = ref<DataOption[]>([
  { name: "ระดับสำนัก", id: "DEPARTMENT" },
  {
    name: "ระดับกอง/สำนักงาน/ส่วนราชการ/โรงพยาบาล/เทียบเท่ากอง",
    id: "OFFICE",
  },
  { name: "ระดับส่วน/กลุ่มภารกิจ", id: "DIVISION" },
  { name: "ระดับฝ่าย/กลุ่มงาน", id: "SECTION" },
]);

const orgLevelOption = ref<DataOption[]>([]);

const orgNameRef = ref<Object | null>(null);
const orgShortNameRef = ref<Object | null>(null);
const orgCodeRef = ref<Object | null>(null);
const orgPhoneExRef = ref<Object | null>(null);
const orgPhoneInRef = ref<Object | null>(null);
const orgFaxRef = ref<Object | null>(null);
const orgLevelRef = ref<Object | null>(null);

const formData = reactive<FormDataAgency>({
  orgName: "",
  orgShortName: "",
  orgCode: "",
  orgPhoneEx: "",
  orgPhoneIn: "",
  orgFax: "",
  orgLevel: "",
});

/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const objectComplaintsRef: FormAgencyRef = {
  orgName: orgNameRef,
  orgShortName: orgShortNameRef,
  orgCode: orgCodeRef,
  orgPhoneEx: orgPhoneExRef,
  orgPhoneIn: orgPhoneInRef,
  orgFax: orgFaxRef,
  orgLevel: orgLevelRef,
};

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
function validateForm() {
  const hasError = [];
  for (const key in objectComplaintsRef) {
    if (Object.prototype.hasOwnProperty.call(objectComplaintsRef, key)) {
      const property = objectComplaintsRef[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() {
  console.log(level.value);
  dialogConfirm($q, async () => {
    // showLoader();
    const type = store.checkLevel(level.value);
    const nameId =
      level.value === 0
        ? "orgRevisionId"
        : level.value === 1
        ? "orgRootId"
        : level.value === 2
        ? "orgChild1Id"
        : level.value === 3
        ? "orgChild2Id"
        : "orgChild3Id";

    let rootId: string = "";
    if (actionType.value === "ADD") {
      rootId = level.value === 0 ? store.draftId : props.dataNode?.orgTreeId;
    } else {
      rootId = level.value === 0 ? store.draftId : props.dataNode?.orgRootId;
    }

    const body = {
      ["org" + type + "Name"]: formData.orgName,
      ["org" + type + "ShortName"]: formData.orgShortName,
      ["org" + type + "Code"]: formData.orgCode,
      ["org" + type + "PhoneEx"]: formData.orgPhoneEx,
      ["org" + type + "PhoneIn"]: formData.orgPhoneIn,
      ["org" + type + "Fax"]: formData.orgFax,
      ["org" + type + "Rank"]: formData.orgLevel,
      [nameId]: rootId,
    };
    console.log(body);

    if (actionType.value === "ADD") {
      await http
        .post(config.API.createOrgLevel(type.toLocaleLowerCase()), body)
        .then((res) => {
          console.log(res);
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          console.log(err);
          messageError($q, err);
        })
        .finally(async () => {
          await props.fetchDataTree?.();
          await closeClear();
          await hideLoader();
        });
    } else {
      props.dataNode &&
        (await http
          .put(
            config.API.orgLevelByid(
              type.toLocaleLowerCase(),
              props.dataNode.orgTreeId
            ),
            body
          )
          .then((res) => {
            console.log(res);
            success($q, "บันทึกข้อมูลสำเร็จ");
          })
          .catch((err) => {
            console.log(err);
            messageError($q, err);
          })
          .finally(async () => {
            await props.fetchDataTree?.();
            await closeClear();
            await hideLoader();
          }));
    }
  });
}

function closeClear() {
  formData.orgName = "";
  formData.orgShortName = "";
  formData.orgCode = "";
  formData.orgPhoneEx = "";
  formData.orgPhoneIn = "";
  formData.orgFax = "";
  formData.orgLevel = "";
  props.close?.();
}

watch(
  () => props.modal,
  () => {
    if (props.modal === true) {
      if (actionType.value === "ADD") {
        if (level.value === 0) {
          formData.orgLevel = "DEPARTMENT";
          orgLevelOption.value = orgLevelOptionMain.value;
        } else {
          orgLevelOption.value = orgLevelOptionMain.value.slice(1, 4);
          formData.orgLevel = "";
        }
      } else {
        if (props.dataNode) {
          formData.orgName = props.dataNode.orgTreeName;
          formData.orgShortName = props.dataNode.orgTreeShortName;
          formData.orgCode = props.dataNode.orgTreeCode;
          formData.orgPhoneEx = props.dataNode.orgTreePhoneEx;
          formData.orgPhoneIn = props.dataNode.orgTreePhoneIn;
          formData.orgFax = props.dataNode.orgTreeFax;
          formData.orgLevel = props.dataNode.orgTreeRank;
          orgLevelOption.value = orgLevelOptionMain.value;
        }
      }
    }
  }
);
</script>
<template>
  <template>
    <q-dialog v-model="props.modal" persistent>
      <q-card style="min-width: 50vw">
        <form @submit.prevent="validateForm">
          <DialogHeader :tittle="`เพิ่มหน่วยงาน`" :close="closeClear" />
          <q-separator />
          <q-card-section>
            <div class="row q-col-gutter-sm">
              <div class="col-4">
                <q-input
                  v-model="formData.orgName"
                  ref="orgNameRef"
                  dense
                  outlined
                  for="#ocName"
                  label="ชื่อหน่วยงาน"
                  hide-bottom-space
                  :rules="[(val) => !!val || `${'กรุณากรอกชื่อหน่วยงาน'}`]"
                />
              </div>
              <div class="col-2">
                <q-input
                  v-model="formData.orgShortName"
                  ref="orgShortNameRef"
                  dense
                  outlined
                  for="#shortName"
                  label="ชื่อย่อ"
                  hide-bottom-space
                  :rules="[(val) => !!val || `${'กรุณากรอกชื่อย่อ'}`]"
                />
              </div>
              <div class="col-2">
                <q-input
                  v-model="formData.orgCode"
                  ref="orgCodeRef"
                  dense
                  outlined
                  for="#ocNo"
                  label="รหัสหน่วยงาน"
                  hide-bottom-space
                  :rules="[(val) => !!val || `${'กรุณากรอกรหัสหน่วยงาน'}`]"
                />
              </div>
              <div class="col-4">
                <q-select
                  :readonly="level === 0 || formData.orgLevel === 'DEPARTMENT'"
                  for="#ocLevel"
                  ref="orgLevelRef"
                  dense
                  hide-bottom-space
                  outlined
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  v-model="formData.orgLevel"
                  :options="orgLevelOption"
                  label="ระดับของหน่วยงาน"
                  :rules="[(val) => !!val || `${'กรุณาเลือกระดับของหน่วยงาน'}`]"
                  lazy-rules
                />
              </div>
              <div class="col-4">
                <q-input
                  v-model="formData.orgPhoneEx"
                  ref="orgPhoneExRef"
                  dense
                  outlined
                  for="#telOut"
                  label="หมายเลขโทรศัพท์ที่ติดต่อจากภายนอก"
                  hide-bottom-space
                  :rules="[
                    (val) =>
                      !!val ||
                      `${'กรุณากรอกหมายเลขโทรศัพท์ที่ติดต่อจากภายนอก'}`,
                  ]"
                />
              </div>
              <div class="col-4">
                <q-input
                  v-model="formData.orgPhoneIn"
                  ref="orgPhoneInRef"
                  dense
                  outlined
                  for="#telIn"
                  label="หมายเลขโทรศัพท์ที่ติดต่อจากภายใน"
                  hide-bottom-space
                  :rules="[
                    (val) =>
                      !!val || `${'กรุณากรอกหมายเลขโทรศัพท์ที่ติดต่อจากภายใน'}`,
                  ]"
                />
              </div>
              <div class="col-4">
                <q-input
                  v-model="formData.orgFax"
                  ref="orgFaxRef"
                  dense
                  outlined
                  for="#tel"
                  label="หมายเลขโทรสาร"
                  hide-bottom-space
                  :rules="[(val) => !!val || `${'กรุณากรอกหมายเลขโทรสาร'}`]"
                />
              </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>
