<script setup lang="ts">
import { ref, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useQuasar } from "quasar";

import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useInsigniaReclaimStore } from "@/modules/07_insignia/storeReclaim";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableColumn } from "quasar";
import type { OptionData } from "@/modules/07_insignia/interface/index/Main";
import type {
  DataReclaim,
  DataRound,
} from "@/modules/07_insignia/interface/response/Reclaim";

import DialogForm from "@/modules/07_insignia/components/7_Reclaim/DialogForm.vue";

const $q = useQuasar();
const { roundData, insigniaTypeData, employeeClassData } = storeToRefs(
  useInsigniaReclaimStore()
);
const {
  showLoader,
  hideLoader,
  messageError,
  dialogRemove,
  success,
  date2Thai,
  onSearchDataTable,
} = useCounterMixin();

/**  Table*/
const rows = ref<DataReclaim[]>([]);
const rowsMain = ref<DataReclaim[]>([]);
const keyword = ref<string>("");
const columns = ref<QTableColumn[]>([
  {
    name: "noNumber",
    align: "left",
    label: "ลำดับ",
    field: "noNumber",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "citizenId",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "fullName",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "profileType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    field: "profileType",
    sortable: true,
    format(val, row) {
      return (
        employeeClassData.value.find((e) => e.id === val.toLowerCase())?.name ??
        ""
      );
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "insigniaType",
    align: "left",
    label: "ประเภทเครื่องราชฯ",
    field: "insigniaType",
    sortable: true,
    format(val, row) {
      return `${row.requestInsignia} (${row.requestInsigniaShortName})`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateReceive",
    align: "left",
    label: "วันที่ได้รับพระราชทาน",
    field: "dateReceive",
    sortable: true,
    format(val, row) {
      return date2Thai(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "date",
    align: "left",
    label: "วันที่ในราชกิจนุเบกษา",
    field: "date",
    sortable: true,
    format(val, row) {
      return date2Thai(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "volumeNo",
    align: "left",
    label: "เล่มที่ในราชกิจนุเบกษา",
    field: "volumeNo",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "section",
    align: "left",
    label: "ตอนที่ในราชกิจนุเบกษา",
    field: "section",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "page",
    align: "left",
    label: "หน้าในราชกิจนุเบกษา",
    field: "page",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "no",
    align: "left",
    label: "ลำดับที่ในราชกิจจานุเบกษา",
    field: "no",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "number",
    align: "left",
    label: "หมายเลขใบกำกับ",
    field: "number",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "typePayment",
    align: "left",
    label: "รูปแบบการจ่าย",
    field: "typePayment",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "reclaimDate",
    align: "left",
    label: "วันที่เรียกคืน",
    field: "reclaimDate",
    sortable: true,
    format(val, row) {
      return date2Thai(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "reclaimReason",
    align: "left",
    label: "หมายเหตุการเรียกคืน",
    field: "reclaimReason",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "noNumber",
  "citizenId",
  "fullName",
  "profileType",
  "insigniaType",
  "dateReceive",
  "date",
  "volumeNo",
  "section",
  "page",
  "no",
  "number",
  "typePayment",
  "reclaimDate",
  "reclaimReason",
]);

const isInsigniaRound = ref<boolean>(false); //สถานะรอบ

const roundOps = ref<DataRound[]>(roundData.value); //รอบเครืองราช
const insigniaTypeOps = ref<OptionData[]>(insigniaTypeData.value); //ประเภทเครื่องราช
const employeeClassOps = ref<OptionData[]>(employeeClassData.value); //ประเภทตำแหน่ง

const modalForm = ref<boolean>(false); // modal บันทึกการเรียกคืนเครื่องราชฯ
const isEdit = ref<boolean>(false); // สถานะการแก้ไข
const insigniaReclaimId = ref<string>(""); // ID รายการเรียกคืนเครื่องราชฯ
const insigniaReclaimData = ref<DataReclaim>(); //ข้อมูลรายการเรียกคืนเครื่องราชฯ

const yearRound = ref<number>(); //รอบการเสนอขอ
const insigniaType = ref<string>("all"); //ประเภทเครื่องราช
const employeeType = ref<string>("all"); //ตำแหน่งประเภม

/** function เรียกรอบการเสนอขอพระราชทานเครื่องราชฯ*/
async function fetchInsigniaRound() {
  roundData.value = [{ name: "ทั้งหมด", id: "all", year: 0 }];
  await http
    .get(config.API.noteround(), { params: { path: "BORROW" } })
    .then(async (res) => {
      let data = res.data.result;
      roundData.value.push(...data);
      roundOps.value = roundData.value;
      if (data.length > 0) {
        yearRound.value = data[0].year;
        isInsigniaRound.value = true;
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function เรียกประเภทเครื่องราชฯ*/
async function fetchInsigniaType() {
  insigniaTypeData.value = [{ name: "ทั้งหมด", id: "all" }];
  await http
    .get(config.API.insigniaOrg)
    .then(async (res) => {
      let data = res.data.result;
      const newOption = data.map((e: OptionData) => ({
        name: e.name,
        id: e.id,
      }));
      insigniaTypeData.value.push(...newOption);
      insigniaTypeOps.value = insigniaTypeData.value;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function เรียกข้อมูลรายการเรียกคืนเครื่องราชฯ*/
async function fetchDataReclaim() {
  await http
    .post(config.API.insigniaReclaim + `-list`, {
      year: yearRound.value,
    })
    .then((res) => {
      const data = res.data.result;
      rowsMain.value = data;
      rows.value = data;
      onSearchDataReclaim();
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * function เป็ด Dialog บันทึกการเรียกคืนเครื่องราชฯ
 * @param actions สถานะการแก่ไข
 * @param data  ข้อมูลของรายการที่ต้องการแก้ไข
 */
function onOpenDialogForm(
  actions: boolean,
  data: DataReclaim = {} as DataReclaim
) {
  isEdit.value = actions;
  insigniaReclaimId.value = actions ? data.id : "";
  insigniaReclaimData.value = data;
  modalForm.value = true;
}

/**
 * function ยืนยันการลบข้อมูลรายการเรียกคืนเครื่องราชฯ
 * @param id ที่ต้องการลบ
 */
function onDeleteDataReclaim(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.insigniaReclaim + `/${id}`)
      .then(async () => {
        await fetchDataReclaim();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** function ค้นหาข้อมูลใน Table*/
function onSearchDataReclaim() {
  if (insigniaType.value !== "all" && employeeType.value !== "all") {
    const data = rowsMain.value.filter(
      (e: DataReclaim) =>
        e.requestInsigniaId === insigniaType.value &&
        e.profileType === employeeType.value.toLocaleUpperCase()
    );
    rows.value = onSearchDataTable(
      keyword.value,
      data,
      columns.value ? columns.value : []
    );
  } else if (insigniaType.value !== "all" && employeeType.value === "all") {
    const data = rowsMain.value.filter(
      (e: DataReclaim) => e.requestInsigniaId === insigniaType.value
    );
    rows.value = onSearchDataTable(
      keyword.value,
      data,
      columns.value ? columns.value : []
    );
  } else if (insigniaType.value === "all" && employeeType.value !== "all") {
    const data = rowsMain.value.filter(
      (e: DataReclaim) =>
        e.profileType.toLocaleUpperCase() ===
        employeeType.value.toLocaleUpperCase()
    );
    rows.value = onSearchDataTable(
      keyword.value,
      data,
      columns.value ? columns.value : []
    );
  } else if (insigniaType.value === "all" && employeeType.value === "all") {
    rows.value = onSearchDataTable(
      keyword.value,
      rowsMain.value,
      columns.value ? columns.value : []
    );
  }
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 * @param name ชื่อ Selec
 */
function filterSelector(val: string, update: Function, name: string) {
  update(() => {
    const needle = val.toLowerCase();
    if (name === "employeeClassOps") {
      employeeClassOps.value = employeeClassData.value.filter(
        (v: OptionData) => v.name.toLowerCase().indexOf(needle) > -1
      );
    } else if (name === "fileterInsigniaList") {
      insigniaTypeOps.value = insigniaTypeData.value.filter(
        (v: OptionData) => v.name.toLowerCase().indexOf(needle) > -1
      );
    } else if (name === "filterSelectRoundAllOption") {
      roundOps.value = roundData.value.filter(
        (v: DataRound) => v.name.toLowerCase().indexOf(needle) > -1
      );
    }
  });
}

/** function เรียกข้อมูลรายการเรียกคืนเครื่องราชฯใหม่เมื่อเปลี่ยนรอบ*/
async function fetchNewData() {
  showLoader();
  await fetchDataReclaim();
  onSearchDataReclaim();
  hideLoader();
}

/** Hook*/
onMounted(async () => {
  try {
    showLoader();
    await Promise.allSettled([fetchInsigniaRound(), fetchInsigniaType()]);
    await fetchDataReclaim();
  } catch (error) {
    console.log(error);
  } finally {
    hideLoader();
  }
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    เรียกคืนเครื่องราชฯ
  </div>

  <q-card flat bordered class="q-pa-md" v-if="isInsigniaRound">
    <div class="row q-col-gutter-sm">
      <div class="col-12">
        <div class="row q-col-gutter-y-sm">
          <div class="row q-col-gutter-sm items-center">
            <q-select
              v-model="yearRound"
              dense
              outlined
              lazy-rules
              hide-bottom-space
              :label="`${'รอบการเสนอขอเครื่องราชฯ'}`"
              emit-value
              map-options
              use-input
              hide-selected
              fill-input
              option-label="name"
              :options="roundOps"
              option-value="year"
              style="width: 340px"
              @filter="(inputValue: string,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'filterSelectRoundAllOption'
              )"
              @update:model-value="fetchNewData()"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <q-space />
          <div class="row q-col-gutter-sm">
            <q-input
              standout
              dense
              v-model="keyword"
              outlined
              placeholder="ค้นหา"
              @keydown.enter.prevent="onSearchDataReclaim()"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>

            <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">
          <q-card bordered class="q-pa-sm col-12 bg-grey-1 q-mt-sm">
            <div class="row col-12 q-col-gutter-sm">
              <q-select
                v-model="insigniaType"
                dense
                outlined
                use-input
                hide-selected
                fill-input
                lazy-rules
                hide-bottom-space
                :label="`${'เครื่องราชฯ'}`"
                :options="insigniaTypeOps"
                emit-value
                map-options
                option-label="name"
                option-value="id"
                @update:model-value="onSearchDataReclaim"
                @filter="(inputValue: string,
    doneFn: Function) => filterSelector(inputValue, doneFn, 'fileterInsigniaList'
    )"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>

              <q-select
                class="col-2"
                v-model="employeeType"
                dense
                outlined
                lazy-rules
                hide-bottom-space
                :label="`${'ประเภทตำแหน่ง'}`"
                emit-value
                use-input
                hide-selected
                fill-input
                map-options
                :options="employeeClassOps"
                option-label="name"
                option-value="id"
                @update:model-value="onSearchDataReclaim"
                @filter="(inputValue: string,
                doneFn: Function) => filterSelector(inputValue, doneFn, 'employeeClassOps'
                )"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>

              <div>
                <q-btn
                  v-if="checkPermission($route)?.attrIsCreate"
                  flat
                  round
                  color="primary"
                  icon="mdi-plus"
                  @click.stop.prevent="onOpenDialogForm(false)"
                >
                  <q-tooltip>เพิ่ม</q-tooltip>
                </q-btn>
              </div>
            </div>
          </q-card>
        </div>
      </div>

      <div class="col-12">
        <d-table
          ref="table"
          :columns="columns"
          :rows="rows"
          flat
          bordered
          :paging="true"
          dense
          class="custom-header-table"
          :visible-columns="visibleColumns"
        >
          <!-- @update:pagination="updatePagination" -->
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width></q-th>
              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                style="color: #000000; font-weight: 500"
              >
                <span class="text-weight-medium">{{ col.label }}</span>
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td auto-width>
                <q-btn
                  v-if="
                    checkPermission($route)?.attrIsGet &&
                    checkPermission($route)?.attrIsUpdate
                  "
                  dense
                  flat
                  round
                  color="edit"
                  icon="edit"
                  @click.stop.prevent="onOpenDialogForm(true, props.row)"
                  ><q-tooltip>แก้ไขข้อมูล</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="checkPermission($route)?.attrIsDelete"
                  dense
                  flat
                  round
                  color="red"
                  icon="delete"
                  @click.stop.prevent="onDeleteDataReclaim(props.row.id)"
                  ><q-tooltip>ลบข้อมูล</q-tooltip>
                </q-btn>
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <div v-if="col.name === 'noNumber'">
                  {{ props.rowIndex + 1 }}
                </div>
                <div v-else>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
          <!-- <template v-slot:pagination="scope">
            ทั้งหมด {{ total.toLocaleString() }} รายการ
            <q-pagination
              v-model="formFilter.page"
              active-color="primary"
              color="dark"
              :max="Number(maxPage)"
              size="sm"
              boundary-links
              direction-links
              :max-pages="5"
              @update:model-value="onSearchData(false)"
            ></q-pagination>
          </template> -->
        </d-table>
      </div>
    </div>
  </q-card>

  <q-card v-else>
    <div class="q-pa-md q-gutter-sm">
      <q-banner inline-actions rounded class="bg-grey-1 text-center">
        ไม่มีข้อมูลรอบการเสนอขอพระราชทานเครื่องราชอิสริยาภรณ์
      </q-banner>
    </div>
  </q-card>

  <DialogForm
    v-model:modal="modalForm"
    :is-edit="isEdit"
    :insignia-reclaim-id="insigniaReclaimId"
    :fetch-data="fetchDataReclaim"
    :round-data="roundData"
    :insignia-reclaim-data="insigniaReclaimData"
  />
</template>

<style scoped></style>
