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

/** importType*/
import type { QTableProps } from "quasar";
import type { NewPagination } from "@/modules/13_salary/interface/index/Main";
import type { DataFilterPerson } from "@/modules/13_salary/interface/index/SalaryList";
import type { DataPersonReq } from "@/modules/13_salary/interface/request/SalaryList";
import type { DataPerson } from "@/modules/13_salary/interface/response/SalaryList";

/** importComponents*/
import Header from "@/components/DialogHeader.vue";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import { useSalaryListSDataStore } from "@/modules/13_salary/store/SalaryListsStore";

/** use*/
const $q = useQuasar();
const store = useSalaryListSDataStore();
const { messageError, showLoader, hideLoader, dialogConfirm, success } =
  useCounterMixin();

/** props*/
const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  fetchData: {
    type: Function,
  },
});

/** Table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    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: "position",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posType",
    align: "left",
    label: "ประเภทตำเเหน่ง",
    sortable: true,
    field: "posType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevel",
    align: "left",
    label: "ระดับตำเเหน่ง",
    sortable: true,
    field: "posLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const rows = ref<DataPerson[]>([]);

/** ข้อมูุลค้นหา*/
const formFilter = reactive<DataFilterPerson>({
  page: 1,
  pageSize: 10,
  keyword: "",
  rootId: "",
  year: 0,
  period: "",
});
const maxPage = ref<number>(1);

/** function close popup*/
function closeModal() {
  modal.value = false;
  formFilter.page = 1;
  formFilter.keyword = "";
}

/** function เรียกรายชื่อ คนเลื่อนเงินเดือน*/
function fetchListPerson() {
  showLoader();
  formFilter.rootId = store.rootId;
  formFilter.period = store.roundMainCode;
  formFilter.year = store.roundYear;
  http
    .post(config.API.salaryListPerson, formFilter)
    .then((res) => {
      const data = res.data.result.data;
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
      rows.value = data;
    })
    .catch((err) => {
      messageError($q, err);
      closeModal();
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function ยืนยันการเพิ่มคนเลื่อนเงินเดือน
 * @param data ข้อมูลคนที่เพิ่ม
 */
function onClickAddPerson(data: DataPerson) {
  const body: DataPersonReq = {
    id: store.groupId,
    type: store.tabType,
    ...data,
  };

  dialogConfirm(
    $q,
    () => {
      http
        .post(config.API.salaryPeriodProfile, body)
        .then(() => {
          props.fetchData?.();
          success($q, "เพื่มรายชื่อสำเร็จ");
          closeModal();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการเพิ่มรายชื่อ",
    "ต้องการยืนยันการเพิ่มรายชื่อนี้ใช่หรือไม่?"
  );
}

/** function updatePage*/
async function updatePagePagination() {
  fetchListPerson();
}

/** function updatePageSize*/
function updatePageSizePagination(newPagination: NewPagination) {
  formFilter.page = 1;
  formFilter.pageSize = newPagination.rowsPerPage;
}

/** function ค้นหาข้อมูลตาม keyword*/
function searchData() {
  formFilter.page = 1;
  fetchListPerson();
}

/** callblack function เรียกข้อมูลรายชื่อคนเลื่อนเงินเดือน เมื่อมีการเปิด Popup*/
watch(
  () => modal.value,
  () => {
    if (modal.value) {
      fetchListPerson();
    }
  }
);

/** callblack function เรียกข้อมูลรายชื่อคนเลื่อนเงินเดือน เมื่อมีการเปลี่ยน PageSize*/
watch(
  () => formFilter.pageSize,
  () => {
    updatePagePagination();
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="max-width: 100vw">
      <Header :tittle="'เพิ่มคนเลื่อนเงินเดือน'" :close="closeModal" />
      <q-separator />

      <q-card-section class="scroll" style="max-height: 70vh">
        <div class="row q-col-gutter-sm">
          <div class="col-12">
            <q-input
              borderless
              dense
              debounce="300"
              outlined
              placeholder="ค้นหา"
              v-model="formFilter.keyword"
              @keydown.enter.prevent="searchData"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
          </div>
          <div class="col-12">
            <d-table
              ref="table"
              :columns="columns"
              :rows="rows"
              row-key="id"
              flat
              bordered
              :paging="true"
              dense
              :rows-per-page-options="[10, 25, 50, 100]"
              @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-th>
                </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"
                  >
                    <div v-if="col.name === 'no'">
                      {{
                        (formFilter.page - 1) * formFilter.pageSize +
                        props.rowIndex +
                        1
                      }}
                    </div>
                    <div v-else-if="col.name === 'fullName'">
                      {{
                        `${props.row.prefix}${props.row.firstName}  ${props.row.lastName}`
                      }}
                    </div>
                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                  <q-td>
                    <q-btn
                      outline
                      color="primary"
                      label="เพิ่ม"
                      @click="onClickAddPerson(props.row)"
                    />
                  </q-td>
                </q-tr>
              </template>
              <template v-slot:pagination="scope">
                <q-pagination
                  v-model="formFilter.page"
                  active-color="primary"
                  color="dark"
                  :max="Number(maxPage)"
                  :max-pages="5"
                  size="sm"
                  boundary-links
                  direction-links
                  @update:model-value="updatePagePagination()"
                ></q-pagination>
              </template>
            </d-table>
          </div>
        </div>
      </q-card-section>
      <q-separator />

      <!-- <q-card-actions align="right" class="bg-white text-teal">
        <q-btn
          type="submit"
          unelevated
          dense
          class="q-px-md items-center"
          color="light-blue-10"
          label="บันทึก"
        />
      </q-card-actions> -->
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
