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

/** importType*/
import type { QTableProps } from "quasar";
import type {
  ListData,
  ResponseData,
} from "@/modules/13_salary/interface/index/EmployeeChart";
import type {
  NewPagination,
  DataOption,
} from "@/modules/13_salary/interface/index/Main";
import type { PosType } from "@/modules/13_salary/interface/response/salaryEmployeeChart";

/** importCompopnents*/
import DialogFormCriteria from "@/modules/13_salary/components/02_salaryEmployee/DialogFormCriteria.vue";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

const $q = useQuasar();
const { dialogRemove, messageError, showLoader, hideLoader, success } =
  useCounterMixin();

/** ข้อมูล Table*/
const rows = ref<ListData[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "name",
    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: "posName",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "posName",
    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",
  },
  {
    name: "rateOldMin",
    align: "left",
    label: "อัตราค่าจ้าง ขั้นต่ำสุด",
    sortable: true,
    field: "rateOldMin",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "groupOld",
    align: "left",
    label: "อัตราค่าจ้าง กลุ่มบัญชีค่าจ่าง",
    sortable: true,
    field: "groupOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "rateMaxOld",
    align: "left",
    label: "อัตราค่าจ้าง ขั้นสูงสุดเดิม",
    sortable: true,
    field: "rateMaxOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "groupRateHigh",
    align: "left",
    label: "อัตราค่าจ้างสูงกว่า ฯ กลุ่มบัญชีค่าจ่าง",
    sortable: true,
    field: "groupRateHigh",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "rateHighMax",
    align: "left",
    label: "อัตราค่าจ้างสูงกว่า ฯ ขั้นสูงใหม่",
    sortable: true,
    field: "rateHighMax",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "reson",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "reson",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "posType",
  "posName",
  "posLevel",
  "rateOldMin",
  "groupOld",
  "rateMaxOld",
  "groupRateHigh",
  "rateHighMax",
  "reson",
]);
const formFilter = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
});
const maxPage = ref<number>(1); //จำนวนหน้า
const totalList = ref<number>(0); //จำนวนรายการ

const modalForm = ref<boolean>(false); //Popup ข้อมูลหลักเกณฑ์
const isStatusEdit = ref<boolean>(false); //สถานะการแก้ไข
const actionsType = ref<string>("");
const dataRow = ref<ListData>(); //ข้อมูลที่ต้องการแก้ไข

const posTypeOpMain = ref<DataOption[]>([]); //ข้อมูลกลุ่มงาน
const posTypeOp = ref<DataOption[]>([]); //ตัวเลือกข้อมูลรายการกลุ่มงาน
const posType = ref<string | null>(""); //กลุ่มงาน

/**
 * ดึงข้อมูลกลุ่มงาน
 */
function getPosType() {
  http
    .get(config.API.salaryEmployeePosType())
    .then((res) => {
      const data = res.data.result;
      const option = [
        {
          id: "",
          name: "ทั้งหมด",
        },
      ];
      const test = data.map((item: PosType) => ({
        id: item.id,
        name: item.posTypeName,
      }));

      option.push(...test);
      posTypeOp.value = option;
      posTypeOpMain.value = option;
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/**
 * ดึงข้อมูลรายการหลักเกณฑ์
 */
function getData() {
  showLoader();
  http
    .get(
      config.API.salaryFormula() +
        `/?page=${formFilter.page}&pageSize=${formFilter.pageSize}&keyword=${formFilter.keyword.trim()}&posTypeId=${posType.value}`
    )
    .then((res) => {
      const data = res.data.result.data;
      totalList.value = res.data.result.total;
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
      rows.value = data.map((item: ResponseData) => ({
        id: item.id,
        posType: item.posType,
        posName: item.position,
        posLevel: item.posLevel,
        rateOldMin: item.salaryMin,
        groupOld: item.salaryEmployeeMin.sort((a, b) => a - b),
        rateMaxOld: item.salary,
        groupRateHigh: `กลุ่มที่ ${item.group}`,
        rateHighMax: item.salaryMax,
        reson: item.details,
      }));
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * เปิด dialog แก้ไขหลักเกณฑ์
 * @param params
 */
function editPopup(params: ListData, type: string) {
  actionsType.value = type;
  modalForm.value = true;
  isStatusEdit.value = true;
  dataRow.value = params;
}

/**
 * function fetch ข้อมูลรายการตามหน้า
 * @param val หน้า
 */
function updatePage(val: number) {
  formFilter.page = val;
  getData();
}

/**
 * function อัปเดทแถวต่อหน้า
 */
function updatePageSize(newPagination: NewPagination) {
  formFilter.page = 1;
  formFilter.pageSize = newPagination.rowsPerPage;
}

/**
 * ลบรายการหลักเกณฑ์
 * @param id หลักเกณฑ์
 */
function onClickDelete(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.salaryFormula() + `/${id}`)
      .then(async () => {
        await getData();
        await success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * function ค้นหาคำใน select
 * @param val คำค้นหา
 * @param update function
 */
function filterSelector(val: string, update: Function) {
  update(() => {
    posTypeOp.value = posTypeOpMain.value.filter(
      (v: DataOption) => v.name.toLowerCase().indexOf(val) > -1
    );
  });
}

/**
 * callbackFuntioon ทำงานเมื่อมี่การอัปเดทแถว
 */
watch(
  () => formFilter.pageSize,
  () => {
    getData();
  }
);

/**
 * functionn fetch ข้อมูลรายการหน้าแรก
 */
function filterFn() {
  formFilter.page = 1;
  getData();
}

const pagination = ref({
  page: formFilter.page,
  rowsPerPage: formFilter.pageSize,
});

onMounted(async () => {
  await Promise.all([getData(), getPosType()]);
});
</script>

<template>
  <q-toolbar class="text-primary" style="padding: 0px">
    <div class="col-3">
      <q-select
        v-model="posType"
        label="กลุ่มงาน"
        outlined
        dense
        :options="posTypeOp"
        option-label="name"
        option-value="id"
        emit-value
        map-options
        hide-selected
        fill-input
        use-input
        @update:model-value="filterFn"
        @filter="(inputValue: string,
            doneFn: Function) => filterSelector(inputValue, doneFn )"
      >
        <template v-if="posType" v-slot:append>
          <q-icon
            name="cancel"
            @click.stop.prevent="
              posType = '';
              filterFn();
            "
            class="cursor-pointer"
          />
        </template>
        <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
      dense
      icon="add"
      @click="() => (modalForm = true)"
    >
      <q-tooltip>เพิ่ม </q-tooltip>
    </q-btn>
    <q-space />
    <q-input
      borderless
      dense
      outlined
      v-model="formFilter.keyword"
      placeholder="ค้นหา"
      @keydown.enter.pervrnt="filterFn"
    >
      <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="columns"
      option-value="name"
      style="min-width: 140px"
      class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
    />
  </q-toolbar>

  <d-table
    flat
    bordered
    dense
    :rows="rows"
    :columns="columns"
    row-key="name"
    class="custom-header-table"
    v-model:pagination="pagination"
    :rows-per-page-options="[10, 20, 50, 100]"
    :visible-columns="visibleColumns"
    @update:pagination="updatePageSize"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width />
        <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>
      <q-separator />
    </template>
    <template v-slot:body="props">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            v-if="checkPermission($route)?.attrIsGet"
            flat
            round
            dense
            icon="mdi-eye"
            color="info"
            @click="editPopup(props.row, 'view')"
          >
            <q-tooltip>รายละเอียด</q-tooltip>
          </q-btn>
          <q-btn
            v-if="
              checkPermission($route)?.attrIsGet &&
              checkPermission($route)?.attrIsUpdate
            "
            flat
            round
            dense
            icon="edit"
            color="edit"
            @click="editPopup(props.row, 'edit')"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>

          <q-btn
            v-if="checkPermission($route)?.attrIsDelete"
            flat
            round
            dense
            icon="mdi-delete"
            color="red"
            @click.stop="onClickDelete(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 === 'no'">
            {{
              (formFilter.page - 1) * Number(pagination.rowsPerPage) +
              props.rowIndex +
              1
            }}
          </div>
          <div
            v-else-if="
              col.name == 'rateOldMin' ||
              col.name == 'rateMaxOld' ||
              col.name == 'rateHighMax'
            "
          >
            {{ col.value ? col.value.toLocaleString() : "-" }}
          </div>
          <div v-else-if="col.name == 'groupOld'">
            <span v-for="(item, index) in col.value">
              {{ item ? `กลุ่มที่ ${item}` : ""
              }}{{ index + 1 == col.value.length ? "" : "," }}
            </span>
          </div>
          <div v-else>{{ col.value != "" ? col.value : "-" }}</div>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:pagination="scope">
      ทั้งหมด {{ totalList }} รายการ
      <q-pagination
        v-model="formFilter.page"
        active-color="primary"
        color="dark"
        :max="maxPage"
        :max-pages="5"
        size="sm"
        boundary-links
        direction-links
        @update:model-value="updatePage"
      ></q-pagination>
    </template>
  </d-table>

  <DialogFormCriteria
    v-model:modal="modalForm"
    v-model:isStatusEdit="isStatusEdit"
    :data="dataRow"
    :get-data-Main="getData"
    :actionsType="actionsType"
  />
</template>

<style scoped></style>
