<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/** import Type*/
import type { QTableProps, QForm } from "quasar";
import type { TypeData } from "@/modules/07_insignia/interface/index/Main";

/** import Stores */
import { useCounterMixin } from "@/stores/mixin";
/** useStore*/
const mixin = useCounterMixin();
const { success, messageError, hideLoader, dialogConfirm, showLoader } = mixin;

const $q = useQuasar();
const myForm = ref<any>();

const fileUpload = ref<any>(null);
const reason = ref<string>("");
const documentTitle = ref<string>("");
const filterKeyword = ref<string>("");
const filterDoc = ref<any>(null);

/** คอลัมน์ตาราง*/
const colums2 = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    field: "no",
    sortable: false,
  },
  {
    name: "fileName",
    align: "left",
    label: "ชื่อเอกสาร",
    field: "fileName",
    sortable: true,
  },
  {
    name: "annotation",
    align: "left",
    label: "หมายเหตุ",
    field: "annotation",
    sortable: true,
  },
  {
    name: "file",
    align: "left",
    label: "ไฟล์เอกสาร",
    field: "file",
    sortable: false,
  },
]);
const visibleColumnsReference = ref<String[]>([
  "no",
  "fileName",
  "annotation",
  "file",
]);
const rows2 = ref<any>([]);

const props = defineProps({
  roundId: {
    type: String,
  },
});

/** function ดึงข้อมูลรายการเอกสารอ้างอิง */
async function getRequest() {
  showLoader();
  await http
    .get(config.API.requestDocNote(props.roundId as string))
    .then((res: any) => {
      const data = res.data.result;
      rows2.value = [];
      data.map((item: TypeData) => {
        rows2.value.push({
          fileName: item.fileName,
          annotation: item.reason,
          file: item.pathName,
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เช็คฟอร์มก่อนบันทึก และยืนยันการบันทึกข้อมูล */
function save() {
  myForm.value.validate().then((result: boolean) => {
    if (result) {
      dialogConfirm($q, () => putRequest());
    }
  });
}

/** function  บันทึกเอกสาร */
async function putRequest() {
  showLoader();
  const dataAppend = new FormData();
  dataAppend.append("Name", documentTitle.value);
  dataAppend.append("Reason", reason.value);
  dataAppend.append("File", fileUpload.value);
  await http
    .put(config.API.requestDocNote(props.roundId as string), dataAppend)
    .then(() => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      documentTitle.value = "";
      reason.value = "";
      fileUpload.value = null;

      // reset เพื่อไม่ให้ฟอร์มแจ้งเตือ validate หลังบันทึกเสร็จแล้วล้างค่าฟิลด์ต่างๆ
      myForm.value.reset();
      getRequest();
      hideLoader();
    });
}

/** function  resetFilter */
function resetFilterRef() {
  filterKeyword.value = "";
  filterDoc.value.focus();
}

const pagination = ref({
  sortBy: "filename",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

/**hook*/
onMounted(async () => {
  await getRequest();
});
</script>

<template>
  <Transition>
    <div class="rounded-borders q-pa-md q-mb-md">
      <div class="row col-12">
        <q-card bordered class="col-12 q-pa-sm q-mb-sm">
          <q-form ref="myForm">
            <div class="row col-12 q-col-gutter-x-sm">
              <div class="col-3">
                <q-file
                  class="bg-white"
                  outlined
                  dense
                  v-model="fileUpload"
                  label="ไฟล์เอกสาร"
                  hide-bottom-space
                  lazy-rules
                  accept=".pdf"
                  :rules="[(val) => !!val || `กรุณาเลือกไฟล์เอกสาร`]"
                >
                  <template v-slot:prepend>
                    <q-icon name="attach_file" color="primary" />
                  </template>
                </q-file>
              </div>
              <div class="col-3">
                <q-input
                  class="bg-white"
                  outlined
                  dense
                  lazy-rules
                  v-model="documentTitle"
                  :label="`${'ชื่อเอกสาร'}`"
                  hide-bottom-space
                  :rules="[(val) => !!val || `กรุณากรอกชื่อเอกสาร`]"
                />
              </div>
              <div class="col-6 row no-wrap">
                <q-input
                  class="bg-white full-width"
                  outlined
                  dense
                  lazy-rules
                  v-model="reason"
                  :label="`${'หมายเหตุ'}`"
                  hide-bottom-space
                />
                <q-btn
                  unelevated
                  dense
                  class="q-ml-sm q-px-md items-center"
                  color="public"
                  label="บันทึก"
                  @click="save"
                />
              </div>
            </div>
          </q-form>
        </q-card>
        <div class="row col-12">
          <q-space />
          <q-input
            class="col-xs-12 col-sm-3 col-md-2"
            standout
            dense
            v-model="filterKeyword"
            ref="filterDoc"
            outlined
            debounce="300"
            placeholder="ค้นหา"
          >
            <template v-slot:append>
              <q-icon v-if="filterKeyword == ''" name="search" />
              <q-icon
                v-if="filterKeyword !== ''"
                name="clear"
                class="cursor-pointer"
                @click="resetFilterRef"
              />
            </template>
          </q-input>

          <q-select
            v-model="visibleColumnsReference"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="colums2"
            option-value="name"
            options-cover
            style="min-width: 150px"
            class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
          />
        </div>
        <div class="col-12 q-pt-sm">
          <d-table
            :columns="colums2"
            :rows="rows2"
            :filter="filterKeyword"
            row-key="fileName"
            :visible-columns="visibleColumnsReference"
            v-model:pagination="pagination"
          >
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  <span class="text-weight-medium">{{ col.label }}</span>
                </q-th>
              </q-tr>
            </template>

            <template v-slot:body="props">
              <q-tr :props="props" class="cursor-pointer">
                <q-td key="no" :props="props">
                  {{ props.rowIndex + 1 }}
                </q-td>
                <q-td key="fileName" :props="props">
                  {{ props.row.fileName }}
                </q-td>
                <q-td key="annotation" :props="props">
                  {{
                    props.row.annotation !== null ? props.row.annotation : "-"
                  }}
                </q-td>
                <q-td auto-width>
                  <q-btn
                    type="a"
                    :href="props.row.file"
                    target="_blank"
                    dense
                    size="14px"
                    flat
                    round
                    color="deep-orange-6"
                    icon="picture_as_pdf"
                  >
                    <q-tooltip>ดาว์โหลด PDF</q-tooltip>
                  </q-btn>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
        <div class="col-xs-12 col-md-9"></div>
        <div class="col-xs-12 col-md-3 flexsave"></div>
      </div>
    </div>
  </Transition>
</template>

<style scoped></style>
