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

import { useCounterMixin } from "@/stores/mixin";
import { useSalaryListSDataStore } from "@/modules/13_salary/store/SalaryListsStore";
import { usePagination } from "@/composables/usePagination";
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";

/** use*/
const $q = useQuasar();
const store = useSalaryListSDataStore();
const { messageError, showLoader, hideLoader, dialogConfirm, success } =
  useCounterMixin();
const { pagination, params, onRequest } = usePagination("", fetchListPerson);

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

/** Table*/
const rows = ref<DataPerson[]>([]);
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: "firstName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "fullName",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "orgShortName",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.orgShortName && row.posMasterNo
        ? `${row.orgShortName} ${row.posMasterNo}`
        : "-";
    },
  },
  {
    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 formFilter = reactive<DataFilterPerson>({
  keyword: "",
  rootId: "",
  year: 0,
  period: "",
});

/**
 * function close popup
 */
function closeModal() {
  modal.value = false;
  formFilter.keyword = "";
  rows.value = [];
  pagination.value = {
    page: 1,
    rowsPerPage: 10,
    sortBy: "",
    descending: false,
  };
}

/**
 * function เรียกรายชื่อ คนเลื่อนเงินเดือน
 */
async function fetchListPerson() {
  showLoader();
  formFilter.rootId = store.rootId;
  formFilter.period = store.roundMainCode;
  formFilter.year = store.roundYear;

  const body = {
    ...params.value,
    ...formFilter,
  };
  await http
    .post(config.API.salaryListPerson, body)
    .then((res) => {
      const result = res.data.result;
      pagination.value.rowsNumber = result.total;
      rows.value = result.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,
    () => {
      showLoader();
      http
        .post(config.API.salaryPeriodProfile, body)
        .then(async () => {
          await props.fetchData?.();
          await success($q, "เพื่มรายชื่อสำเร็จ");
          closeModal();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการเพิ่มรายชื่อ",
    "ต้องการยืนยันการเพิ่มรายชื่อนี้ใช่หรือไม่?"
  );
}

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

/** callblack function เรียกข้อมูลรายชื่อคนเลื่อนเงินเดือน เมื่อมีการเปิด Popup*/
watch(
  () => modal.value,
  () => {
    if (modal.value) {
      fetchListPerson();
    }
  }
);
</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
              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">
            <p-table
              ref="table"
              :columns="columns"
              :rows="rows"
              row-key="id"
              flat
              bordered
              :paging="true"
              dense
              :rows-per-page-options="[10, 25, 50, 100]"
              v-model:pagination="pagination"
              :onRequest="onRequest"
            >
              <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"
                  >
                    <span class="text-weight-medium">{{ col.label }}</span>
                  </q-th>
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td>
                    <q-btn
                      outline
                      color="primary"
                      label="เพิ่ม"
                      @click="onClickAddPerson(props.row)"
                    />
                  </q-td>
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    <div v-if="col.name === 'no'">
                      {{ props.rowIndex + 1 }}
                    </div>
                    <div v-else-if="col.name === 'firstName'">
                      {{
                        `${props.row.prefix}${props.row.firstName}  ${props.row.lastName}`
                      }}
                    </div>
                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
            </p-table>
          </div>
        </div>
      </q-card-section>
      <q-separator />
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
