<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/01_Salary/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,
});

const typeAction = ref<string>(""); //ประเภทการกระทำ
const dataSalaryRate = ref<SalaryRate>(); //ข้อมูลรายการ

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

/**
 *  function openDialog เพิ่ม,แก้ไข อัตราเงินเดือน
 * @param type ประเภท แก่ไข,เพิ่ม
 * @param data ข้อมูลอัตราเงินเดือน
 */
function onClickSalaryRate(type: string, data: SalaryRate | null) {
  modalDialogFormRate.value = !modalDialogFormRate.value;
  typeAction.value = type;
  if (data) {
    dataSalaryRate.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(async (res) => {
      const data = await res.data.result;
      isActive.value = data.isActive;
      posType.value = `${data.posTypeName}(${data.posLevelName})`;
    })
    .catch((e) => {
      messageError($q, e);
    });
}

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

/**
 *  ทำงานเมื่อมีการ เปลี่ยนหน้าหรือ แถว
 */
watch([() => formQuery.page, () => formQuery.pageSize], async () => {
  await fetchListSalalyRate();
});

onMounted(async () => {
  await Promise.all([fetchDataSalary(), 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"
    :type-action="typeAction"
    :fetch-data="fetchListSalalyRate"
    :data="dataSalaryRate"
  />
</template>

<style scoped></style>
