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

/**
 * importType
 */
import type { QTableProps } from "quasar";
import type {
  NewPagination,
  ItemsMenu,
} from "@/modules/13_salary/interface/index/Main";
import type { SalaryRate } from "@/modules/13_salary/interface/response/Main";
import type { FormQuerySalary } from "@/modules/13_salary/interface/request/Main";

/**
 * importComponents
 */
import DialogFormRate from "@/modules/13_salary/components/SalaryChart/DialogFormRate.vue";

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

/** use*/
const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const { dialogRemove, success, messageError, showLoader, hideLoader } =
  useCounterMixin();

const isActive = ref<boolean>(false);
const posType = ref<string>("");

const salaryId = ref<string>(route.params.id.toString());

/** modalDialog*/
const modalDialogFormRate = ref<boolean>(false);

/** Table*/
const rows = ref<SalaryRate[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "salary",
    align: "left",
    label: "เงินเดือนฐาน",
    sortable: false,
    field: "salary",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "salaryHalf",
    align: "left",
    label: "เลื่อน 0.5 ขั้น/(พิเศษ)",
    sortable: false,
    field: "salaryHalf",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "salaryFull",
    align: "left",
    label: "เลื่อน 1 ขั้น/(พิเศษ)",
    sortable: false,
    field: "salaryFull",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "salaryFullHalf",
    align: "left",
    label: "เลื่อน 1.5 ขั้น/(พิเศษ)",
    sortable: false,
    field: "salaryFullHalf",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isNext",
    align: "left",
    label: "ทะลุขั้น",
    sortable: false,
    field: "isNext",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** List Mune*/
const itemMenu = ref<ItemsMenu[]>([
  {
    label: "แก้ไข",
    icon: "edit",
    color: "edit",
    type: "edit",
  },

  {
    label: "ลบ",
    icon: "delete",
    color: "red",
    type: "delete",
  },
]);

/** queryString*/
const formQuery = reactive<FormQuerySalary>({
  page: 1, //*หน้า
  pageSize: 100, //*จำนวนแถวต่อหน้า
  keyword: "", //keyword ค้นหา
});
const maxPage = ref<number>(1);
const totalRow = ref<number>(0);
const pagination = ref({
  page: 1,
  rowsPerPage: 100,
});

/**
 * fetch รายการอัตราเงินเดือน
 */
async function fetchListSalalyRate() {
  showLoader();
  const page = await formQuery.page.toString();
  const pageSize = await formQuery.pageSize.toString();
  const keyword = await formQuery.keyword.toString();
  await http
    .get(
      config.API.salaryRateListByid(salaryId.value) +
        `?page=${page}&pageSize=${pageSize}&keyword=${keyword}`
    )
    .then((res) => {
      maxPage.value = Math.ceil(res.data.result.total / formQuery.pageSize);
      totalRow.value = res.data.result.total;
      rows.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const typeAction = ref<string>("");
const dataRow = ref<SalaryRate>();
function onClickSalaryRate(type: string, data: SalaryRate | null) {
  modalDialogFormRate.value = !modalDialogFormRate.value;
  typeAction.value = type;
  if (data) {
    dataRow.value = data;
  }
}

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

/**
 *  ดาวน์โหลดไฟล์
 */
function clickDownload() {
  showLoader();
  http
    .get(config.API.salaryReportByid(salaryId.value))
    .then(async (res) => {
      const dataList = res.data.result;
      await genReportXLSX(dataList, "อัตราเงินเดือน");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * fetch ข้อมูลอัตราเงินเดือน
 */
function fetchDataSalary() {
  http
    .get(config.API.salaryChartByid(salaryId.value))
    .then((res) => {
      isActive.value = res.data.result.isActive;
      posType.value = `${res.data.result.posTypeName}(${res.data.result.posLevelName})`;
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: NewPagination) {
  formQuery.page = 1;
  formQuery.pageSize = newPagination.rowsPerPage;
}

onMounted(async () => {
  fetchDataSalary();
  await fetchListSalalyRate();
});

watch([() => formQuery.page, () => formQuery.pageSize], async () => {
  await fetchListSalalyRate();
});
</script>

<template>
  <div class="row items-center">
    <div class="toptitle text-dark row items-center q-py-xs">
      <q-btn
        icon="mdi-arrow-left"
        unelevated
        round
        dense
        flat
        color="primary"
        class="q-mr-sm"
        @click="router.go(-1)"
      />
      อัตราเงินเดือนของ{{ posType }}
    </div>
  </div>
  <q-card flat bordered class="q-pa-md">
    <div class="col-12 row">
      <q-btn
        v-if="!isActive && checkPermission($route)?.attrIsUpdate"
        flat
        round
        dense
        icon="add"
        color="primary"
        @click="onClickSalaryRate('add', null)"
      >
        <q-tooltip>เพิ่มอัตราเงินเดือน </q-tooltip>
      </q-btn>
      <q-space />
      <!-- <q-btn outline label="พิมพ์เอกสาร" icon="print" color="green" /> -->
      <q-btn
        outline
        label="ดาวน์โหลด"
        icon="download"
        color="blue"
        @click="clickDownload()"
      />
    </div>

    <div class="col-12 q-pt-sm">
      <d-table
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        flat
        bordered
        :paging="true"
        dense
        :rows-per-page-options="[10, 25, 50, 100, 500]"
        @update:pagination="updatePagination"
        v-model:pagination="pagination"
      >
        <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>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td auto-width>
              <q-btn
                v-if="!isActive && checkPermission($route)?.attrIsUpdate"
                flat
                round
                dense
                v-for="(item, index) in itemMenu"
                :key="index"
                :color="item.color"
                :icon="item.icon"
                @click.stop="
                  item.type === 'edit'
                    ? onClickSalaryRate('edit', props.row)
                    : item.type === 'delete'
                    ? onClickDelete(props.row.id)
                    : null
                "
              >
                <q-tooltip>{{ item.label }}</q-tooltip>
              </q-btn>
            </q-td>
            <q-td
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              :class="props.row.isNext === true ? 'text-edit text-bold' : ''"
            >
              <div v-if="col.name == 'no'">
                {{
                  (formQuery.page - 1) * formQuery.pageSize + props.rowIndex + 1
                }}
              </div>
              <div v-else-if="col.name === 'salaryHalf'">
                {{
                  props.row.salaryHalfSpecial
                    ? col.value.toLocaleString() +
                      " " +
                      `(${props.row.salaryHalfSpecial.toLocaleString()})`
                    : col.value.toLocaleString()
                }}
              </div>

              <div v-else-if="col.name === 'salaryFull'">
                {{
                  props.row.salaryFullSpecial
                    ? col.value.toLocaleString() +
                      " " +
                      `(${props.row.salaryFullSpecial.toLocaleString()})`
                    : col.value.toLocaleString()
                }}
              </div>

              <div v-else-if="col.name === 'salaryFullHalf'">
                {{
                  props.row.salaryFullHalfSpecial
                    ? col.value.toLocaleString() +
                      " " +
                      `(${props.row.salaryFullHalfSpecial.toLocaleString()})`
                    : col.value.toLocaleString()
                }}
              </div>
              <div v-else-if="col.name === 'isNext'">
                <q-icon
                  v-if="col.value"
                  name="done"
                  color="primary"
                  size="24px"
                />
              </div>

              <div v-else>
                {{ col.value ? col.value.toLocaleString() : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="scope">
          ทั้งหมด {{ totalRow }} รายการ
          <q-pagination
            v-model="formQuery.page"
            active-color="primary"
            color="dark"
            :max="maxPage"
            size="sm"
            boundary-links
            direction-links
            :max-pages="5"
          ></q-pagination>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogFormRate
    v-model:modal="modalDialogFormRate"
    :typeAction="typeAction"
    :data="dataRow"
    :fetchData="fetchListSalalyRate"
  />
</template>

<style scoped></style>
