<script setup lang="ts">
import { onMounted, ref } 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<any>();
const mixin = useCounterMixin();
const { date2Thai,showLoader,success,hideLoader,messageError,dialogConfirm } = mixin;
const files = ref<any>();
const filesReturn = ref<any>();
const OrganazationId = ref<string>("");
const OrgList = ref<DataOption[]>([]);
const Datereceive = ref<Date | null>(null);
const Datereturn = ref<Date | null>();
const remark = ref<string>("")
const nullii = ref<any>(null)
const props = defineProps({
  modal: Boolean,
  personId: String,
  close: Function,
  fecthlistInsignia: Function,
  fileCheck:String
});
// reset วันที่ประกาศราชกิจจานุเบกษา
const clearReceiveDate = () => {
  Datereceive.value = null;
};
const clearReturnDate = () => {
  Datereturn.value = null;
};
const close = () => {
  props.close?.();
      Datereceive.value = null
      files.value = null
      OrganazationId.value = ''
      Datereturn.value = null
      filesReturn.value = null
      OrganazationId.value = ''
};

const SaveData = async (type:string,id:string) => {
 await myForm.value.validate().then((result: boolean) => {
  console.log(result)
    if (result) {
      console.log(1)
      dialogConfirm($q,() => dataSave(type,id))
}else{
  console.log(2)
}

})};
const dataSave = (type:string,id:string) => {
  const formData = new FormData();
    if(props.fileCheck === null){
        formData.append("Datereceiveinsignia", Datereceive.value?.toString() ?? "");
        formData.append("Docreceiveinsignia", files.value);
        formData.append("Orgreceiveinsignia", nullii.value);
    } else {
        formData.append("DateReturnInsignia", Datereturn.value?.toString() ?? "");
        formData.append("DocReturnInsignia", filesReturn.value);
        formData.append("OrgReturnInsignia", nullii.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
      OrganazationId.value = ''
      props.close?.();
      hideLoader();
      props.fecthlistInsignia?.()
    });
}
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();
    });
};
onMounted(()=>{
  fetchOrgList()
})
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="min-width: 900px">
      <q-toolbar>
        <q-toolbar-title v-if="props.fileCheck === null" class="text-subtitle2 text-bold">รับเครื่องราชฯ</q-toolbar-title>
        <q-toolbar-title v-else 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 v-if="props.fileCheck === null" class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs">
              <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">
                  <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="Datereceive != null ? date2Thai(Datereceive) : undefined
                        " :label="`${'วันที่ได้รับ'}`" clearable @clear="clearReceiveDate">
                      <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-4">

                <q-file outlined dense v-model="files" label="ไฟล์หลักฐานการรับ" lazy-rules
                  :rules="[(val) => val || 'กรุณาเลือกไฟล์หลักฐานการรับ']" hide-bottom-space>
                  <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 || 'กรุณาเลือกหน่วยงานที่รับ']" />
              </div>
            </div>
            <div v-if="props.fileCheck !== null" class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs">
              <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">
                  <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">
                      <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-4">
                <q-file outlined dense v-model="filesReturn" label="ไฟล์หลักฐานการคืน" lazy-rules
                  :rules="[(val) => val || 'กรุณาเลือกไฟล์หลักฐานการคืน']" hide-bottom-space>
                  <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 || 'กรุณาเลือกหน่วยงานที่คืน']" />
              </div>

              <!-- <div class="col-xs-12 col-sm-12">
                <q-input type="textarea" v-model="remark" outlined dense rows="3" :label="`${'หมายเหตุ'}`"/>
              </div> -->

            </div>
          </div>

      </q-form>

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