<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="roundCoin"
                  label="รอบการเสนอขอพระราชทานเหรียญจักรพรรดิมาลา"
                  :options="options"
                  option-value="value"
                  option-label="label"
                  @update:model-value="updateDateRange"
                />
                <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
                >
                  <!-- :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>
<script setup lang="ts">
import type { QTableProps } from "quasar";
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, success, dateToISO, messageError, showLoader, hideLoader } =
  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 roundCoin = 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();
    console.log(id.value);

    await http
      .get(config.API.getRoundInsignia(id.value))
      .then((res) => {
        const data = res.data.result;
        //   const files = res.data.result.files;
        id.value = data.period_id;
        roundCoin.value = data.period_name;
        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 routeName = router.currentRoute.value.name;

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

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

const uploadDocData = async () => {
  const formData = new FormData();
  if (fileDocDataUpload.value.length > 0) {
    fileDocDataUpload.value.forEach((file: any) => {
      formData.append("", file);
    });
    showLoader();
    await http
      .put(config.API.RoundInsignia(id.value), formData)
      .then((res) => {})
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        hideLoader();
        success($q, "บันทึกข้อมูลสำเร็จ");
        clickBack();
      });
  } else {
    success($q, "บันทึกข้อมูลสำเร็จ");
    clickBack();
  }
};

const editData = async (id: string) => {
  const formData = new FormData();
  formData.append("Name", roundCoin.value);
  formData.append("year", parseInt(yearly.value).toString());
  formData.append("amount", datelast.value.toString());
  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 () => {
      await uploadDocData();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      clickBack();
    });
  console.log(formData);
};

const checkSave = 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 sendData = () => {
//   const valueData: any = {
//     Name: roundInsig.value,
//     year: year.value,
//     Amount: datelast.value,
//     dateStart: dateStart.value !== null ? dateToISO(dateStart.value) : null,
//     dateEnd: dateEnd.value !== null ? dateToISO(dateEnd.value) : null,
//   };
//   return valueData;
// };
const updateDateRange = () => {
// console.log("test")
  if (roundCoin.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 (roundCoin.value.value == 2) {
    dateStart.value = new Date(new Date().getFullYear(), 3, 29);
    dateEnd.value = new Date(new Date().getFullYear() + 1, 6, 28);
    console.log(2)
  }
};
const addData = async () => {
  const formData = new FormData();
  formData.append("name", roundCoin.value);
  formData.append("year", parseInt(yearly.value).toString());
  formData.append("amount", datelast.value.toString());
  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[0]);
  //   console.log(formData);
  formData.append("file", files.value);
  showLoader();
  await http
    .post(config.API.listRoundInsignia("coin"), formData)
    .then(async (res) => {})
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      clickBack();
    });
};

const clickBack = () => {
  router.push({ name: "coinProposals" });
};
</script>
