<script setup lang="ts">
import { ref, onMounted, watch } from "vue";

import config from "@/app.config";
import http from "@/plugins/http";
import { useDataStore } from "@/stores/data";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";

/**
 * importType
 */
import type { QTableProps } from "quasar";
import type {
  DataOption,
  NewPagination,
} from "@/modules/10_registry/interface/index/Main";
import type { DataRequest } from "@/modules/10_registry/interface/response/Main";

/**
 * importComponents
 */
import DialogAddRequestEdit from "@/modules/10_registry/components/DialogAddRequestEdit.vue";

/**
 * importStore
 */
import { useRequestEditStore } from "@/modules/10_registry/store/RequestEdit";
import { useCounterMixin } from "@/stores/mixin";

/**
 * use
 */
const $q = useQuasar();
const store = useRequestEditStore();
const link = ref<string>("");
const router = useRouter();
const dataStore = useDataStore();
const { showLoader, hideLoader, messageError, dialogRemove, success } =
  useCounterMixin();

/**
 * ตัวแปร
 */
const modalPetiton = ref<boolean>(false);
const status = ref<string>("");
const keyword = ref<string>("");
const statusOption = ref<DataOption[]>(store.optionStatus);

/**
 * Table
 */
const rows = ref<DataRequest[]>([]);
const page = ref<number>(1);
const pageSize = ref<number>(10);
const rowsTotal = ref<number>(0);
const maxPage = ref<number>(0);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: (row) => rows.value.indexOf(row) + 1,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "topic",
    align: "left",
    label: "ชื่อเรื่อง",
    sortable: false,
    field: "topic",
    format: (v) => (v ? v : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: false,
    field: "detail",
    format: (v) => (v ? v : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  // {
  //   name: "document",
  //   align: "center",
  //   label: "หลักฐานอ้างอิง",
  //   sortable: false,
  //   field: "document",
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  {
    name: "status",
    align: "left",
    label: "สถานะคำร้อง",
    sortable: false,
    field: "status",
    format: (v) => store.convertStatus(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ ",
    sortable: false,
    field: "remark",
    format: (v) => (v ? v : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "topic",
  "detail",
  // "document",
  "status",
  "remark",
]);

/**
 * function กลับไปหน้าทะเบียนประวัติ
 */
function onclickBackPage() {
  router.push(`/registry`);
}

/**
 * function กดเพิ่มรายการยื่นคำร้องขอแก้ไขข้อมูล
 */
function onClickAdd() {
  modalPetiton.value = true;
}

/**
 * function fetch รายการข้อมูลการยื่นคำร้องขอแก้ไขข้อมูล
 */
function fetchListRequset() {
  let queryParams = {
    page: page.value,
    pageSize: pageSize.value,
    status: status.value,
    keyword: keyword.value,
  };
  showLoader();
  http
    .get(config.API.requestEditByType(link.value) + `user`, {
      params: queryParams,
    })
    .then((res) => {
      const data = res.data.result;
      maxPage.value = Math.ceil(data.total / pageSize.value);
      rowsTotal.value = data.total;
      rows.value = data.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function เลือกสถานะคำร้อง
 */
function updateStatusValue() {
  page.value = 1;
  fetchListRequset();
}

/**
 * function เคลียร์ข้อมูลสถานะคำร้อง
 */
function clearStatus() {
  status.value = "";
  statusOption.value = store.optionStatus;
}

/**
 * function ค้นหาข้อมูลใน select
 * @param val คำค้นหา
 * @param update Function
 */
function filterOption(val: string, update: Function) {
  update(() => {
    status.value = val ? "" : status.value;
    statusOption.value = store.optionStatus.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

function updatePageSizePagination(newPagination: NewPagination) {
  page.value = 1;
  pageSize.value = newPagination.rowsPerPage;
}

/**
 * function หาชื่อไฟล์
 * @param id รายการยื่นคำร้องขอแก้ไขข้อมูล
 */
function onDownloadFile(id: string) {
  showLoader();
  http
    .get(
      config.API.file(
        "ระบบทะเบียนประวัติ",
        "เอกสารหลักฐานคำร้องขอแก้ไขข้อมูล",
        id
      )
    )
    .then((res) => {
      if (res.data.length !== 0) {
        downloadUrl(id, res.data[0].fileName);
      } else {
        hideLoader();
      }
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    });
}

/**
 * function  โหลดไฟล์
 * @param id  รายการยื่นคำร้องขอแก้ไขข้อมูล
 * @param fileName  ชื่อไฟล์
 */
function downloadUrl(id: string, fileName: string) {
  http
    .get(
      config.API.fileByFile(
        "ระบบทะเบียนประวัติ",
        "เอกสารหลักฐานคำร้องขอแก้ไขข้อมูล",
        id,
        fileName
      )
    )
    .then((res) => {
      window.open(res.data.downloadUrl, "_blank");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

// function onDeleteLidt(id: string) {
//   dialogRemove($q, () => {
//     showLoader();
//     http
//       .delete(config.API.requestEdit + `${id}`)
//       .then(async (res) => {
//         await fetchListRequset();
//         await success($q, "ลบข้อมูลสำเร็จ");
//       })
//       .catch((err) => {
//         messageError($q, err);
//         hideLoader();
//       });
//   });
// }

watch(
  () => pageSize.value,
  () => {
    fetchListRequset();
  }
);

onMounted(async () => {
  link.value = await dataStore.getProFileType();
  fetchListRequset();
});
</script>

<template>
  <div class="row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-11">
      <div class="toptitle text-white col-12 row items-center">
        <q-btn
          icon="mdi-arrow-left"
          unelevated
          round
          dense
          flat
          color="primary"
          class="q-mr-sm"
          @click="onclickBackPage"
        />
        รายการยื่นคำร้องขอแก้ไขข้อมูล
      </div>
      <q-card bordered class="q-pa-md">
        <div class="row q-mb-sm q-col-gutter-sm">
          <div class="col-12" v-if="!$q.screen.gt.sm">
            <q-btn
              flat
              round
              color="primary"
              icon="mdi-plus"
              @click="onClickAdd()"
            >
              <q-tooltip>ยื่นคำร้องขอแก้ไขข้อมูล</q-tooltip>
            </q-btn>
          </div>
          <div class="col-xs-12 col-md-2">
            <q-select
              v-model="status"
              label="สถานะคำร้อง"
              dense
              outlined
              emit-value
              map-options
              option-label="name"
              option-value="id"
              :options="statusOption"
              @update:model-value="updateStatusValue"
              :clearable="status !== ''"
              @clear="clearStatus"
              use-input
              @filter="(inputValue:string,
              doneFn:Function) => filterOption(inputValue, doneFn
              ) "
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div v-if="$q.screen.gt.sm">
            <q-btn
              flat
              round
              color="primary"
              icon="mdi-plus"
              @click="onClickAdd()"
            >
              <q-tooltip>ยื่นคำร้องขอแก้ไขข้อมูล</q-tooltip>
            </q-btn>
          </div>
          <q-space v-if="$q.screen.gt.sm" />
          <div class="col-xs-12 col-md-2">
            <q-input
              v-model="keyword"
              outlined
              clearable
              dense
              label="ค้นหา"
              @keydown.enter.prevent="updateStatusValue()"
            >
            </q-input>
          </div>
          <div class="col-xs-12 col-md-2">
            <q-select
              v-model="visibleColumns"
              multiple
              outlined
              dense
              options-dense
              :display-value="$q.lang.table.columns"
              emit-value
              map-options
              :options="columns"
              option-value="name"
              style="min-width: 140px"
            />
          </div>
        </div>
        <div class="col-12">
          <d-table
            :columns="columns"
            :rows="rows"
            row-key="id"
            :rows-per-page-options="[10, 25, 50, 100]"
            :paging="true"
            :visible-columns="visibleColumns"
            @update:pagination="updatePageSizePagination"
          >
            <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-th auto-width /> -->
              </q-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props" class="cursor-pointer">
                <q-td
                  v-for="col in props.cols"
                  :key="col.name"
                  :props="props"
                  @click.pervent="
                    router.push(`/registry/request-edit/${props.row.id}`)
                  "
                >
                  <div v-if="col.name == 'no'">
                    {{ props.rowIndex + 1 }}
                  </div>
                  <!-- <div v-else-if="col.name === 'document'">
                    <q-btn
                      icon="mdi-download"
                      round
                      dense
                      flat
                      color="primary"
                      size="12px"
                      @click.stop.pervent="onDownloadFile(props.row.id)"
                    >
                      <q-tooltip>หลักฐานอ้างอิง</q-tooltip>
                    </q-btn>
                  </div> -->
                  <div v-else class="table_ellipsis2">
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
                <!-- <q-td>
                  <q-btn
                    v-if="props.row.status === 'PENDING'"
                    flat
                    round
                    color="red"
                    icon="mdi-delete"
                    size="12px"
                    @click="onDeleteLidt(props.row.id)"
                  >
                    <q-tooltip>ลบคำร้องขอแก้ไขข้อมูล</q-tooltip>
                  </q-btn>
                </q-td> -->
              </q-tr>
            </template>
            <template v-slot:pagination="scope">
              ทั้งหมด {{ rowsTotal }} รายการ
              <q-pagination
                v-model="page"
                active-color="primary"
                color="dark"
                :max="Number(maxPage)"
                :max-pages="5"
                size="sm"
                boundary-links
                direction-links
                @update:model-value="fetchListRequset()"
              ></q-pagination>
            </template>
          </d-table>
        </div>
      </q-card>
    </div>
  </div>

  <DialogAddRequestEdit
    v-model:modal="modalPetiton"
    :fetchData="fetchListRequset"
  />
</template>

<style scoped></style>
