<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
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 {
  ItemsMenu,
  NewPagination,
} from "@/modules/13_salary/interface/index/Main";
import type { FormFilter } from "@/modules/13_salary/interface/request/EmployeeChart";
import type { EmployeeRateSalary } from "@/modules/13_salary/interface/response/salaryEmployeeChart";

/** importComponts*/
import DialogEmployeeRate from "@/modules/13_salary/components/salaryEmployeeChart/DialogEmployeeRate.vue";

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

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

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

/** ข้อมูล Table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "step",
    align: "left",
    label: "ลำดับขั้น",
    sortable: false,
    field: "step",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "salaryMonth",
    align: "left",
    label: "อัตราค่าจ้าง/ขั้นวิ่ง (รายเดือน)",
    sortable: false,
    field: "salaryMonth",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) =>
      val.toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
  },
  {
    name: "salaryDay",
    align: "left",
    label: "อัตราค่าจ้าง/ขั้นวิ่ง (รายวัน)",
    sortable: false,
    field: "salaryDay",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: number) => a.toLocaleString("en", {
    //                     minimumFractionDigits: 2,
    //                     maximumFractionDigits: 2,
    //                   }),
    format: (val) =>
      val.toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
  },
]);
const rows = ref<EmployeeRateSalary[]>([]);
const visibleColumns = ref<string[]>(["step", "salaryMonth", "salaryDay"]);

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

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

const formFilter = reactive<FormFilter>({
  page: 1,
  pageSize: 100,
  keyword: "",
});
const maxPage = ref<number>(1);

const pagination = ref({
  page: formFilter.page,
  rowsPerPage: formFilter.pageSize,
});
const isActive = ref<boolean>(false);

function fetchDataDetail() {
  http
    .get(config.API.salaryEmployeeChartByid(salaryEmployeeId.value))
    .then((res) => {
      isActive.value = res.data.result.isActive;
    })
    .catch((e) => {})
    .finally(() => {});
}

function fetchSalalyEmployeeRate() {
  showLoader();
  http
    .get(
      config.API.salaryEmployeeRateListByid(salaryEmployeeId.value) +
        `?page=${formFilter.page}&pageSize=${formFilter.pageSize}&keyword=${formFilter.keyword}`
    )
    .then((res) => {
      rows.value = res.data.result.data;
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const modalDialogEmployeeRate = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const dataRow = ref<EmployeeRateSalary>();

function onClickAction(type: string, data: EmployeeRateSalary) {
  switch (type) {
    case "edit":
      onEdit(data);
      break;
    case "delete":
      onDelete(data.id);
      break;

    default:
      break;
  }
}

function onEdit(data: EmployeeRateSalary) {
  modalDialogEmployeeRate.value = true;
  isStatusEdit.value = true;
  dataRow.value = data;
}

function onDelete(id: string) {
  dialogRemove($q, () => {
    http
      .delete(config.API.salaryEmployeeRateListByid(id))
      .then(() => {
        fetchSalalyEmployeeRate();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
        hideLoader();
      })
      .finally(() => {});
  });
}

function onClickAdd() {
  modalDialogEmployeeRate.value = true;
  isStatusEdit.value = false;
}

function filterFn() {
  formFilter.page = 1;
  fetchSalalyEmployeeRate();
}

function updatePage(val: number) {
  formFilter.page = val;
  fetchSalalyEmployeeRate();
}

function updatePageSize(newPagination: NewPagination) {
  formFilter.page = 1;
  formFilter.pageSize = newPagination.rowsPerPage;
}

/** click download */
function clickDownload() {
  showLoader();
  http
    .get(config.API.salaryReportemployeeByid(salaryEmployeeId.value))
    .then((res) => {
      const dataList = res.data.result;
      genReportXLSX(dataList, "อัตราเงินเดือน");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

watch(
  () => formFilter.pageSize,
  () => {
    fetchSalalyEmployeeRate();
  }
);

onMounted(() => {
  fetchSalalyEmployeeRate();
  fetchDataDetail();
});
</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)"
      />
      อัตราค่าจ้าง
    </div>
  </div>
  <q-card flat bordered class="q-pa-md">
    <q-toolbar class="text-primary" style="padding: 0px">
      <q-btn v-if="!isActive" flat round dense icon="add" @click="onClickAdd">
        <q-tooltip>เพิ่ม </q-tooltip>
      </q-btn>
      <q-space />
      <q-btn
        outline
        label="ดาวน์โหลด"
        icon="download"
        color="blue"
        @click="clickDownload()"
      />
      <!-- <q-input
        borderless
        dense
        outlined
        v-model="formFilter.keyword"
        @keydown.enter.pervrnt="filterFn"
        placeholder="ค้นหา"
      >
        <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"
        options-cover
        style="min-width: 150px"
        class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
      /> -->
    </q-toolbar>
    <div class="col-12">
      <d-table
        flat
        bordered
        dense
        :rows="rows"
        :columns="columns"
        row-key="name"
        :rows-per-page-options="[10, 20, 50, 100]"
        :visible-columns="visibleColumns"
        @update:pagination="updatePageSize"
        v-model:pagination="pagination"
      >
        <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 v-if="!isActive" />
          </q-tr>
          <q-separator />
        </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">
              {{ col.value ? col.value : "-" }}
            </q-td>
            <q-td v-if="!isActive">
              <q-btn
                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: 200px">
                    <q-item
                      v-for="(item, index) in itemMenu"
                      :key="index"
                      clickable
                      v-close-popup
                      @click.stop="onClickAction(item.type, props.row)"
                    >
                      <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">
          <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>
    </div>
  </q-card>

  <DialogEmployeeRate
    v-model:modal="modalDialogEmployeeRate"
    :isStatusEdit="isStatusEdit"
    :fetchData="fetchSalalyEmployeeRate"
    :data="dataRow as EmployeeRateSalary"
  />
</template>

<style scoped></style>
