<script setup lang="ts">
import { ref, onMounted } 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";
import { useRequestEditStore } from "@/modules/10_registry/store/RequestEdit";
import { useCounterMixin } from "@/stores/mixin";

/**importType*/
import type { QTableProps } from "quasar";
import type { PropsTable } from "@/interface/PropsTable";
import type { DataOption } 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";

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

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

/** Table*/
const rows = ref<DataRequest[]>([]);
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: true,
    field: "topic",
    format: (v) => (v ? v : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    format: (v) => (v ? v : "-"),
    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: true,
    field: "remark",
    format: (v) => (v ? v : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "topic",
  "detail",
  // "document",
  "status",
  "remark",
]);
const pagination = ref<PropsTable.Pagination>({
  descending: true,
  page: 1,
  sortBy: "",
  rowsPerPage: 10,
  rowsNumber: 0,
});

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

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

/** function fetch รายการข้อมูลการยื่นคำร้องขอแก้ไขข้อมูล*/
async function fetchListRequset() {
  const queryParams = new URLSearchParams({
    page: pagination.value.page.toString(),
    pageSize: pagination.value.rowsPerPage.toString(),
    status: status.value,
    keyword: keyword.value,
  });

  if (pagination.value.sortBy) {
    queryParams.append("sortBy", pagination.value.sortBy);
    queryParams.append(
      "descending",
      pagination.value.descending ? "true" : "false"
    );
  }
  isLoading.value = true;
  await http
    .get(
      config.API.requestEditByType(link.value) +
        `user?${queryParams.toString()}`
    )
    .then((res) => {
      const result = res.data.result;
      pagination.value.rowsNumber = result.total;
      rows.value = result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoading.value = false;
    });
}

/** function เลือกสถานะคำร้อง*/
function updateStatusValue() {
  pagination.value.page = 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
    );
  });
}

/**
 * ฟังก์ชันรับ request จากตาราง เมื่อมีการเปลี่ยน pagination
 * @param requestProps ข้อมูลการร้องขอจากตาราง
 */
function onTableRequest(requestProps: PropsTable.RequestProps) {
  const newPagination = requestProps?.pagination || requestProps;
  if (!newPagination?.page || !newPagination?.rowsPerPage) return;
  pagination.value = { ...newPagination };
  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"
            v-model:pagination="pagination"
            :loading="isLoading"
            @request="onTableRequest"
          >
            <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 class="table_ellipsis2">
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </q-card>
    </div>
  </div>

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

<style scoped></style>
