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

/** importType*/
import type { QTableProps } from "quasar";
import type { ObjectGroupRef } from "@/modules/01_metadataNew/interface/index/positionEmployee";
import type { ResGroup } from "@/modules/01_metadataNew/interface/response/positionEmployee/Main";
import type { FrmDataGroup } from "@/modules/01_metadataNew/interface/request/positionEmployee";

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

/** importStore*/
import { usePositionEmployeeDataStore } from "@/modules/01_metadataNew/stores/positionEmployeeStore";
import { useCounterMixin } from "@/stores/mixin";

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

const columns = ref<QTableProps["columns"]>([
  {
    name: "posTypeName",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "posTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posTypeShortName",
    align: "left",
    label: "อักษรย่อกลุ่มงาน",
    sortable: true,
    field: "posTypeShortName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posTypeRank",
    align: "left",
    label: "ระดับกลุ่มงาน",
    sortable: true,
    field: "posTypeRank",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "posTypeName",
  "posTypeShortName",
  "posTypeRank",
]);

/** from เพิ่มข้อมูลกลุ่มงาน */
const formDataGroup = reactive<FrmDataGroup>({
  posTypeName: "",
  posTypeShortName: "",
  posTypeRank: null,
});

/** formRef*/
const posTypeNameRef = ref<Object | null>(null);
const posTypeShortNameRef = ref<Object | null>(null);
const posTypeRankRef = ref<Object | null>(null);
const objectGroupRef: ObjectGroupRef = {
  posTypeName: posTypeNameRef,
  posTypeShortName: posTypeShortNameRef,
  posTypeRank: posTypeRankRef,
};

const editId = ref<string>("");
const filterKeyword = ref<string>("");
const dialog = ref<boolean>(false);
const dialogStatus = ref<string>("");
const rows = ref<ResGroup[]>([]);

async function fetchData() {
  showLoader();
  await http
    .get(config.API.orgEmployeeType)
    .then(async (res) => {
      rows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function onClickSubmit() {
  const hasError = [];
  for (const key in objectGroupRef) {
    if (Object.prototype.hasOwnProperty.call(objectGroupRef, key)) {
      const property = objectGroupRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    dialogConfirm($q, () => {
      submit();
    });
  }
}

async function submit() {
  const body: FrmDataGroup = {
    posTypeName: formDataGroup.posTypeName,
    posTypeShortName: formDataGroup.posTypeShortName,
    posTypeRank: Number(formDataGroup.posTypeRank),
  };
  showLoader();
  try {
    const url =
      dialogStatus.value === "create"
        ? config.API.orgEmployeeType
        : config.API.orgEmployeeTypeById(editId.value);
    await http[dialogStatus.value === "create" ? "post" : "put"](url, body);
    success($q, "บันทีกข้อมูลสำเร็จ");
    fetchData();
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
    closeDialog();
  }
}

function onClickDelete(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.orgEmployeeTypeById(id))
      .then(() => {
        fetchData();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function onClickOpenDialogEdit(data: ResGroup) {
  dialogStatus.value = "edit";
  dialog.value = true;
  editId.value = data.id;
  formDataGroup.posTypeName = data.posTypeName;
  formDataGroup.posTypeShortName = data.posTypeShortName;
  formDataGroup.posTypeRank = data.posTypeRank;
}

function onClickDetail(id: string) {
  router.push(`/master-data/position-employee/level/${id}`);
}

function closeDialog() {
  dialog.value = false;
  clearFormData();
}

function clearFormData() {
  formDataGroup.posTypeName = "";
  formDataGroup.posTypeShortName = "";
  formDataGroup.posTypeRank = null;
}

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

<template>
  <q-toolbar style="padding: 0">
    <q-btn
      flat
      round
      color="primary"
      icon="add"
      @click.stop="
        () => {
          dialogStatus = 'create';
          dialog = true;
        }
      "
    >
      <q-tooltip> เพิ่มข้อมูล </q-tooltip>
    </q-btn>
    <q-space />
    <div class="row q-gutter-sm">
      <q-input outlined dense v-model="filterKeyword" label="ค้นหา"></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"
    :filter="filterKeyword"
    row-key="name"
    flat
    bordered
    :paging="true"
    dense
    class="custom-header-table"
    :rows-per-page-options="[10, 20, 50, 100]"
    :visible-columns="visibleColumns"
  >
    <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"
        @click.stop="onClickDetail(props.row.id)"
      >
        <q-td v-for="col in props.cols" :key="col.id">
          {{ col.value ? col.value : "-" }}
        </q-td>
        <q-td auto-width>
          <q-btn
            color="edit"
            flat
            dense
            round
            class="q-mr-xs"
            size="12px"
            icon="edit"
            @click.stop="onClickOpenDialogEdit(props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="red"
            flat
            dense
            round
            size="12px"
            icon="mdi-delete"
            clickable
            @click.stop="onClickDelete(props.row.id)"
          >
            <q-tooltip>ลบข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
  </d-table>

  <q-dialog v-model="dialog" class="dialog" persistent>
    <q-card style="width: 350px">
      <form @submit.prevent="onClickSubmit">
        <q-card-section class="flex justify-between" style="padding: 0">
          <dialog-header
            :tittle="
              dialogStatus === 'edit'
                ? 'แก้ไขข้อมูลกลุ่มงาน'
                : 'เพิ่มข้อมูลกลุ่มงาน'
            "
            :close="closeDialog"
          />
        </q-card-section>

        <q-separator color="grey-4" />
        <q-card-section class="row q-gutter-y-md">
          <div class="col-12">
            <q-input
              ref="posTypeNameRef"
              outlined
              v-model="formDataGroup.posTypeName"
              label="ชื่อกลุ่มงาน"
              dense
              lazy-rules
              borderless
              bg-color="white"
              :rules="[(val) => val.length > 0 || 'กรุณากรอกชื่อกลุ่มงาน']"
              hide-bottom-space
            />
          </div>

          <div class="col-12">
            <q-input
              ref="posTypeShortNameRef"
              v-model="formDataGroup.posTypeShortName"
              dense
              outlined
              for="#positionShortName"
              label="อักษรย่อกลุ่มงาน"
              lazy-rules
              hide-bottom-space
              :rules="[(val) => !!val || `${'กรุณากรอกอักษรย่อกลุ่มงาน'}`]"
            />
          </div>

          <div class="col-12">
            <q-input
              ref="posTypeRankRef"
              outlined
              v-model="formDataGroup.posTypeRank"
              label="ระดับกลุ่มงาน"
              dense
              lazy-rules
              borderless
              min="1"
              bg-color="white"
              :rules="[(val) => val != undefined || 'กรุณากรอกระดับกลุ่มงาน']"
              hide-bottom-space
              mask="############"
            />
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn
            id="onSubmit"
            type="submit"
            dense
            unelevated
            label="บันทึก"
            color="public"
            class="q-px-md"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
</template>

<style scoped lang="scss"></style>
