<script setup lang="ts">
import { reactive, ref, onMounted, computed, watch } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";

import type { RehabilitationForm } from "@/modules/05_leave/interface/request/AddAbsence";
import { useLeaveStore } from "@/modules/05_leave/store";
import http from "@/plugins/http";
import config from "@/app.config";
import genReport from "@/plugins/genreport";

const $q = useQuasar();
const dataStore = useLeaveStore();
const mixin = useCounterMixin();
const {
  date2Thai,
  calculateDurationYmd,
  messageError,
  showLoader,
  hideLoader,
  convertDateToAPI,
} = mixin;

const edit = ref<boolean>(true);
const isSave = ref<boolean>(false);
const leaveId = ref<any>("");
const leaveStartDateRef = ref<object | null>(null);
const leaveEndDateRef = ref<object | null>(null);
const leaveWroteRef = ref<object | null>(null);
const leaveText = ref<string>("");

/** รับ props มาจากหน้าหลัก */
const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
  onConfirm: {
    type: Function,
    default: () => "",
  },
  clickDelete: {
    type: Function,
    default: () => "",
  },
});

/** ข้อมูล v-model ของฟอร์ม */
const formDataRehabilitation = reactive<any>({
  type: dataStore.typeId,
  leaveWrote: "",
  leaveStartDate: null,
  leaveEndDate: null,
  leaveDocument: [],
  leaveDetail: "",
  leaveRange: "ALL",
  leaveRangeEnd: "ALL",
  leaveDraftDocument: null,
});

/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const formRef: RehabilitationForm = {
  leaveStartDate: leaveStartDateRef,
  leaveEndDate: leaveEndDateRef,
  leaveWrote: leaveWroteRef,
};

/** ฟังก์ชั่นตรวจสอบความถูกต้องก่อน บันทึก */
async function onValidate() {
  const formData = new FormData();
  if (formDataRehabilitation.leaveDocument.length > 0) {
    formDataRehabilitation.leaveDocument.forEach((file: File) => {
      formData.append("leaveDocument", file);
    });
  }

  if (formDataRehabilitation.leaveDraftDocument) {
    formData.append(
      "leaveDraftDocument",
      formDataRehabilitation.leaveDraftDocument
    );
  }

  formData.append("type", formDataRehabilitation.type); //
  formData.append(
    "leaveStartDate",
    convertDateToAPI(formDataRehabilitation.leaveStartDate) ?? ""
  );
  formData.append(
    "leaveEndDate",
    convertDateToAPI(formDataRehabilitation.leaveEndDate) ?? ""
  );
  formData.append("leaveWrote", formDataRehabilitation.leaveWrote); //
  formData.append("leaveDetail", formDataRehabilitation.leaveDetail); //
  formData.append("leaveTotal", formDataRehabilitation.leaveTotal); //

  formData.append("leaveRange", formDataRehabilitation.leaveRange);
  formData.append("leaveRangeEnd", formDataRehabilitation.leaveRangeEnd);
  props.onSubmit(formData, isLeave.value);
}

/** ส่วนของการประกาศและเลือกไฟล์เอกสารประกอบ */
const fileDocDataUpload = ref<File[]>([]);
const fileUploadDoc = async (files: any) => {
  files.forEach((file: any) => {
    fileDocDataUpload.value.push(file);
  });
};

const reasonLeave = ref<string>("");
const isLeave = ref<boolean>(true);

const checkDate = computed(() => {
  if (
    convertDateToAPI(formDataRehabilitation.leaveEndDate) ==
    convertDateToAPI(formDataRehabilitation.leaveStartDate)
  ) {
    return true;
  } else {
    return false;
  }
});

/**
 * check ว่าลาได้ไหม จาก api
 * @param formData
 */
//  const totalCheck = ref<number|null>(null)
async function fetchCheck() {
  if (
    formDataRehabilitation.leaveStartDate &&
    formDataRehabilitation.leaveEndDate
  ) {
    showLoader();
    await http
      .post(config.API.leaveCheck(), {
        type: dataStore.typeId ?? null,
        StartLeaveDate:
          convertDateToAPI(formDataRehabilitation.leaveStartDate) ?? null,
        EndLeaveDate:
          convertDateToAPI(formDataRehabilitation.leaveEndDate) ?? null,
        leaveRange: formDataRehabilitation.leaveRange,
        leaveRangeEnd: checkDate.value
          ? formDataRehabilitation.leaveRange
          : formDataRehabilitation.leaveRangeEnd,
      })
      .then((res: any) => {
        const data = res.data.result;
        isLeave.value = data.isLeave;
        formDataRehabilitation.leaveTotal = data.totalDate;
        // totalCheck.value = data.totalDate;
        leaveText.value = calculateDurationYmd(
          convertDateToAPI(formDataRehabilitation.leaveStartDate),
          convertDateToAPI(formDataRehabilitation.leaveEndDate)
        );

        reasonLeave.value = data.message
          ? data.message
          : "จำนวนวันลาเกินที่กำหนด";
      })
      .catch((e: any) => {
        messageError($q, e);
        // totalCheck.value = null
      })
      .finally(() => {
        hideLoader();
      });
  }
}

//download function
async function onClickDownloadFile(id: string, fileName: string) {
  showLoader();
  await http
    .get(config.API.leaveReport(id))
    .then(async (res) => {
      const data = res.data.result;
      await genReport(data, fileName);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** แจ้งเมื่อวันลาไม่ถูกต้อง */
const dateEndInputStyle = computed(() => {
  return !isLeave.value ? "input-alert" : "";
});

/** ตรวจสอบว่ามีการส่งข้อมูลเข้ามาที่ฟอร์มไหม เมื่อมีการส่งจะ map ข้อมูลเข้า v-model ของฟอร์ม */
const leaveDocumentList = ref<any>();
const leaveDraftDocument = ref<string>();
const statusCheck = ref<string>("");
watch(
  () => props.data,
  async () => {
    if (props.data) {
      // totalCheck.value = null;
      formDataRehabilitation.leaveWrote = props.data.leaveWrote;
      formDataRehabilitation.leaveStartDate = new Date(
        props.data.leaveStartDate
      );
      formDataRehabilitation.leaveEndDate = new Date(props.data.leaveEndDate);
      formDataRehabilitation.leaveDetail = props.data.leaveDetail;
      leaveDraftDocument.value = props.data.leaveDraftDocument;
      leaveDocumentList.value = props.data.leaveDocument;
      formDataRehabilitation.leaveRange = props.data.leaveRange;
      formDataRehabilitation.leaveRangeEnd = props.data.leaveRangeEnd;
      formDataRehabilitation.leaveDraftDocument = null;
      formDataRehabilitation.leaveDocument = [];
      statusCheck.value = props.data.status;
      const leaveTotal = await calculateDurationYmd(
        props.data.leaveStartDate,
        props.data.leaveEndDate
      );
      leaveText.value = leaveTotal;
    }
  }
);

/**Hook */
onMounted(async () => {
  if (props.data) {
    // totalCheck.value = null;
    formDataRehabilitation.leaveWrote = props.data.leaveWrote;
    formDataRehabilitation.leaveStartDate = new Date(props.data.leaveStartDate);
    formDataRehabilitation.leaveEndDate = new Date(props.data.leaveEndDate);
    formDataRehabilitation.leaveDetail = props.data.leaveDetail;

    formDataRehabilitation.leaveRange = props.data.leaveRange;
    formDataRehabilitation.leaveRangeEnd = props.data.leaveRangeEnd;

    leaveDraftDocument.value = props.data.leaveDraftDocument;
    leaveDocumentList.value = props.data.leaveDocument;
    statusCheck.value = props.data.status;
    leaveId.value = props.data.id;
    const leaveTotal = await calculateDurationYmd(
      props.data.leaveStartDate,
      props.data.leaveEndDate
    );
    leaveText.value = leaveTotal;

    fetchCheck();
  }
});
</script>

<template>
  <div style="display: flex; align-items: center">
    <q-icon name="mdi-numeric-3-circle" size="20px" color="primary" />
    <div class="q-pl-sm text-weight-bold text-dark">กรอกข้อมูล</div>
  </div>

  <q-form greedy @submit.prevent @validation-success="onValidate">
    <q-card bordered class="q-pa-md bg-grey-1">
      <div class="row q-pa-sm q-col-gutter-sm">
        <div class="col-12 col-sm-12 inputgreen">
          <q-input
            v-model="formDataRehabilitation.leaveWrote"
            ref="leaveWroteRef"
            dense
            outlined
            bg-color="white"
            label="เขียนที่"
            hide-bottom-space
            :readonly="!edit || statusCheck === 'NEW'"
            :rules="[(val:string) => !!val || `${'เขียนที่'}`]"
          />
        </div>

        <div class="col-12">
          <div class="row q-col-gutter-sm">
            <div class="col-12 col-md-3 col-sm-6 inputgreen">
              <datepicker
                v-model="formDataRehabilitation.leaveStartDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                borderless
                :enableTimePicker="false"
                week-start="0"
                :readonly="!edit || statusCheck === 'NEW'"
                @update:model-value="
                  (formDataRehabilitation.leaveEndDate = null), fetchCheck()
                "
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    outlined
                    dense
                    ref="leaveStartDateRef"
                    for="leaveStartDateRef"
                    hide-bottom-space
                    bg-color="white"
                    :readonly="!edit || statusCheck === 'NEW'"
                    class="full-width datepicker"
                    :model-value="
                      formDataRehabilitation.leaveStartDate != null
                        ? date2Thai(formDataRehabilitation.leaveStartDate)
                        : null
                    "
                    :label="`${'วันที่เริ่มต้น'}`"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวันที่เริ่มต้น'}`]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <!-- <div class="col-12 col-md-3 col-sm-6 inputgreen">
              <q-select
                outlined
                dense
                bg-color="white"
                v-model="formDataRehabilitation.leaveRange"
                :options="dataStore.rangeOptions"
                emit-value
                map-options
                option-value="id"
                option-label="name"
                @update:model-value="fetchCheck()"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="mdi-clock-outline"
                    style="color: var(--q-primary)"
                  />
                </template>
              </q-select>
            </div> -->
            <!-- </div>
        </div>
        <div class="col-12">
          <div class="row q-col-gutter-sm"> -->
            <div class="col-12 col-md-3 col-sm-6 inputgreen">
              <datepicker
                v-model="formDataRehabilitation.leaveEndDate"
                :locale="'th'"
                autoApply
                hide-bottom-space
                @update:model-value="fetchCheck()"
                borderless
                :enableTimePicker="false"
                week-start="0"
                :min-date="formDataRehabilitation.leaveStartDate"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    outlined
                    dense
                    ref="leaveEndDateRef"
                    for="leaveEndDateRef"
                    hide-bottom-space
                    bg-color="white"
                    class="full-width datepicker"
                    :model-value="
                      formDataRehabilitation.leaveEndDate != null
                        ? date2Thai(formDataRehabilitation.leaveEndDate)
                        : null
                    "
                    :label="`${'วันที่สิ้นสุด'}`"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวันที่สิ้นสุด'}`]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <!-- <div class="col-12 col-md-3 col-sm-6 inputgreen">
              <q-select
                v-if="!checkDate"
                outlined
                dense
                bg-color="white"
                v-model="formDataRehabilitation.leaveRangeEnd"
                :options="dataStore.rangeOptions.filter((items:any)=> items.id !== 'AFTERNOON')"
                emit-value
                map-options
                option-value="id"
                option-label="name"
                @update:model-value="fetchCheck()"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="mdi-clock-outline"
                    style="color: var(--q-primary)"
                  />
                </template>
              </q-select>
            </div> -->

            <div class="col-12 col-md-3 col-sm-6">
              <q-input
                :bottom-slots="!isLeave ? true : false"
                :color="!isLeave ? 'red' : 'black'"
                :bg-color="!isLeave ? 'red-2' : 'white'"
                :border-color="!isLeave ? 'red' : 'gray'"
                :input-class="!isLeave ? dateEndInputStyle : ''"
                dense
                outlined
                ref="leaveTotalRef"
                for="leaveTotalRef"
                v-model="leaveText"
                label="เป็นเวลา"
                readonly
              >
                <template v-slot:hint>
                  <span style="color: red">
                    {{ !isLeave ? reasonLeave : "" }}
                  </span>
                </template>
              </q-input>
            </div>
          </div>
        </div>

        <div class="col-12 col-md-12 col-sm-12 inputgreen">
          <q-input
            v-model="formDataRehabilitation.leaveDetail"
            :readonly="!edit || statusCheck === 'NEW'"
            bg-color="white"
            dense
            outlined
            type="textarea"
            label="สาเหตุการลา"
          />
        </div>

        <div class="col-12" v-if="statusCheck != 'NEW'">
          <q-file
            v-model="formDataRehabilitation.leaveDocument"
            @added="fileUploadDoc"
            multiple
            use-chips
            bg-color="white"
            dense
            outlined
            label="เอกสารประกอบ"
          >
            <template v-slot:prepend>
              <q-icon name="attach_file" color="primary" />
            </template>
          </q-file>
          <div class="col-12 q-mt-sm" v-if="data">
            <div class="col-12 col-md-12 col-sm-12">
              <q-card>
                <q-list separator>
                  <q-item
                    v-for="(document, index) in leaveDocumentList"
                    :key="index"
                    class="q-my-xs"
                  >
                    <q-item-section>
                      <q-item-label class="row items-baseline">
                        <div class="col">
                          {{ "เอกสารแนบที่ " + (index + 1) }}
                        </div>
                        <div>
                          <q-btn
                            :href="document.path"
                            target="_blank"
                            outline
                            flat
                            dense
                            color="blue"
                            icon="mdi-download"
                            size="12px"
                            class="q-mr-md"
                          >
                            <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
                          </q-btn>
                        </div>
                        <div>
                          <q-btn
                            @click="clickDelete(leaveId, document.docId)"
                            target="_blank"
                            outline
                            color="red"
                            flat
                            dense
                            icon="delete"
                            size="12px"
                          >
                            <q-tooltip>ลบไฟล์</q-tooltip>
                          </q-btn>
                        </div>
                      </q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-card>
            </div>
          </div>
        </div>
      </div>
    </q-card>

    <div v-if="data && data.id" class="q-mt-md">
      <div style="display: flex; align-items: center">
        <q-icon name="mdi-numeric-4-circle" size="20px" color="primary" />
        <div class="q-pl-sm text-weight-bold text-dark">
          ดาวน์โหลด/อัปโหลดแบบฟอร์ม
        </div>
      </div>
      <q-card class="bg-grey-1 q-pa-sm" bordered>
        <div class="row">
          <div class="col-sm-3 q-my-sm">
            <div class="column q-mx-xs">
              <!-- <div class="q-pl-sm text-weight-bold text-dark text-center">
                ดาวน์โหลด
              </div> -->
              <q-btn
                color="primary"
                icon="download"
                label="ดาวน์โหลดแบบฟอร์ม"
                @click="
                  onClickDownloadFile(data.id, `แบบฟอร์ม${data.leaveTypeName}`)
                "
              />
            </div>
          </div>
          <div class="col-sm-5 q-my-sm">
            <div class="column q-mx-xs">
              <!-- <div class="q-pl-sm text-weight-bold text-dark text-center">
                อัปโหลด
              </div> -->
              <q-file
                v-model="formDataRehabilitation.leaveDraftDocument"
                use-chips
                dense
                label="อัปโหลดแบบฟอร์ม"
                outlined
                bg-color="white"
                accept="application/pdf"
              >
                <template v-slot:prepend>
                  <q-icon name="attach_file" color="primary" />
                </template>
              </q-file>
            </div>
          </div>

          <div v-if="leaveDraftDocument" class="col-sm-2 q-my-sm">
            <div class="column q-mx-xs">
              <q-btn
                icon="visibility"
                color="blue"
                label="ดาวน์โหลดไฟล์"
                :href="leaveDraftDocument"
                target="_blank"
              />
            </div>
          </div>
        </div>
      </q-card>
    </div>

    <div v-if="!isSave">
      <q-separator class="q-mt-sm" />
      <div class="row col-12 q-pt-md">
        <q-space />
        <!-- <div v-if="totalCheck == 0" class="text-red q-mr-sm">**จำนวนวันลาของท่านไม่ถูกต้อง หรือวันที่ยื่นลาของท่านตรงกับวันหยุด</div> -->
        <q-btn
          v-if="!props.data || props.data.status == 'DRAFT'"
          id="onSubmit"
          type="submit"
          unelevated
          dense
          class="q-px-md items-center btnBlue"
          label="บันทึก"
          :disable="!isLeave"
          ><q-tooltip>บันทึกแบบร่าง</q-tooltip></q-btn
        >
        <q-btn
          v-if="data && statusCheck != 'NEW'"
          id="onSubmit"
          type="button"
          unelevated
          dense
          class="q-px-md items-center q-ml-sm"
          color="primary"
          label="ยื่นใบลา"
          @click="onConfirm()"
          ><q-tooltip>ยื่นใบลา</q-tooltip></q-btn
        >
      </div>
    </div>
  </q-form>
</template>
