<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 { QTableProps } from "quasar";
import DialogHeader from "@/components/DialogHeader.vue";
import type {
  FormExecutiveRef,
  RowListForm,
} from "@/modules/01_metadataNew/interface/request/position/index";
import { useCounterMixin } from "@/stores/mixin";
import { bo } from "@fullcalendar/core/internal-common";
const { dialogConfirm, showLoader, success, hideLoader, messageError } =
  useCounterMixin();

const formExecutive = reactive<RowListForm>({
  id: "",
  posExecutiveName: "",
  posExecutivePriority: null,
});
const $q = useQuasar();

const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const modal = defineModel<boolean>("executive", { required: true });
const formData = defineModel<any>("formData", { required: true });
const isEdit = defineModel<any>("edit", { required: true });

const posExecutiveNameRef = ref<Object | null>(null);
const posExecutivePriorityRef = ref<Object | null>(null);

const objectExecutiveRef: FormExecutiveRef = {
  posExecutiveName: posExecutiveNameRef,
  posExecutivePriority: posExecutivePriorityRef,
};

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

/** ฟังชั่น บันทึก */
function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      const body = {
        posExecutiveName: formExecutive.posExecutiveName,
        posExecutivePriority: formExecutive.posExecutivePriority, //สายงาน
      };
      await http
        .post(config.API.orgPosExecutive, body)
        .then(() => {
          success($q, "เพิ่มข้อมูลสำเร็จ");
          clearForm();
          modal.value = false;
          props.getData?.()
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการเพิ่มตำแหน่ง",
    "ต้องการยืนยันการเพิ่มตำแหน่งนี้ใช่หรือไม่?"
  );
}
/** ฟังชั่น บันทึก */
function putSubmit() {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      const body = {
        posExecutiveName: formExecutive.posExecutiveName,
        posExecutivePriority: formExecutive.posExecutivePriority, //สายงาน
      };
      await http
        .put(config.API.orgPosExecutive+`/${formExecutive.id}`, body)
        .then(() => {
          success($q, "เพิ่มข้อมูลสำเร็จ");
          clearForm();
          modal.value = false;
          props.getData?.()
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการเพิ่มตำแหน่ง",
    "ต้องการยืนยันการเพิ่มตำแหน่งนี้ใช่หรือไม่?"
  );
}

async function clearForm() {
  formExecutive.id = "";
  formExecutive.posExecutiveName = "";
  formExecutive.posExecutivePriority = null;
  isEdit.value = false;
}

/**
 * ส่งค่า css ออกไปตามเงื่อนไข
 * @param val true/false
 */
function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer inputgreen ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

function close() {
  clearForm();
  modal.value = false;
}
watch(
  () => modal.value,
  () => {
    if (modal.value == true) {
      const dataList = formData.value;
      formExecutive.id = "";
      formExecutive.posExecutiveName = "";
      formExecutive.posExecutivePriority = null;
      if (isEdit.value == true) {
        formExecutive.id = dataList.id;
        formExecutive.posExecutiveName = dataList.posExecutiveName;
        formExecutive.posExecutivePriority = dataList.posExecutivePriority;
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 50vw">
      <form @submit.prevent="validateFormExecutive">
        <DialogHeader
          :tittle="isEdit ? `แก้ไขตำแหน่งทางการบริหาร` : 'เพิ่มตำแหน่งทางการบริหาร'"
          :close="close"
        />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm col-12">
            <div class="col-6">
              <q-input
                ref="posExecutiveNameRef"
                v-model="formExecutive.posExecutiveName"
                :class="inputEdit(isReadonly)"
                dense
                outlined
                for="#posExecutiveName"
                label="ชื่อตำแหน่งทางการบริหาร"
                lazy-rules
                hide-bottom-space
                :rules="[
                  (val) => !!val || `${'กรุณากรอกชื่อตำแหน่งทางการบริหาร'}`,
                ]"
              />
            </div>
            <div class="col-6">
              <q-input
                ref="posExecutivePriorityRef"
                v-model="formExecutive.posExecutivePriority"
                :class="inputEdit(isReadonly)"
                dense
                outlined
                type="number"
                for="#posExecutivePriority"
                label="ลำดับความสำคัญ"
                lazy-rules
                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>
