<script setup lang="ts">
import { ref, watch } from "vue";
import { useQuasar } from "quasar";

import { useCounterMixin } from "@/stores/mixin";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

/** import Type*/
import type { DataOption } from "@/modules/07_insignia/interface/index/Main";
import type { DataStructureTree } from "@/interface/main";

/**
 * import Components
 */
import DialogHeader from "@/components/DialogHeader.vue";

/** use*/
const route = useRoute();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  date2Thai,
  showLoader,
  success,
  hideLoader,
  messageError,
  dialogConfirm,
  dateToISO,
} = mixin;

/**
 * props
 */
const props = defineProps({
  modal: Boolean,
  personId: String,
  close: Function,
  fecthlistInsignia: Function,
  dateCheckReceive: String,
  dateCheckReturn: String,
  dataModal: Object,
});

const files = ref<any>(); //ไฟล์รับ
const filesReturn = ref<any>(); //ไฟล์คืน
const OrganazationId = ref<string>(""); //id หน่วยงานที่รับ
const OrganazationId2 = ref<string>(""); //id หน่วยงานที่คือ
const OrgListMain = ref<DataOption[]>([]); ////รายการหน่วยงาน
const OrgList = ref<DataOption[]>([]); //รายการหน่วยงาน
const OrgList2 = ref<DataOption[]>([]); //รายการหน่วยงาน

const Datereceive = ref<Date | null>(); //วันที่รับ
const Datereturn = ref<Date | null>(); //วันที่คืน
const nullii = ref<any>(null);
const filesCheck = ref<string>("");
const filesReturnCheck = ref<string>("");

/**
 * 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
 */
function onSubmit(type: string, id: string) {
  dialogConfirm($q, () => {
    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(async () => {
        await props.fecthlistInsignia?.();
        await props.close?.();
        await success($q, "บันทึกข้อมูลสำเร็จ");
        Datereceive.value = null;
        files.value = null;
        OrganazationId.value = "";
        Datereturn.value = null;
        filesReturn.value = null;
        OrganazationId2.value = "";
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * function เรียกหน่วยงาน
 */
async function fetchOrgList() {
  const newData = [
    {
      id: "00000000-0000-0000-0000-000000000000",
      name: "สำนักนายกรัฐมนตรี",
    },
  ];
  // OrgListMain.value = newData;
  // OrgList.value = newData;
  // OrgList2.value = newData;

  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then(async (res) => {
      const data = res.data.result;
      await http
        .get(config.API.orgByIdSystem(data.activeId, route.meta.Key as string))
        .then(async (res) => {
          const dataSystem = await res.data.result.map(
            (item: DataStructureTree) => ({
              id: item.orgTreeId,
              name: item.orgName,
            })
          );

          newData.push(...dataSystem);
          OrgListMain.value = newData;
          OrgList.value = newData;
          OrgList2.value = newData;
        })
        .catch((err) => {
          messageError($q, err);
        });
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function ค้นหาข้อมูลใน select
 * @param val คำค้นหา
 * @param update Function
 */
function filterOption(val: string, update: Function, type: string) {
  switch (type) {
    case "receive":
      update(() => {
        OrgList.value = OrgListMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "return":
      update(() => {
        OrgList2.value = OrgListMain.value.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
  }
}

/**
 * class inpui
 * @param val ค่าสถานะ
 */
function classInput(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

/**
 * callback function จะทำงานเมื่อ modal มีการเปลี่ยนแปลง
 */
watch(
  () => props.modal,
  async () => {
    if (props.modal == true) {
      await fetchOrgList();
    }
  }
);

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

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="width: 1200px; max-width: 200vw">
      <q-form
        greedy
        @submit.prevent
        @validation-success="
          onSubmit(
            props.dateCheckReceive === null ? 'receive' : 'return',
            props.personId as string
          )
        "
      >
        <DialogHeader :tittle="'รับ-คืนเครื่องราชฯ'" :close="close" />

        <q-separator />
        <q-card-section>
          <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:string) => !!val || 'กรุณาเลือกวันที่ได้รับ']"
                    hide-bottom-space
                    :model-value="
                      Datereceive != null ? date2Thai(Datereceive) : null
                    "
                    :label="`${'วันที่ได้รับ'}`"
                    :class="classInput(dateCheckReceive !== null)"
                    :readonly="dateCheckReceive !== 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="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:string) => val || 'กรุณาเลือกไฟล์หลักฐานการรับ']"
                hide-bottom-space
                :disable="dateCheckReceive !== null"
                class="inputgreen"
              >
                <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
                use-input
                v-model="OrganazationId"
                lazy-rules
                :label="`หน่วยงานที่รับ`"
                :rules="[(val:string) => !!val || 'กรุณาเลือกหน่วยงานที่รับ']"
                :class="classInput(dateCheckReceive !== null)"
                :readonly="dateCheckReceive !== null"
                @filter="(inputValue:string,
                doneFn:Function) => filterOption(inputValue, doneFn,'receive'
                ) "
              />
            </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
                    :rules="[(val:string) => !!val || 'กรุณาเลือกวันที่คืน']"
                    hide-bottom-space
                    :model-value="
                      Datereturn != null ? date2Thai(Datereturn) : undefined
                    "
                    :label="`${'วันที่คืน'}`"
                    clearable
                    @clear="clearReturnDate"
                    :class="classInput(dateCheckReturn !== null)"
                    :readonly="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:string) => val || 'กรุณาเลือกไฟล์หลักฐานการคืน']"
                hide-bottom-space
                :disable="dateCheckReturn !== null"
                class="inputgreen"
              >
                <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
                use-input
                :label="`หน่วยงานที่คืน`"
                :rules="[(val:string) => !!val || 'กรุณาเลือกหน่วยงานที่คืน']"
                :class="classInput(dateCheckReturn !== null)"
                :readonly="dateCheckReturn !== null"
                @filter="(inputValue:string,
                doneFn:Function) => filterOption(inputValue, doneFn,'return'
                
                ) "
              />
            </div>
          </div>
        </q-card-section>

        <q-separator v-if="dateCheckReturn === null" />
        <q-card-actions align="right">
          <q-btn
            v-if="dateCheckReturn === null"
            label="บันทึก"
            color="public"
            type="submit"
          >
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
