<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar, QForm } from "quasar";
import { useRouter, useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

const mixin = useCounterMixin();
const {
  date2Thai,
  dateToISO,
  messageError,
  showLoader,
  hideLoader,
  dialogConfirm,
  success,
} = mixin;
const router = useRouter();
const route = useRoute();
const $q = useQuasar();
const id = ref<string>(route.params.id as string);
const myForm = ref<QForm | null>(null); //form data input
const edit = ref<boolean>(false);
const dateStart = ref<Date>(new Date());
const dateEnd = ref<Date>(new Date());
const yearly = ref<number>(new Date().getFullYear());
const files = ref<any>();
const fileDocDataUpload = ref<File[]>([]);
const roundInsig = ref<any>();
const datelast = ref<number>(1);
const options = ref([
  { label: "รอบการเสนอขอพระราชทานเครื่องราชรอบที่ 1", value: 1 },
  { label: "รอบการเสนอขอพระราชทานเครื่องราชรอบที่ 2", value: 2 },
]);
onMounted(async () => {
  await fetchData();
});
const fetchData = async () => {
  if (route.params.id) {
    edit.value = true;
    showLoader();
    await http
      .get(config.API.getRoundInsignia(id.value))
      .then((res) => {
        const data = res.data.result;
        id.value = data.period_id;
        roundInsig.value =
          options.value.filter((r: any) => r.value == data.period_round)
            .length > 0
            ? options.value.filter((r: any) => r.value == data.period_round)[0]
            : null;
        yearly.value = data.period_year;
        datelast.value = data.period_amount;
        dateStart.value = new Date(data.period_start);
        dateEnd.value = new Date(data.period_end);
        files.value = data.period_doc;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};

const fileUploadDoc = async (files: any) => {
  files.forEach((file: any) => {
    fileDocDataUpload.value.push(file);
  });
};

const updateYear = async (e: number) => {
  yearly.value = e;
};

const editData = async (id: string) => {
  const formData = new FormData();
  const name = `รอบการเสนอขอพระราชทานเครื่องราชรอบที่ ${
    roundInsig.value.value
  } ปี ${yearly.value + 543}`;
  formData.append("name", name);
  formData.append("year", yearly.value.toString());
  formData.append("amount", datelast.value.toString());
  formData.append("round", roundInsig.value.value);
  if (dateStart.value !== null) {
    formData.append("startDate", dateToISO(dateStart.value));
  }
  if (dateEnd.value !== null) {
    formData.append("endDate", dateToISO(dateEnd.value));
  }
  formData.append("file", files.value);
  console.log(formData);
  showLoader();
  await http
    .put(config.API.editRoundInsignia(id), formData)
    .then(async () => {})
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      clickBack();
    });
  console.log(formData);
};
const checkSave = () => {
  dialogConfirm($q, () => SaveData());
};
const SaveData = async () => {
  if (myForm.value !== null) {
    myForm.value.validate().then(async (success) => {
      if (success) {
        if (edit.value) {
          await editData(id.value);
        } else {
          await addData();
          clickBack();
        }
      }
    });
  }
};
const updateDateRange = () => {
  if (roundInsig.value.value == 1) {
    dateStart.value = new Date(new Date().getFullYear(), 9, 1);
    dateEnd.value = new Date(new Date().getFullYear() + 1, 3, 29);
    console.log(1);
  } else if (roundInsig.value.value == 2) {
    dateStart.value = new Date(new Date().getFullYear(), 3, 29);
    dateEnd.value = new Date(new Date().getFullYear(), 4, 29);
    console.log(2);
  }
};

const addData = async () => {
  const formData = new FormData();
  const name = `รอบการเสนอขอพระราชทานเครื่องราชรอบที่ ${
    roundInsig.value.value
  }  ปี ${yearly.value + 543} `;
  console.log(name);
  formData.append("name", name);
  formData.append("year", yearly.value.toString());
  formData.append("amount", datelast.value.toString());
  formData.append("round", roundInsig.value.value);
  if (dateStart.value !== null) {
    formData.append("startDate", dateToISO(dateStart.value));
  }
  if (dateEnd.value !== null) {
    formData.append("endDate", dateToISO(dateEnd.value));
  }
  formData.append("file", files.value);

  showLoader();
  await http
    .post(config.API.listRoundInsignia(), formData)
    .then(() => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
};

const clickBack = () => {
  router.push({ name: "insigniaProposals" });
};
</script>
<template>
  <div class="col-xs-12 col-sm-12 col-md-11">
    <div class="toptitle col-12 row items-center">
      <q-btn
        icon="mdi-arrow-left"
        unelevated
        round
        dense
        flat
        color="primary"
        class="q-mr-sm"
        @click="clickBack"
      />
      {{
        edit
          ? "รอบการเสนอขอพระราชทานเครื่องราชอิสริยาภรณ์"
          : "เพิ่มรอบการเสนอขอพระราชทานเครื่องราชอิสริยาภรณ์"
      }}
    </div>
    <q-form ref="myForm">
      <div class="col-12">
        <q-card bordered>
          <div class="col-12 row q-col-gutter-md q-pa-md">
            <div class="col-xs-12 col-sm-12 row">
              <q-separator />
              <div class="col-12 row q-pa-sm q-col-gutter-sm">
                <q-select
                  class="col-10"
                  dense
                  outlined
                  v-model="roundInsig"
                  :options="options"
                  option-value="value"
                  option-label="label"
                  label="รอบการเสนอขอพระราชทานเครื่องราชฯ"
                  @update:model-value="updateDateRange"
                  :rules="[(val) => !!val || `${'กรุณาเลือกรอบที่'}`]"
                />
                <datepicker
                  menu-class-name="modalfix"
                  v-model="yearly"
                  class="col-2"
                  :locale="'th'"
                  autoApply
                  year-picker
                  :enableTimePicker="false"
                  @update:modelValue="updateYear"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      dense
                      lazy-rules
                      outlined
                      :model-value="yearly + 543"
                      :rules="[(val) => !!val || `${'กรุณาเลือกปีที่เสนอ'}`]"
                      :label="`${'ปีที่เสนอ'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
                <datepicker
                  menu-class-name="modalfix"
                  v-model="dateStart"
                  :locale="'th'"
                  autoApply
                  class="col-xs-12 col-sm-5"
                  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
                      outlined
                      dense
                      class="full-width datepicker"
                      :model-value="
                        dateStart != null ? date2Thai(dateStart) : null
                      "
                      :label="`${'วันเริ่มต้น'}`"
                      :rules="[(val) => !!val || `${'กรุณาเลือกวันเริ่มต้น'}`]"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
                <datepicker
                  menu-class-name="modalfix"
                  v-model="dateEnd"
                  class="col-xs-12 col-sm-5"
                  :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
                      outlined
                      dense
                      class="col-xs-12 col-sm-4"
                      :model-value="dateEnd != null ? date2Thai(dateEnd) : null"
                      :label="`${'วันสิ้นสุด'}`"
                      :rules="[
                        (val) => !!val || `${'กรุณาเลือกวันที่วันสิ้นสุด'}`,
                      ]"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>

                <q-input
                  class="col-xs-12 col-sm-2"
                  dense
                  outlined
                  v-model="datelast"
                  label="จำนวนวันแจ้งเตือนก่อนวันสิ้นสุด"
                />
                <q-file
                  class="col-xs-12 col-sm-10"
                  outlined
                  dense
                  v-model="files"
                  @added="fileUploadDoc"
                  label="อัปโหลดเอกสารประกอบ"
                  hide-bottom-space
                  lazy-rules
                  accept=".pdf,.xlsx,.doc"
                >
                  <!-- :rules="[
                    (val) => val || 'กรุณาเลือกไฟล์หนังสือถึงหน่วยงานที่รับโอน',
                  ]" -->
                  <template v-slot:prepend>
                    <q-icon name="attach_file" />
                  </template>
                </q-file>
              </div>
            </div>
          </div>
          <q-separator />
          <q-separator />
          <div class="row col-12 q-pa-sm">
            <q-space />
            <q-btn
              unelevated
              dense
              class="q-px-md items-center"
              color="light-blue-10"
              label="บันทึก"
              @click="checkSave"
            />
          </div>
        </q-card>
      </div>
    </q-form>
  </div>
</template>
