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

/** 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 { EmployeeSalary } from "@/modules/13_salary/interface/response/salaryEmployeeChart";

/** importComponents*/
import DialogEmployeeChart from "@/modules/13_salary/components/salaryEmployeeChart/DialogEmployeeChart.vue";
import DialogEmployeeUpload from "@/modules/13_salary/components/salaryEmployeeChart/DialogEmployeeUpload.vue";

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

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

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

/** ข้อมูล Table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ชื่อผังบัญชีอัตราค่าจ้าง",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "group",
    align: "left",
    label: "กลุ่มของผังบัญชีอัตราค่าจ้าง",
    sortable: true,
    field: "group",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "date",
    align: "left",
    label: "วันที่มีผลบังคับใช้",
    sortable: true,
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isActive",
    align: "left",
    label: "สถานะการใช้งาน",
    sortable: true,
    field: "isActive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const rows = ref<EmployeeSalary[]>([]);
const visibleColumns = ref<string[]>(["name", "group", "date", "isActive"]);

/** List Mune*/
const itemMenu = ref<ItemsMenu[]>([
  {
    label: "แก้ไข",
    icon: "edit",
    color: "edit",
    type: "edit",
  },
  {
    label: "เอกสารอ้างอิง",
    icon: "mdi-file-document-outline",
    color: "teal",
    type: "upload",
  },
  {
    label: "อัตราค่าจ้าง",
    icon: "mdi-format-list-bulleted-triangle",
    color: "secondary",
    type: "salaryRate",
  },
  {
    label: "คัดลอก",
    icon: "content_copy",
    color: "blue-6",
    type: "copy",
  },
]);

function fetchListChart() {
  showLoader();
  http
    .get(
      config.API.salaryEmployeeChart +
        `?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();
    });
}

function onClickAction(type: string, data: EmployeeSalary) {
  switch (type) {
    case "edit":
      onEdit(data);
      break;
    case "upload":
      onUpload(data.id, data.isActive);
      break;
    case "salaryRate":
      onSalaryRate(data.id);
      break;
    case "copy":
      onCoppy(data.id);
      break;

    default:
      break;
  }
}

function onEdit(data: EmployeeSalary) {
  modalDialogEmployeeChart.value = true;
  isStatusEdit.value = true;
  dataRow.value = data;
}

const modalDialogUpload = ref<boolean>(false);
const salaryChartId = ref<string>("");
const isActive = ref<boolean>(false);
function onUpload(id: string, status: boolean) {
  modalDialogUpload.value = true;
  salaryChartId.value = id;
  isActive.value = status;
}

function onSalaryRate(id: string) {
  router.push(`/salary-employee/rate/${id}`);
}

function onCoppy(id: string) {
  http
    .post(config.API.salaryEmployeeChartCopy, { id: id })
    .then(() => {
      fetchListChart();
      success($q, "คัดลอกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    });
}
function onClickDelete(id: string) {
  dialogRemove($q, () => {
    http
      .delete(config.API.salaryEmployeeChartByid(id))
      .then(() => {
        fetchListChart();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      });
  });
}

const modalDialogEmployeeChart = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const dataRow = ref<EmployeeSalary>();
function onClickAdd() {
  modalDialogEmployeeChart.value = true;
  isStatusEdit.value = false;
}

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

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

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

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

onMounted(() => {
  fetchListChart();
});
</script>
<template>
  <q-toolbar class="text-primary" style="padding: 0px">
    <q-btn flat round dense icon="add" @click="onClickAdd()">
      <q-tooltip>เพิ่ม </q-tooltip>
    </q-btn>
    <q-space />
    <q-input
      borderless
      dense
      outlined
      v-model="formFilter.keyword"
      placeholder="ค้นหา"
      @keydown.enter.prevent="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"
      options-cover
      style="min-width: 150px"
      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"
    :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 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-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">
          <div v-if="col.name === 'date'">
            {{ col.value ? date2Thai(col.value) : "-" }}
          </div>
          <div v-else-if="col.name === 'group'">
            {{ col.value ? `กลุ่มที่ ${col.value}` : "-" }}
          </div>
          <div v-else-if="col.name === 'isActive'">
            <q-icon
              :name="col.value ? 'done' : 'close'"
              :color="col.value ? 'primary' : 'grey'"
              size="24px"
            ></q-icon>
          </div>
          <div v-else>{{ col.value ? col.value : "-" }}</div>
        </q-td>
        <q-td>
          <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-item
                  v-if="props.row.isActive == false"
                  clickable
                  v-close-popup
                  @click.stop="onClickDelete(props.row.id)"
                >
                  <q-item-section>
                    <div class="row items-center">
                      <q-icon color="red" size="17px" name="delete" />
                      <div class="q-pl-md">ลบ</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>

  <DialogEmployeeChart
    v-model:modal="modalDialogEmployeeChart"
    :isStatusEdit="isStatusEdit"
    :data="dataRow as EmployeeSalary"
    :fetchData="fetchListChart"
  />

  <DialogEmployeeUpload
    v-model:modal="modalDialogUpload"
    :id="salaryChartId"
    :isActive="isActive"
  />
</template>

<style scoped></style>
