<script setup lang="ts">
import { ref, onMounted, reactive, 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 {
  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 {
  date2Thai,
  dialogRemove,
  success,
  messageError,
  showLoader,
  hideLoader,
} = useCounterMixin();

const isActive = ref<boolean>(false)
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 totalRow = ref<number>(1);

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) => {
      totalRow.value = Math.ceil(res.data.result.total / formQuery.pageSize);

      rows.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ตั้งค่าเริ่มต้น paging */
const pagination = ref({
  page: 1,
  rowsPerPage: 100,
});
/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: NewPagination) {
  formQuery.page = 1;
  formQuery.pageSize = newPagination.rowsPerPage;
}

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;
  }
}

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

function clickDownload() {
  showLoader();
  http
    .get(config.API.salaryReportByid(salaryId.value))
    .then((res) => {
      const dataList = res.data.result;
      genReportXLSX(dataList, "อัตราเงินเดือน");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}
function fetchList(){
  http
  .get(config.API.salaryChartByid(salaryId.value))
  .then((res)=>{
    isActive.value = res.data.result.isActive
  })
  .catch((e)=>{})
  .finally(()=>{})
}
onMounted(async () => {
  await fetchList();
  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)"
      />
      อัตราเงินเดือน
    </div>
  </div>
  <q-card flat bordered class="q-pa-md">
    <div class="col-12 row">
      <q-btn
      v-if="!isActive"
        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 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="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-td>
              <q-btn
              v-if="!isActive"
                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 itemMenu"
                      :key="index"
                      clickable
                      v-close-popup
                      @click.stop="
                        item.type === 'edit'
                          ? onClickSalaryRate('edit', props.row)
                          : 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">
          <q-pagination
            v-model="formQuery.page"
            active-color="primary"
            color="dark"
            :max="totalRow"
            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>
