<script setup lang="ts">
import { ref, watch } from "vue";
import { QForm, useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";
import type { DataOption } from "@/modules/04_registry/components/profileType";

const $q = useQuasar();
const myForm = ref<QForm>();
const mixin = useCounterMixin();
const {
  date2Thai,
  dialogConfirm,
  success,
  messageError,
  showLoader,
  hideLoader,
  notifyError,
} = mixin;

const brand = ref<string>("");
const roundNo = ref<string | undefined>("");
const cardid = ref<string>("");
const OrganazationId = ref<string>("");
const fullName = ref<string>("");
// const position = ref<string>("");
const receivedate = ref<Date | null>();
const returndate = ref<Date | null>();
const reason = ref<string>("");
const listPerson = ref<any>([]);
const OrgList = ref<DataOption[]>([]);
const insigniaNoteProfileId = ref<string>("");

const clearData = () => {
  receivedate.value = null;
  returndate.value = null;
  OrganazationId.value = "";
  roundNo.value = "";
  cardid.value = "";
  fullName.value = "";
  brand.value = "";
  reason.value = "";
};

const props = defineProps({
  modal: Boolean,
  save: {
    type: Function,
    default: () => console.log("not function"),
  },
  close: {
    type: Function,
    default: () => console.log("not function"),
  },
  closeAndFecth: {
    type: Function,
    default: () => console.log("not function"),
  },
  roundId: {
    type: String,
  },
  action: {
    type: String,
  },
  typeId: {
    type: String,
  },
  selectRoundOption: {
    type: Array,
  },
  profileId: {
    type: String,
    default: "",
  },
});

watch(props, () => {
  if (props.modal == true && props.roundId != "all") {
    roundNo.value = props.roundId;
    fecthlistInsignia();
    fetchOrgList();
    if (props.action == "editData") {
      fetchData();
    }
  }
});

const fecthlistInsignia = async () => {
  showLoader();
  let data = {
    insigniaTypeId: props.typeId,
    insigniaNoteId: props.roundId,
    insigniaId: "",
  };
  await http
    .post(config.API.noteSearch(), data)
    .then((res) => {
      listPerson.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchOrgList = async () => {
  showLoader();
  await http
    .get(config.API.typeOc())
    .then(async (response: any) => {
      const orgArr = response.data.result.map((e: any) => ({
        id: e.organizationId,
        name: e.organizationName,
      }));

      if (props.action == "editData") {
        OrgList.value = [
          {
            id: "00000000-0000-0000-0000-000000000000",
            name: "สำนักนายกรัฐมนตรี",
          },
          ...orgArr,
        ];
      } else {
        OrgList.value = orgArr;
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.insigniaManageBorrowById(props.profileId))
    .then(async (response: any) => {
      console.log(response.data.result);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
};

const clickSave = async () => {
  await myForm.value!.validate().then((result: boolean) => {
    if (result) {
      dialogConfirm($q, async () => {
        if (props.action == "addData") {
          await http
            .post(config.API.insigniaManageBorrow(), {
              borrowDate: receivedate.value,
              borrowOrganizationId: OrganazationId.value,
              insigniaNoteProfileId: insigniaNoteProfileId.value,
            })
            .then(() => {
              success($q, "บันทึกข้อมูลสำเร็จ");
            })
            .catch((err) => {
              messageError($q, err);
            })
            .finally(() => {
              clearData();
              props.closeAndFecth();
            });
        } else {
          await http
            .put(config.API.insigniaManageBorrowReturn(props.profileId), {
              returnDate: returndate.value,
              returnOrganizationId: OrganazationId.value,
              returnReason: reason.value,
            })
            .then(() => {
              success($q, "บันทึกข้อมูลสำเร็จ");
            })
            .catch((err) => {
              messageError($q, err);
            })
            .finally(() => {
              clearData();
              props.closeAndFecth();
            });
        }
      });
    }
  });
};

const searchcardid = async () => {
  if (cardid.value.length === 13) {
    const node = await listPerson.value.find(
      (e: any) => e.citizenId === cardid.value
    );

    if (node) {
      console.log("node", node);
      fullName.value = `${node.prefix} ${node.fullName}`;
      brand.value = node.requestInsignia;
      insigniaNoteProfileId.value = node.id;
    } else notifyError($q, "ไม่พบข้อมูลการได้รับในรอบนี้");
  }
};

const closeDialog = () => {
  clearData();
  props.close();
};
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="min-width: 900px" class="q-pb-md">
      <q-toolbar class="q-py-md">
        <q-toolbar-title class="text-h6">ยืม-คืนเครื่องราชฯ </q-toolbar-title>
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="closeDialog"
          style="color: #ff8080; background-color: #ffdede"
          ><q-tooltip>ปิด</q-tooltip></q-btn
        >
      </q-toolbar>
      <q-separator />

      <q-form ref="myForm">
        <div class="q-pa-md">
          <div
            class="row col-12 items-center q-col-gutter-x-xs q-col-gutter-y-xs"
          >
            <div
              v-if="props.action === 'addData'"
              class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs"
            >
              <div class="col-6">
                <q-select
                  v-model="roundNo"
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  :label="`${'รอบการขอเครื่องราชฯ'}`"
                  emit-value
                  map-options
                  option-label="name"
                  :options="selectRoundOption"
                  option-value="id"
                  :readonly="false"
                  :borderless="false"
                  style="min-width: 150px"
                  :rules="[(val) => !!val || 'กรุณาเลือกรอบการขอเครื่องราชฯ']"
                  @update:model-value="fecthlistInsignia()"
                />
              </div>
              <div class="col-12 text-weight-bold text-grey">ข้อมูลผู้ยืม</div>
              <div class="col-xs-12 col-sm-6">
                <q-input
                  :disable="roundNo == ''"
                  hide-bottom-space
                  outlined
                  class="inputgreen"
                  v-model="cardid"
                  dense
                  lazy-rules
                  :rules="[
                    (val: string) => !!val || `${'กรุณากรอก เลขบัตรประจำตัวประชาชน'}`,
                    (val: string) =>
                      val.length >= 13 ||
                      `${'กรุณากรอกเลขบัตรประจำตัวประชาชนให้ครบ'}`,
                  ]"
                  label="เลขบัตรประจำตัวประชาชน"
                  maxlength="13"
                  mask="#############"
                  @keyup="searchcardid"
                />
              </div>
              <div class="col-xs-6 col-sm-6">
                <q-input
                  disable
                  hide-bottom-space
                  outlined
                  dense
                  lazy-rules
                  class="inputgreen"
                  borderless
                  v-model="fullName"
                  :label="`${'ชื่อ-นามสกุล'}`"
                />
              </div>

              <div class="col-12 q-my-xs"><q-separator size="2px" /></div>
              <div class="col-12 text-weight-bold text-grey">
                รายละเอียดการยืมเครื่องราชฯ
              </div>
              <div class="col-xs-12 col-sm-6">
                <q-input
                  v-model="brand"
                  disable
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  :label="`${'เครื่องราชฯ'}`"
                />
              </div>
              <div class="col-xs-12 col-sm-6">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="receivedate"
                  :locale="'th'"
                  autoApply
                  borderless
                  :enableTimePicker="false"
                  week-start="0"
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      dense
                      borderless
                      outlined
                      :rules="[(val) => !!val || 'กรุณาเลือกวันที่']"
                      hide-bottom-space
                      :model-value="
                        receivedate != null ? date2Thai(receivedate) : undefined
                      "
                      :label="`${'วันที่ยืม'}`"
                      clearable
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="col-xs-12 col-sm-6">
                <q-select
                  hide-bottom-space
                  :options="OrgList"
                  dense
                  borderless
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  outlined
                  v-model="OrganazationId"
                  :label="`เลือกหน่วยงาน`"
                />
              </div>
            </div>

            <div
              class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs"
              v-if="props.action === 'editData'"
            >
              <div class="col-12 q-my-xs"><q-separator size="2px" /></div>
              <div class="col-12 text-weight-bold text-grey">
                รายละเอียดการคืนเครื่องราชฯ
              </div>
              <div class="col-xs-12 col-sm-6">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="returndate"
                  :locale="'th'"
                  autoApply
                  borderless
                  :enableTimePicker="false"
                  week-start="0"
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      dense
                      borderless
                      outlined
                      :rules="[(val) => !!val || 'กรุณาเลือกวันที่']"
                      hide-bottom-space
                      :model-value="
                        returndate != null ? date2Thai(returndate) : undefined
                      "
                      :label="`${'วันที่คืน'}`"
                      clearable
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="col-xs-12 col-sm-6">
                <q-select
                  hide-bottom-space
                  :options="OrgList"
                  dense
                  borderless
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  outlined
                  v-model="OrganazationId"
                  :label="`เลือกหน่วยงานที่ส่งคืน`"
                />
              </div>

              <div class="col-12">
                <q-input
                  type="textarea"
                  hide-bottom-space
                  dense
                  borderless
                  option-label="name"
                  option-value="id"
                  emit-value
                  map-options
                  outlined
                  v-model="reason"
                  :label="`สาเหตุที่ส่งคืนเครื่องราชอิสริยาภรณ์`"
                />
              </div>
            </div>
          </div>
        </div>
      </q-form>

      <q-separator />
      <div class="q-pa-md">
        <div class="row justify-end">
          <q-btn label="บันทึก" @click="clickSave" color="public">
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </div>
      </div>
    </q-card>
  </q-dialog>
</template>
