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

import dialogHeader from "@/components/DialogHeader.vue";
import type {
  DataOption,
  NewPagination,
} from "@/modules/14_KPI/interface/index/Main";
import type { ResponseObject } from "@/modules/14_KPI/interface/response/KpiGroup";
import http from "@/plugins/http";
import config from "@/app.config";

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

const editStatus = ref<boolean>(false);
const editId = ref<string>("");
const competencyTypeOp = ref<DataOption[]>([
  {
    id: "ID1",
    name: "สมรรถนะหลัก",
  },
  {
    id: "ID2",
    name: "สมรรถนะประจำกลุ่มงาน",
  },
  {
    id: "ID3",
    name: "สมรรถนะประจำผู้บริหารกรุงเทพมหานคร",
  },
  {
    id: "ID4",
    name: "สมรรถนะเฉพาะสำหรับตำแหน่ง ผอ.เขต ผช.ผอ.เขต และหัวหน้าฝ่ายในสังกัด สนง.เขต",
  },
  {
    id: "ID5",
    name: "สมรรถนะเฉพาะสำหรับตำแหน่งผู้ตรวจราชการ กทม. และผู้ตรวจราชการ",
  },
]);
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 +
        `?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();
    });
}

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

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 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"
        options-cover
        style="min-width: 150px"
      />
    </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 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>
    </template>
    <template v-slot:body="props">
      <q-tr :props="props" class="cursor-pointer">
        <q-td v-for="col in props.cols" :key="col.id">
          {{ col.value }}
        </q-td>
        <q-td auto-width>
          <q-btn
            color="edit"
            flat
            dense
            round
            class="q-mr-xs"
            size="12px"
            icon="edit"
            clickable
            @click="onEdit(props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="red"
            flat
            dense
            round
            size="12px"
            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-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" class="bg-white text-teal">
          <q-btn
            type="submit"
            for="#submitForm"
            unelevated
            dense
            class="q-px-md items-center"
            color="public"
            label="บันทึก"
          />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
