<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue";
import { VuePDF, usePDF } from "@tato30/vue-pdf";
import type { PDFDocumentLoadingTask } from "pdfjs-dist/types/src/display/api";
import type { QForm } from "quasar";
import { useCounterMixin } from "@/stores/mixin";

const mixin = useCounterMixin();
const { date2Thai } = mixin;

const dialog = ref<boolean>(false);

// onUnmounted(() => {
//   window.removeEventListener("resize", (e: any) => {
//     myEventHandler(e);
//   });
// });

onMounted(async () => {
  //   window.addEventListener("resize", (e: any) => {
  //     myEventHandler(e);
  //   });

  const pdfData = usePDF("/src/assets/05_modules.pdf");

  setTimeout(() => {
    pdfSrc.value = pdfData.pdf.value;
    numOfPages.value = pdfData.pages.value;
  }, 1000);
});

// const myEventHandler = (e: any) => {
//   console.log("e", e.target.innerWidth);
//   if (vuePDFRef !== null) {
//     vuePDFRef.value.reload();
//   }
// };

const pdfSrc = ref<PDFDocumentLoadingTask | undefined>();
const numOfPages = ref<number>(0);
const page = ref<number>(1);
const vuePDFRef = ref<any>(null);

const myForm = ref<QForm | null>(null);

const props = defineProps({
  next: {
    type: Function,
    default: () => console.log("not function"),
  },
  previous: {
    type: Function,
    default: () => console.log("not function"),
  },
});

const next = () => props.next();
const previous = () => props.previous();

const splitterModel = ref<number>(70);
const tab = ref<string>("main");
const fileOrder = ref<any>(null);
const fileTailer = ref<any>(null);

const order = ref<string>("");
const years = ref<number>(new Date().getFullYear());
const date = ref<Date>(new Date());

const onchangePage = (val: any) => {
  //   console.log(val);
  if (vuePDFRef !== null) {
    vuePDFRef.value.reload();
  }
};

const save = () => {
  if (myForm.value !== null) {
    myForm.value!.validate().then((success: Boolean) => {
      if (success) {
        // yay, models are correct
      }
    });
  }
};

const validateForm = () => {
  return (
    fileOrder.value !== null &&
    fileTailer.value !== null &&
    order.value.trim() !== ""
  );
};

const getClass = (val: boolean) => {
  return {
    "card-header-active q-px-lg q-py-md cursor-pointer": val,
    "card-header q-px-lg q-py-md cursor-pointer": !val,
  };
};

const setTab = (val: string) => {
  tab.value = val;
  page.value = 1;
};
</script>

<template>
  <div>
    <div style="min-height: 70vh">
      <q-splitter
        v-model="splitterModel"
        style="height: 70vh"
        @update:model-value="onchangePage"
      >
        <template v-slot:before>
          <div class="space">
            <div @click="setTab('main')" :class="getClass(tab == 'main')">
              <div class="q-pr-sm">คำสั่ง</div>
              <q-btn
                size="12px"
                flat
                dense
                icon="mdi-download"
                :disable="tab !== 'main'"
                :color="tab !== 'main' ? 'grey' : 'add'"
              >
                <q-tooltip>ดาวน์โหลด</q-tooltip>
                <q-menu>
                  <q-list style="min-width: 150px">
                    <q-item clickable v-close-popup>
                      <q-item-section avatar
                        ><q-icon color="red" name="mdi-file-pdf"
                      /></q-item-section>
                      <q-item-section>ไฟล์ .PDF</q-item-section>
                    </q-item>
                    <q-item clickable v-close-popup>
                      <q-item-section avatar
                        ><q-icon color="blue" name="mdi-file-word"
                      /></q-item-section>
                      <q-item-section>ไฟล์ .docx</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </q-btn>
            </div>
            <div @click="setTab('second')" :class="getClass(tab == 'second')">
              <div class="q-pr-sm">เอกสารแนบท้าย</div>
              <q-btn
                size="12px"
                flat
                dense
                :color="tab !== 'second' ? 'grey' : 'add'"
                icon="mdi-download"
                :disable="tab !== 'second'"
              >
                <q-tooltip>ดาวน์โหลด</q-tooltip>
                <q-menu>
                  <q-list style="min-width: 150px">
                    <q-item clickable v-close-popup>
                      <q-item-section avatar
                        ><q-icon color="red" name="mdi-file-pdf"
                      /></q-item-section>
                      <q-item-section>ไฟล์ .PDF</q-item-section>
                    </q-item>
                    <q-item clickable v-close-popup>
                      <q-item-section avatar
                        ><q-icon color="green-7" name="mdi-file-excel"
                      /></q-item-section>
                      <q-item-section>ไฟล์ .xls</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </q-btn>
            </div>
            <q-space />
            <q-btn
              class="text-dark"
              flat
              dense
              icon="mdi-fullscreen"
              color="add"
              @click="dialog = true"
            />
          </div>
          <q-separator style="margin-top: -1px; z-index: 1" />
          <q-card bordered class="card-pdf q-ma-md q-pa-md">
            <div class="justify-between items-center align-center q-pb-sm row">
              <q-btn
                class="text-dark bg-grey-4"
                flat
                dense
                @click="page = page > 1 ? page - 1 : page"
              >
                <q-icon name="mdi-chevron-left" />
              </q-btn>

              <span class="body-2 grey--text">
                หน้าที่ {{ page }} จาก {{ numOfPages }}
              </span>

              <q-btn
                class="text-dark bg-grey-4"
                flat
                dense
                @click="page = page < numOfPages ? page + 1 : page"
              >
                <q-icon name="mdi-chevron-right" />
              </q-btn>
            </div>
            <div class="pdfWidth">
              <VuePDF ref="vuePDFRef" :pdf="pdfSrc" :page="page" fit-parent />
              <!-- <VuePdf :key="page" :src="pdfSrc" :page="page" /> -->
            </div>
            <div class="justify-between items-center align-center q-pt-sm row">
              <q-btn
                class="text-dark bg-grey-4"
                flat
                dense
                @click="page = page > 1 ? page - 1 : page"
              >
                <q-icon name="mdi-chevron-left" />
              </q-btn>

              <span class="body-2 grey--text">
                หน้าที่ {{ page }} จาก {{ numOfPages }}
              </span>

              <q-btn
                class="text-dark bg-grey-4"
                flat
                dense
                @click="page = page < numOfPages ? page + 1 : page"
              >
                <q-icon name="mdi-chevron-right" />
              </q-btn>
            </div>
          </q-card>
        </template>

        <template v-slot:separator>
          <q-avatar
            color="primary"
            text-color="white"
            size="30px"
            icon="drag_indicator"
          />
        </template>

        <template v-slot:after>
          <q-form ref="myForm">
            <div class="q-pa-md q-gutter-y-md">
              <fieldset class="border q-px-lg q-py-md">
                <legend class="text-header q-px-sm">อัปโหลดไฟล์</legend>
                <div class="q-gutter-y-md q-mb-md">
                  <div>
                    <label class="text-file">คำสั่ง</label>
                    <q-file
                      outlined
                      dense
                      v-model="fileOrder"
                      label="เลือกไฟล์คำสั่ง"
                      hide-bottom-space
                      lazy-rules
                      :rules="[(val) => val || 'กรุณาเลือกไฟล์เอกสารแนบท้าย']"
                    >
                      <template v-slot:prepend>
                        <q-icon name="attach_file" />
                      </template>
                    </q-file>
                  </div>
                  <div>
                    <label class="text-file">เอกสารแนบท้าย</label>
                    <q-file
                      outlined
                      dense
                      v-model="fileTailer"
                      label="เลือกไฟล์เอกสารแนบท้าย"
                      hide-bottom-space
                      lazy-rules
                      :rules="[(val) => val || 'กรุณาเลือกไฟล์เอกสารแนบท้าย']"
                    >
                      <template v-slot:prepend>
                        <q-icon name="attach_file" />
                      </template>
                    </q-file>
                  </div>
                </div>
              </fieldset>

              <fieldset class="border q-px-lg q-py-md">
                <legend class="text-header q-px-sm">รายละเอียด</legend>
                <div class="q-gutter-y-md q-mb-md">
                  <div>
                    <label class="text-file">เลขที่คำสั่ง</label>
                    <q-input
                      :outlined="true"
                      dense
                      lazy-rules
                      :readonly="!true"
                      :borderless="!true"
                      v-model="order"
                      :rules="[(val) => !!val || `${'กรุณากรอกเลขที่คำสั่ง'}`]"
                      hide-bottom-space
                      :label="`${'เลขที่คำสั่ง'}`"
                    />
                  </div>
                  <div>
                    <label class="text-file">ปีที่ออกคำสั่ง</label>
                    <datepicker
                      menu-class-name="modalfix"
                      v-model="years"
                      :locale="'th'"
                      autoApply
                      year-picker
                      :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
                          lazy-rules
                          :model-value="years + 543"
                          :rules="[
                            (val) => !!val || `${'กรุณาเลือกปีที่ออกคำสั่ง'}`,
                          ]"
                          hide-bottom-space
                          :label="`${'ปีที่ออกคำสั่ง'}`"
                        >
                          <template v-slot:prepend>
                            <q-icon
                              name="event"
                              class="cursor-pointer"
                              style="color: var(--q-grey)"
                            >
                            </q-icon>
                          </template>
                        </q-input>
                      </template>
                    </datepicker>
                  </div>
                  <div>
                    <label class="text-file">วันที่ลงนาม</label>
                    <datepicker
                      menu-class-name="modalfix"
                      v-model="date"
                      :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="full-width datepicker"
                          hide-bottom-space
                          :model-value="date != null ? date2Thai(date) : null"
                          :label="`${'วันที่มีผลออกคำสั่ง'}`"
                          :rules="[
                            (val) =>
                              !!val || `${'กรุณาเลือกวันที่มีผลออกคำสั่ง'}`,
                          ]"
                        >
                          <template v-slot:prepend>
                            <q-icon
                              name="event"
                              class="cursor-pointer"
                              style="color: var(--q-grey)"
                            >
                            </q-icon>
                          </template>
                        </q-input>
                      </template>
                    </datepicker>
                  </div>
                </div>
              </fieldset>
              <div class="flex justify-around">
                <q-btn
                  unelevated
                  label="ออกคำสั่ง"
                  :color="validateForm() ? 'public' : 'grey'"
                  :disable="!validateForm()"
                />
                <q-btn
                  class="text-dark"
                  unelevated
                  label="ส่งไปลงนาม"
                  color="grey"
                  disable
                />
              </div>
            </div>
          </q-form>
        </template>
      </q-splitter>
    </div>
    <q-separator />
    <div class="flex justify-end q-pa-sm q-gutter-sm">
      <q-btn
        dense
        outline
        color="primary"
        icon="chevron_left"
        @click="previous"
        class="q-pr-md"
        label="เลือกรายชื่อส่งสำเนา"
      >
      </q-btn>
      <q-btn
        unelevated
        label="บันทึก"
        :color="validateForm() ? 'public' : 'grey'"
        :disable="!validateForm()"
        @click="save"
      >
      </q-btn>

      <!-- <q-btn flat round color="primary" icon="chevron_right" @click="next">
          <q-tooltip>ต่อไป</q-tooltip>
        </q-btn> -->
    </div>

    <q-dialog
      v-model="dialog"
      persistent
      :maximized="true"
      transition-show="slide-up"
      transition-hide="slide-down"
    >
      <q-card class="bg-white text-white">
        <!-- <q-bar>
            <q-space />
  
            <q-btn dense flat icon="close" v-close-popup>
              <q-tooltip>ปิดหน้าต่าง</q-tooltip>
            </q-btn>
          </q-bar> -->

        <div class="flex justify-end items-center align-center q-mr-md q-mt-sm">
          <q-btn
            icon="close"
            unelevated
            round
            dense
            style="color: #ff8080; background-color: #ffdede"
            size="12px"
            v-close-popup
          />
        </div>
        <q-card-section bordered class="card-pdf q-ma-md q-pa-md">
          <div class="justify-between items-center align-center q-pb-sm row">
            <q-btn
              class="text-dark bg-grey-4"
              flat
              dense
              @click="page = page > 1 ? page - 1 : page"
            >
              <q-icon name="mdi-chevron-left" />
            </q-btn>

            <span class="body-2 grey--text text-black">
              หน้าที่ {{ page }} จาก {{ numOfPages }}
            </span>

            <q-btn
              class="text-dark bg-grey-4"
              flat
              dense
              @click="page = page < numOfPages ? page + 1 : page"
            >
              <q-icon name="mdi-chevron-right" />
            </q-btn>
          </div>
          <div class="pdfWidth">
            <VuePDF
              ref="vuePDFRef"
              :pdf="pdfSrc"
              :page="page"
              fit-parent
              :scale="0.1"
            />
            <!-- <VuePdf :key="page" :src="pdfSrc" :page="page" /> -->
          </div>
          <div class="justify-between items-center align-center q-pt-sm row">
            <q-btn
              class="text-dark bg-grey-4"
              flat
              dense
              @click="page = page > 1 ? page - 1 : page"
            >
              <q-icon name="mdi-chevron-left" />
            </q-btn>

            <span class="body-2 grey--text text-black">
              หน้าที่ {{ page }} จาก {{ numOfPages }}
            </span>

            <q-btn
              class="text-dark bg-grey-4"
              flat
              dense
              @click="page = page < numOfPages ? page + 1 : page"
            >
              <q-icon name="mdi-chevron-right" />
            </q-btn>
          </div>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<style lang="scss" scoped>
.border {
  border-radius: 10px;
  border: 1px solid #e9eaec;
}
.text-header {
  color: #34373c;
  font-size: 1rem;
  font-weight: 300;
}

.text-file {
  padding-top: 5px;
  color: #34373c;
  font-weight: 500;
}

.space {
  background-color: #e9eaec61;
  display: flex;
  z-index: 3;
}

.card-header {
  margin-top: 5px;
  background-color: transparent;
  padding: 2px !important;
  border-radius: 10px 10px 0px 0px;
  width: 200px;
  display: flex;
  justify-content: center;
  font-weight: normal;
  align-items: center;
}

.card-header-active {
  margin-top: 5px;
  margin-left: -1px;
  background-color: white;
  padding: 2px !important;
  border-radius: 10px 10px 0px 0px;
  border: 1px solid #e9eaec;
  width: 200px;
  display: flex;
  justify-content: center;
  border-bottom-style: none;
  font-weight: 600;
  align-items: center;
}

.card-pdf {
  border-radius: 10px;
  border: 1px solid #e9eaec;
  background-color: #e9eaec61;
  //   height: 60vh;
}
</style>
