<script setup lang="ts">
import { ref, onMounted, reactive, watch } from "vue";
import type { QTableProps } from "quasar";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";

import type { NewPagination } from "@/modules/14_KPI/interface/index/Main";

import dialogHeader from "@/components/DialogHeader.vue";

const total = ref<number>();
const modal = ref<boolean>(false);
const rows = ref<any[]>([]);
const groupName = ref<string>("");

const editStatus = ref<boolean>(false);
const editId = ref<string>("");
const columns = ref<QTableProps["columns"]>([
  {
    name: "nameGroupKPI",
    align: "left",
    label: "รายการกลุ่มงาน",
    sortable: true,
    field: "nameGroupKPI",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogRemove,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
} = mixin;

const visibleColumns = ref<string[]>(["nameGroupKPI"]);

const formQuery = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
});
const totalList = ref<number>(1); //จำนวนข้อมูลรายการ

/** ดึงข้อมูล */
async function fetchData() {
  showLoader();
  await http
    .get(
      config.API.kpiGroup +
        `/edit?page=${formQuery.page}&pageSize=${formQuery.pageSize}&keyword=${formQuery.keyword}`
    )
    .then(async (res) => {
      total.value = res.data.result.total;
      const data = res.data.result;
      totalList.value = Math.ceil(res.data.result.total / formQuery.pageSize);
      rows.value = data.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** เพิ่มข้อมูล */
async function addData() {
  await http
    .post(config.API.kpiGroup, {
      nameGroupKPI: groupName.value,
    })
    .then(() => {
      fetchData();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** save แก้ไขข้อมูล */
async function editData(id: string) {
  await http
    .put(config.API.kpiGroupById(id), {
      nameGroupKPI: groupName.value,
    })
    .then(() => {
      fetchData();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

/** เปลี่ยนเป็นหน้าเพิ่มข้อมูล */
function onAdd() {
  modal.value = true;
}

function closeDialog() {
  modal.value = false;
  editStatus.value = false;
  groupName.value = "";
}

/** เปิด dialog แก้ไข */
function onEdit(data: any) {
  modal.value = true;
  editStatus.value = true;
  groupName.value = data.nameGroupKPI;
  editId.value = data.id;
}

/** บันทึกข้อมูล */
async function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      editStatus.value ? editData(editId.value) : addData();
      closeDialog();
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

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

watch(
  () => formQuery.pageSize,
  () => {
    fetchNewList();
  }
);

onMounted(async () => {
  fetchData();
});
</script>

<template>
  <q-toolbar style="padding: 0">
    <q-btn
      v-if="checkPermission($route)?.attrIsCreate"
      flat
      round
      color="primary"
      icon="add"
      @click="onAdd()"
    >
      <q-tooltip> เพิ่มข้อมูล </q-tooltip>
    </q-btn>
    <q-space />
    <div class="row q-gutter-sm">
      <q-input
        outlined
        dense
        v-model="formQuery.keyword"
        label="ค้นหา"
        @keyup.enter="fetchNewList()"
      >
        <template v-slot:append>
          <q-icon v-if="formQuery.keyword == ''" name="search" />
          <q-icon
            v-if="formQuery.keyword !== ''"
            name="clear"
            class="cursor-pointer"
            @click="(formQuery.keyword = ''), fetchNewList()"
          /> </template
      ></q-input>
      <q-select
        v-model="visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="columns"
        option-value="name"
        
        style="min-width: 140px"
      />
    </div>
  </q-toolbar>

  <d-table
    ref="table"
    :columns="columns"
    :rows="rows"
    row-key="id"
    flat
    bordered
    :paging="true"
    dense
    class="custom-header-table"
    :rows-per-page-options="[10, 25, 50, 100]"
    :visible-columns="visibleColumns"
    @update:pagination="updatePagination"
  >
    <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="
              checkPermission($route)?.attrIsGet &&
              checkPermission($route)?.attrIsUpdate
            "
            color="edit"
            flat
            dense
            round
            class="q-mr-xs"
            icon="edit"
            clickable
            @click="onEdit(props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            v-if="checkPermission($route)?.attrIsDelete"
            color="red"
            flat
            dense
            round
            icon="mdi-delete"
            clickable
            @click.stop="
              dialogRemove($q, async () => await deleteData(props.row.id))
            "
            v-close-popup
          >
            <q-tooltip>ลบข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.id">
          {{ col.value }}
        </q-td>
      </q-tr>
    </template>
    <template v-slot:pagination="scope">
      ทั้งหมด {{ total }} รายการ
      <q-pagination
        v-model="formQuery.page"
        active-color="primary"
        color="dark"
        :max="Number(totalList)"
        size="sm"
        boundary-links
        direction-links
        :max-pages="5"
        @update:model-value="fetchData"
      ></q-pagination>
    </template>
  </d-table>

  <q-dialog v-model="modal" persistent>
    <q-card flat bordered style="min-width: 50vh">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <dialog-header
          :tittle="editStatus ? 'แก้ไขกลุ่มงาน' : 'เพิ่มกลุ่มงาน'"
          :close="closeDialog"
        />
        <q-separator />
        <q-card-section>
          <q-input
            label="กลุ่มงาน"
            v-model="groupName"
            outlined
            dense
            class="inputgreen"
            :rules="[(val:string) => !!val || `${'กรุณากรอกกลุ่มงาน'}`,]"
            hide-bottom-space
          />
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn
            type="submit"
            for="#submitForm"
            class="q-px-md items-center"
            color="public"
            label="บันทึก"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
