<script setup lang="ts">
import { ref, reactive, watch, computed } 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,
    default: () => "",
  },
  fetchDataTable: {
    type: Function,
    require: true,
    default: () => "",
  },
  dataNode: {
    type: Object,
    require: true,
  },
  edit: {
    type: Function,
    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 orgLevelSubOptionMain = ref<DataOption[]>([]);

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 orgLevelSubRef = ref<Object | null>(null);

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

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

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
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() {
  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,
      ["org" + type + "RankSub"]:
        level.value !== 0 ? formData.orgLevelSub : undefined,
      [nameId]: rootId,
    };
    console.log(body);

    if (actionType.value === "ADD") {
      await http
        .post(config.API.createOrgLevel(type.toLocaleLowerCase()), body)
        .then(() => {
          props.fetchDataTree(store.draftId);
          success($q, "บันทึกข้อมูลสำเร็จ");
          closeClear();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    } else {
      props.dataNode &&
        (await http
          .put(
            config.API.orgLevelByid(
              type.toLocaleLowerCase(),
              props.dataNode.orgTreeId
            ),
            body
          )
          .then(() => {
            props.edit?.(
              props.dataNode?.orgTreeId,
              type,
              body,
              props.dataNode?.orgRootCode
            );
            closeClear();
            props.fetchDataTable(
              props?.dataNode?.orgTreeId,
              props?.dataNode?.orgLevel,
              false
            );
            success($q, "บันทึกข้อมูลสำเร็จ");
          })
          .catch((err) => {
            messageError($q, err);
          })
          .finally(async () => {
            // await props.fetchDataTree?.();
            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") {
        console.log(props.dataNode);

        if (props.dataNode) {
          formData.orgCode =
            props?.dataNode?.orgLevel !== 0
              ? props?.dataNode.orgTreeCode
              : undefined;
        }

        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;
          formData.orgLevelSub = props.dataNode.orgTreeRankSub;
          orgLevelOption.value =
            props.dataNode.orgTreeRank === "DEPARTMENT"
              ? orgLevelOptionMain.value
              : orgLevelOptionMain.value.slice(1, 4);
          selectOrgLevele(formData.orgLevel, false);
        }
      }
    }
  }
);

const tittleName = computed(() => {
  let name = "";
  if (actionType.value === "ADD") {
    name = level.value === 0 ? "เพิ่มหน่วยงาน" : "เพิ่มส่วนราชการ";
  } else {
    name = level.value === 0 ? "แก้ไขหน่วยงาน" : "แก้ไขส่วนราชการ";
  }

  return name;
});

function selectOrgLevele(val: string, status: boolean = true) {
  formData.orgLevelSub = status ? "" : formData.orgLevelSub;
  switch (val) {
    case "OFFICE":
      orgLevelSubOptionMain.value = [
        { name: "ระดับกอง", id: "DIVISION" },
        {
          name: "สำนักงาน",
          id: "OFFICE",
        },
        { name: "ส่วนราชการ", id: "GOVERNMENT" },
        { name: "โรงพยาบาล", id: "HOSPITAL" },
        { name: "เทียบเท่ากอง", id: "EQUIVALENT" },
      ];

      break;
    case "DIVISION":
      orgLevelSubOptionMain.value = [
        { name: "ระดับส่วน", id: "SECTION" },
        {
          name: "กลุ่มภารกิจ",
          id: "MISSION",
        },
      ];

    case "SECTION":
      orgLevelSubOptionMain.value = [
        { name: "ระดับฝ่าย", id: "FACTION" },
        {
          name: "กลุ่มงาน",
          id: "WORK",
        },
      ];

    default:
      break;
  }
}
</script>

<template>
  <template>
    <q-dialog v-model="props.modal" persistent>
      <q-card style="min-width: 60vw">
        <form @submit.prevent="validateForm">
          <DialogHeader :tittle="tittleName" :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="level == 0 ? 'ชื่อหน่วยงาน' : 'ชื่อส่วนราชการ'"
                  hide-bottom-space
                  :rules="[
                    (val) =>
                      !!val ||
                      `${
                        level == 0
                          ? 'กรุณากรอกชื่อหน่วยงาน'
                          : 'กรุณากรอกชื่อส่วนราชการ'
                      }`,
                  ]"
                />
              </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
                  :readonly="
                    (actionType === 'ADD' && props?.dataNode?.orgLevel !== 0) ||
                    (actionType === 'EDIT' && props?.dataNode?.orgLevel > 1)
                  "
                  mask="##"
                  v-model="formData.orgCode"
                  ref="orgCodeRef"
                  dense
                  outlined
                  for="#ocNo"
                  :label="level == 0 ? 'รหัสหน่วยงาน' : 'รหัสส่วนราชการ'"
                  hide-bottom-space
                  class="inputNumber"
                  :rules="[
                    (val) =>
                      !!val ||
                      `${
                        level == 0
                          ? 'กรุณากรอกรหัสหน่วยงาน'
                          : 'กรุณากรอกรหัสส่วนราชการ'
                      }`,
                  ]"
                />
              </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"
                  @update:model-value="selectOrgLevele"
                  :options="orgLevelOption"
                  :label="
                    level == 0 ? 'ระดับของหน่วยงาน' : 'ระดับของส่วนราชการ'
                  "
                  :rules="[
                    (val) =>
                      !!val ||
                      `${
                        level == 0
                          ? 'กรุณาเลือกระดับของหน่วยงาน'
                          : 'กรุณาเลือกระดับของส่วนราชการ'
                      }`,
                  ]"
                  lazy-rules
                />
              </div>
              <div class="col-4" v-if="formData.orgLevel !== '' && level !== 0">
                <q-select
                  :readonly="level === 0 || formData.orgLevel === 'DEPARTMENT'"
                  ref="orgLevelSubRef"
                  dense
                  hide-bottom-space
                  outlined
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  v-model="formData.orgLevelSub"
                  :options="orgLevelSubOptionMain"
                  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
                />
              </div>
              <div class="col-4">
                <q-input
                  v-model="formData.orgPhoneIn"
                  ref="orgPhoneInRef"
                  dense
                  outlined
                  for="#telIn"
                  label="หมายเลขโทรศัพท์ที่ติดต่อจากภายใน"
                  hide-bottom-space
                />
              </div>
              <div class="col-4">
                <q-input
                  v-model="formData.orgFax"
                  ref="orgFaxRef"
                  dense
                  outlined
                  for="#tel"
                  label="หมายเลขโทรสาร"
                  hide-bottom-space
                />
              </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>

<style scoped>
.inputNumber >>> input[type="number"] {
  -moz-appearance: textfield;
}
.inputNumber >>> input::-webkit-outer-spin-button,
.inputNumber >>> input::-webkit-inner-spin-button {
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
}
</style>
