<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { QForm, useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/** import Type*/
import type { DataOption } from "@/modules/04_registry/components/profileType";

/** import Stores */
import { useCounterMixin } from "@/stores/mixin";
/** useStore*/
const mixin = useCounterMixin();
const {
  date2Thai,
  showLoader,
  success,
  hideLoader,
  messageError,
  dialogConfirm,
  dateToISO,
} = mixin;

const $q = useQuasar();
const myForm = ref<any>();

const files = ref<any>();
const filesReturn = ref<any>();
const OrganazationId = ref<string>("");
const OrganazationId2 = ref<string>("");
const OrgList = ref<DataOption[]>([]);
const OrgList2 = ref<DataOption[]>([]);
const Datereceive = ref<Date | null>();
const Datereturn = ref<Date | null>();
const remark = ref<string>("");
const nullii = ref<any>(null);
const filesCheck = ref<string>("");
const filesReturnCheck = ref<string>("");

const props = defineProps({
  modal: Boolean,
  personId: String,
  close: Function,
  fecthlistInsignia: Function,
  dateCheckReceive: String,
  dateCheckReturn: String,

  dataModal: Object,
});

/** function reset วันที่ประกาศราชกิจจานุเบกษา*/
function clearReceiveDate() {
  Datereceive.value = null;
}

/** function clearDate */
function clearReturnDate() {
  Datereturn.value = null;
}

/** function Colsepopup*/
function close() {
  props.close?.();
  Datereceive.value = null;
  files.value = null;
  OrganazationId.value = "";
  Datereturn.value = null;
  filesReturn.value = null;
  OrganazationId2.value = "";
}

/**
 * function ยืนยันการบันทึกข้อมูล
 * @param type receive,return
 * @param id personId
 */
async function SaveData(type: string, id: string) {
  await myForm.value.validate().then((result: boolean) => {
    if (result) {
      dialogConfirm($q, () => dataSave(type, id));
    } else {
    }
  });
}

/**
 * function บันทึกข้อมูล
 * @param type receive,return
 * @param id personId
 */
function dataSave(type: string, id: string) {
  const formData = new FormData();
  if (props.dateCheckReceive === null) {
    formData.append("Date", dateToISO(Datereceive.value as Date ?? nullii));
    formData.append("File", files.value);
    formData.append("OrgId", OrganazationId.value);
  } else {
    formData.append("Date", dateToISO(Datereturn.value as Date?? nullii));
    formData.append("File", filesReturn.value);
    formData.append("OrgId", OrganazationId2.value);
  }
  showLoader();
  http
    .put(config.API.requestinsignia(type, id), formData)
    .then(() => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      Datereceive.value = null;
      files.value = null;
      OrganazationId.value = "";
      Datereturn.value = null;
      filesReturn.value = null;
      OrganazationId2.value = "";
      props.fecthlistInsignia?.();
      props.close?.();
      hideLoader();
    });
}

/** function เรียกหน่วยงาน*/
async function fetchOrgList() {
  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,
      }));
      OrgList.value = orgArr;
      OrgList2.value = [
        {
          id: "00000000-0000-0000-0000-000000000000",
          name: "สำนักนายกรัฐมนตรี",
        },
        ...orgArr,
      ];
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** hook*/
onMounted(() => {
  fetchOrgList();
});

/** callback function จำทำงานเมื่อ props มีการเปลี่ยนแปลง*/
watch(props, () => {
  if (props.dataModal) {
    Datereceive.value = props.dataModal.dateReceiveInsignia;
    Datereturn.value = props.dataModal.dateReturnInsignia;
    OrganazationId.value = props.dataModal.orgReceiveInsignia;
    filesCheck.value = props.dataModal.docReceiveInsignia;
    filesReturnCheck.value = props.dataModal.docReturnInsignia;
    OrganazationId2.value =
      Datereturn.value != null
        ? props.dataModal.orgReturnInsignia == null ||
          props.dataModal.orgReturnInsignia == "-"
          ? "00000000-0000-0000-0000-000000000000"
          : props.dataModal.orgReturnInsignia
        : "-";
  }
});
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="min-width: 900px">
      <q-toolbar>
        <q-toolbar-title class="text-subtitle2 text-bold"
          >รับ-คืนเครื่องราชฯ</q-toolbar-title
        >
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="close"
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-toolbar>
      <q-separator />

      <q-form ref="myForm">
        <div class="q-pa-md bg-grey-1">
          <div class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs">
            <div class="col-12 text-weight-bold text-grey-7">
              รับเครื่องราชฯ
            </div>
            <div class="col-xs-12 col-sm-4">
              <datepicker
                menu-class-name="modalfix"
                v-model="Datereceive"
                :locale="'th'"
                autoApply
                borderless
                :enableTimePicker="false"
                week-start="0"
                :readonly="dateCheckReceive !== null"
              >
                <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="
                      Datereceive != null ? date2Thai(Datereceive) : null
                    "
                    :label="`${'วันที่ได้รับ'}`"
                    :disable="dateCheckReceive !== null"
                  >
                  <template v-if="Datereceive" v-slot:append>
                      <q-icon
                        name="cancel"
                        @click.stop.prevent="Datereceive = null"
                        class="cursor-pointer"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div v-if="filesCheck !== null" class="col-xs-12 col-sm-4">
              <q-btn
                type="a"
                outline
                ripple
                class="full-width"
                target="_blank"
                label="ดาวน์โหลดเอกสาร"
                :href="filesCheck"
                size="15px"
                icon="mdi-download"
                color="primary"
              >
                <q-tooltip>ดาวน์โหลดเอกสาร รับเครื่องราชฯ</q-tooltip>
              </q-btn>
            </div>
            <div class="col-xs-12 col-sm-4" v-if="filesCheck === null">
              <q-file
                outlined
                dense
                v-model="files"
                label="ไฟล์หลักฐานการรับ"
                lazy-rules
                :rules="[(val) => val || 'กรุณาเลือกไฟล์หลักฐานการรับ']"
                hide-bottom-space
                :disable="dateCheckReceive !== null"
              >
                <template v-slot:prepend>
                  <q-icon name="attach_file" color="primary" />
                </template>
              </q-file>
            </div>
            <div class="col-xs-12 col-sm-4">
              <q-select
                hide-bottom-space
                :options="OrgList"
                dense
                borderless
                option-label="name"
                option-value="id"
                emit-value
                map-options
                outlined
                v-model="OrganazationId"
                lazy-rules
                :label="`หน่วยงานที่รับ`"
                :rules="[(val) => !!val || 'กรุณาเลือกหน่วยงานที่รับ']"
                :disable="dateCheckReceive !== null"
              />
            </div>
          </div>

          <div
            v-if="dateCheckReceive !== null"
            class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs"
          >
            <div class="col-12 q-mt-sm"><q-separator /></div>
            <div class="col-12 text-weight-bold text-grey-7">
              คืนเครื่องราชฯ
            </div>
            <div class="col-xs-12 col-sm-4">
              <datepicker
                menu-class-name="modalfix"
                v-model="Datereturn"
                :locale="'th'"
                autoApply
                borderless
                :enableTimePicker="false"
                week-start="0"
                :readonly="dateCheckReturn !== null"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    dense
                    borderless
                    outlined
                    lazy-rules
                    :rules="[(val) => !!val || 'กรุณาเลือกวันที่คืน']"
                    hide-bottom-space
                    :model-value="
                      Datereturn != null ? date2Thai(Datereturn) : undefined
                    "
                    :label="`${'วันที่คืน'}`"
                    clearable
                    @clear="clearReturnDate"
                    :disable="dateCheckReturn !== null"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div v-if="filesReturnCheck !== null" class="col-xs-12 col-sm-4">
              <q-btn
                type="a"
                outline
                ripple
                class="full-width"
                target="_blank"
                label="ดาวน์โหลดเอกสาร"
                :href="filesReturnCheck"
                size="15px"
                icon="mdi-download"
                color="primary"
              >
                <q-tooltip>ดาวน์โหลดเอกสาร คืนเครื่องราชฯ</q-tooltip>
              </q-btn>
            </div>
            <div class="col-xs-12 col-sm-4" v-if="filesReturnCheck === null">
              <q-file
                outlined
                dense
                v-model="filesReturn"
                label="ไฟล์หลักฐานการคืน"
                lazy-rules
                :rules="[(val) => val || 'กรุณาเลือกไฟล์หลักฐานการคืน']"
                hide-bottom-space
                :disable="dateCheckReturn !== null"
              >
                <template v-slot:prepend>
                  <q-icon name="attach_file" color="primary" />
                </template>
              </q-file>
            </div>
            <div class="col-xs-12 col-sm-4">
              <q-select
                hide-bottom-space
                :options="OrgList2"
                dense
                borderless
                option-label="name"
                option-value="id"
                emit-value
                map-options
                outlined
                v-model="OrganazationId2"
                lazy-rules
                :label="`หน่วยงานที่คืน`"
                :rules="[(val) => !!val || 'กรุณาเลือกหน่วยงานที่คืน']"
                :disable="dateCheckReturn !== null"
              />
            </div>
          </div>
        </div>
      </q-form>

      <q-separator />
      <div class="q-px-md q-py-sm">
        <div class="row justify-end">
          <q-btn
            v-if="dateCheckReturn === null"
            label="บันทึก"
            color="public"
            @click="
              SaveData(
                props.dateCheckReceive === null ? 'receive' : 'return',
                props.personId as string
              )
            "
          >
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </div>
      </div>
    </q-card>
  </q-dialog>
</template>
