<script setup lang="ts">
import { ref, watch, computed } 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 { DataFilter } from "@/modules/13_salary/interface/index/SalaryList";

/** importComponents*/
import DialogAddPerson from "@/modules/13_salary/components/SalaryLists//DialogAddPerson.vue";
import DialogFormEdit from "@/modules/13_salary/components/SalaryLists/DialogFormEdit.vue";
import DialogMoveGroup from "@/modules/13_salary/components/SalaryLists/DialogMoveGroup.vue";
import DialogMoveLevel from "@/modules/13_salary/components/SalaryLists/DialogMoveLevel.vue";

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

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

/** props*/
const formFilter = defineModel<DataFilter>("formFilter", { required: true });
const maxPage = defineModel<Number>("maxPage", { required: true });
const props = defineProps({
  rows: { type: Array },
  fetchDataTable: {
    type: Function,
  },
  total: {
    type: Number,
  },
});

/** ข้อมูล Table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posNo",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: true,
    field: "posNo",
    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: false,
    field: "posType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevel",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: false,
    field: "posLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posExecutive",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: false,
    field: "posExecutive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "amount",
    align: "left",
    label: "เงินเดือนฐาน",
    sortable: false,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "amountUse",
    align: "left",
    label: "จำนวนเงินที่ใช้เลื่อน",
    sortable: false,
    field: "amountUse",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "positionSalaryAmount",
    align: "left",
    label: "เงินเดือนหลังเลื่อน",
    sortable: false,
    field: "positionSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isRetired",
    align: "center",
    label: "เกษียณอายุ",
    sortable: false,
    field: "isRetired",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const visibleColumns = ref<string[]>([
  "no",
  "posNo",
  "fullName",
  "position",
  "posType",
  "posLevel",
  "posExecutive",
  "amount",
  "amountUse",
  "positionSalaryAmount",
  "isRetired",
]);

/** modalDialog*/
const modalDialogAddPerson = ref<boolean>(false);
const modalDialogForm = ref<boolean>(false);
const modalDialogMoveGroup = ref<boolean>(false);
const modalDialogMoveLeve = ref<boolean>(false);

const profileId = ref<string>("");
const amount = ref<number>(0);

/** function openPopup เพิ่มคนเลื่อนเงินเดือน*/
function onClickAddPerson() {
  modalDialogAddPerson.value = !modalDialogAddPerson.value;
}

/**
 * function openPopup แก้ไขเงินเดือน
 * @param id profileId
 * @param amountSalary จำนวนเงินเดือน
 *
 */
function onClickEdit(id: string, amountSalary: number) {
  profileId.value = id;
  amount.value = amountSalary;
  modalDialogForm.value = !modalDialogForm.value;
}

/**
 * function openPopup ย้ายกลุ่ม
 * @param id profileId
 *
 */
function onClickMovieGroup(id: string) {
  profileId.value = id;
  modalDialogMoveGroup.value = !modalDialogMoveGroup.value;
}

const typeLevel = ref<string>("");
const isReserve = ref<boolean>(false);
/**
 * function openPopup ย้ายกขั้น
 * @param id profileId
 *
 */
function onClickMoveLevel(id: string, typeVal: string, isReserveVal: boolean) {
  profileId.value = id;
  modalDialogMoveLeve.value = !modalDialogMoveLeve.value;
  typeLevel.value = typeVal;
  isReserve.value = isReserveVal;
}

/**
 * function ยืนยันการลบรายชื่อ
 *  @param id profileId
 */
function onClickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.salaryListPeriodProfileById(id))
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
        props.fetchDataTable?.();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** function updatePageTable*/
function updatePagePagination() {
  props.fetchDataTable?.();
}

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

/** function ค้นหาข้อมูล Table*/
function searchData() {
  formFilter.value.page = 1;
  props.fetchDataTable?.();
}

/** callblack function เรียกข้อมูลรายชื่อใหม่ เมื่อมีการเปลี่ยน PageSize*/
watch(
  () => formFilter.value.pageSize,
  () => {
    updatePagePagination();
  }
);
</script>
<template>
  <q-toolbar class="text-primary" style="padding: 0px">
    <q-btn
      v-if="!store.isClosedRound"
      flat
      round
      dense
      icon="add"
      @click="onClickAddPerson"
    >
      <q-tooltip>เพิ่ม</q-tooltip>
    </q-btn>
    <q-space />
    <q-input
      borderless
      dense
      debounce="300"
      outlined
      v-model="formFilter.keyword"
      placeholder="ค้นหา"
      @keydown.enter.prevent="searchData"
    >
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>
    <q-select
      for="#select"
      v-model="visibleColumns"
      multiple
      outlined
      dense
      options-dense
      :display-value="$q.lang.table.columns"
      emit-value
      map-options
      :options="
        store.roundMainCode === 'OCT'
          ? columns
          : columns
          ? columns.slice(0, 10)
          : []
      "
      option-value="name"
      options-cover
      style="min-width: 150px"
      class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
    />
  </q-toolbar>

  <d-table
    ref="table"
    :columns="
      store.roundMainCode === 'OCT'
        ? columns
        : columns
        ? columns.slice(0, 10)
        : []
    "
    :rows="props.rows"
    row-key="id"
    flat
    bordered
    :paging="true"
    dense
    :rows-per-page-options="[10, 25, 50, 100]"
    :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-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"
          :class="
            store.tabType !== 'RETIRE'
              ? props.row.isNext == true
                ? 'text-red'
                : ''
              : ''
          "
        >
          <div v-if="col.name === 'no'">
            {{
              (formFilter.page - 1) * formFilter.pageSize +
              props.rowIndex +
              1 +
              (store.tabType == "FULL" && props.row.isReserve == true
                ? " (สำรอง)"
                : "")
            }}
          </div>
          <div v-else-if="col.name === 'posNo'">
            {{ `${props.row.orgShortName}${props.row.posMasterNo}` }}
          </div>
          <div v-else-if="col.name === 'fullName'">
            {{
              `${props.row.prefix}${props.row.firstName}  ${props.row.lastName}`
            }}
          </div>
          <div v-else-if="col.name === 'amount'">
            {{
              props.row.amount !== null ? props.row.amount.toLocaleString() : ""
            }}
          </div>
          <div v-else-if="col.name === 'amountUse'">
            {{
              props.row.amountUse !== null
                ? props.row.amountUse.toLocaleString()
                : ""
            }}
            {{
              props.row.amountSpecial > 0
                ? `(${props.row.amountSpecial.toLocaleString()})`
                : ""
            }}
          </div>
          <div v-else-if="col.name === 'positionSalaryAmount'">
            {{
              props.row.positionSalaryAmount !== null
                ? props.row.positionSalaryAmount.toLocaleString()
                : ""
            }}
            {{
              props.row.amountSpecial > 0
                ? `(${props.row.amountSpecial.toLocaleString()})`
                : ""
            }}
          </div>

          <div v-else-if="col.name === 'isRetired'">
            <q-icon
              name="check"
              color="primary"
              size="24px"
              v-if="props.row.isRetired && store.roundMainCode === 'OCT'"
            />
          </div>

          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td>
          <q-btn
            v-if="!store.isClosedRound"
            flat
            dense
            icon="mdi-dots-vertical"
            class="q-pa-none q-ml-xs"
            color="grey-13"
            size="12px"
          >
            <q-menu>
              <q-list dense style="min-width: 150px">
                <q-item
                  v-for="(item, index) in store.roundCode !== 'SPECIAL' ? store.itemMenu.filter((x:any)=>x.type !== 'properties') :store.itemMenu.filter((x:any)=>x.type !== 'moveGroup' && x.type !== 'properties')"
                  :key="index"
                  clickable
                  v-close-popup
                  @click="
                    item.type === 'edit'
                      ? onClickEdit(props.row.id, props.row.amount)
                      : item.type === 'moveGroup'
                      ? onClickMovieGroup(props.row.id)
                      : item.type === 'moveLevel'
                      ? onClickMoveLevel(
                          props.row.id,
                          props.row.type,
                          props.row.isReserve
                        )
                      : item.type === 'delete'
                      ? onClickDelete(props.row.id)
                      : null
                  "
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon
                        :color="item.color"
                        size="17px"
                        :name="item.icon"
                      />
                      <div class="q-pl-md">{{ item.label }}</div>
                    </div>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-menu>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:pagination="scope">
      ทั้งหมด {{ props.total }} รายการ
      <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>

  <DialogAddPerson
    v-model:modal="modalDialogAddPerson"
    :fetchData="props.fetchDataTable"
  />

  <DialogFormEdit
    v-model:modal="modalDialogForm"
    v-model:profileId="profileId"
    v-model:amount="amount"
    :fetchData="props.fetchDataTable"
  />
  <DialogMoveGroup
    v-model:modal="modalDialogMoveGroup"
    v-model:profileId="profileId"
    :group="store.tabGroup === 'group1' ? 'กลุ่ม1' : 'กลุ่ม2'"
    :fetchData="props.fetchDataTable"
  />
  <DialogMoveLevel
    :typeLevel="typeLevel"
    :isReserve="isReserve"
    v-model:modal="modalDialogMoveLeve"
    v-model:profileId="profileId"
    :fetchData="props.fetchDataTable"
    :type="store.tabType"
  />
</template>

<style scoped></style>
