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

/** importType*/
import type { QTableProps } from "quasar";
import type {
  ResGroup,
  ResLevel,
} from "@/modules/01_metadata/interface/response/positionEmployee/Main";
import type { ObjectLevelRef } from "@/modules/01_metadata/interface/index/positionEmployee";
import type { FormDataLevel } from "@/modules/01_metadata/interface/request/positionEmployee";

/** importComponts*/
import DialogHeader from "@/components/DialogHeader.vue";

/** importStore*/
import { useMainOptionDataStore } from "@/modules/01_metadata/stores/main";
import { useCounterMixin } from "@/stores/mixin";

/**use*/
const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const posName = ref<string>("");
const posTypeId = ref<string>(route.params.id.toString());

const {
  dialogRemove,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
} = useCounterMixin();
const storeOption = useMainOptionDataStore();

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px; width:0px",
    style: "font-size: 14px",
  },
  {
    name: "posLevelName",
    align: "left",
    label: "ระดับชั้นงาน",
    sortable: true,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posTypeName",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "posTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "posLevelAuthority",
    align: "left",
    label: "ผู้มีอำนาจสั่งบรรจุ",
    sortable: true,
    field: "posLevelAuthority",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const rows = ref<any>([]);

const visibleColumns = ref<string[]>([
  "no",
  "posLevelName",
  "posTypeName",
  "posLevelAuthority",
]);
const filter = ref<string>("");

const levelId = ref<string>("");
const titleName = ref<string | null>("");
const formDataLevel = reactive<FormDataLevel>({
  posLevelName: null,
  posTypeName: "",
  posLevelAuthority: "",
});

/** formRef*/
const posLevelNameRef = ref<Object | null>(null);
const commanderRef = ref<Object | null>(null);
const objectLevelRef: ObjectLevelRef = {
  posLevelName: posLevelNameRef,
  posLevelAuthority: commanderRef,
};

const id = ref<string>(route.params.id.toString());

function fetchData() {
  showLoader();
  http
    .get(config.API.orgEmployeeTypeById(id.value))
    .then((res) => {
      titleName.value = res.data.result.posTypeName ?? null;
      formDataLevel.posTypeName = res.data.result.posTypeName;
      rows.value = res.data.result.posLevels.map((x: any) => ({
        ...x,
        posTypeName: res.data.result.posTypeName,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const isStatusEdit = ref<boolean>(false);
const modalDialog = ref<boolean>(false);
function onClickOpenDialog(statusEdit: boolean = false, data: any = []) {
  isStatusEdit.value = statusEdit;
  modalDialog.value = true;

  if (statusEdit) {
    levelId.value = data.id;
    formDataLevel.posLevelName = data.posLevelName;
    formDataLevel.posTypeName = titleName.value;
    formDataLevel.posLevelAuthority = data.posLevelAuthority;
  } else {
    formDataLevel.posTypeName = titleName.value ? titleName.value : "";
  }
}

function onClickCloseDialog() {
  modalDialog.value = false;
  formDataLevel.posLevelName = null;
  formDataLevel.posTypeName = "";
  formDataLevel.posLevelAuthority = "";
}

function onClickSubmit() {
  const hasError = [];
  for (const key in objectLevelRef) {
    if (Object.prototype.hasOwnProperty.call(objectLevelRef, key)) {
      const property = objectLevelRef[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 = {
    posLevelName: Number(formDataLevel.posLevelName),
    posTypeId: posTypeId.value,
    posLevelRank: Number(formDataLevel.posLevelName),
    posLevelAuthority: formDataLevel.posLevelAuthority,
  };
  showLoader();
  try {
    const url = !isStatusEdit.value
      ? config.API.orgEmployeelevel
      : config.API.orgEmployeelevelById(levelId.value);
    await http[!isStatusEdit.value ? "post" : "put"](url, body);
    success($q, "บันทีกข้อมูลสำเร็จ");
    fetchData();
    onClickCloseDialog();
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

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

function convertPosLevelAuthority(val: string) {
  const result = storeOption.posLevelAuthorityOption.find((e) => e.id === val);
  return result?.label;
}

onMounted(() => {
  posTypeId.value && fetchData();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="router.go(-1)"
    />
    รายการระดับชั้นงาน{{ titleName }}
  </div>

  <q-card flat bordered>
    <div class="q-pa-md">
      <q-toolbar style="padding: 0">
        <q-btn
          flat
          round
          color="primary"
          icon="add"
          @click.stop.pervent="onClickOpenDialog()"
        >
          <q-tooltip> เพิ่มข้อมูล </q-tooltip>
        </q-btn>
        <q-space />
        <div class="row q-gutter-sm">
          <q-input outlined dense v-model="filter" 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="filter"
        row-key="name"
        flat
        bordered
        :paging="true"
        dense
        class="custom-header-table"
        :visible-columns="visibleColumns"
      >
        <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-bold">{{ col.label }}</span>
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td auto-width>
              <q-btn
                color="edit"
                flat
                dense
                round
                class="q-mr-xs"
                icon="edit"
                @click.stop.pervent="onClickOpenDialog(true, props.row)"
              >
                <q-tooltip>แก้ไขข้อมูล</q-tooltip>
              </q-btn>
              <!-- <q-btn
                color="red"
                flat
                dense
                round
                icon="mdi-delete"
                @click="onClickDelete(props.row.id)"
              >
                <q-tooltip>ลบข้อมูล</q-tooltip>
              </q-btn> -->
            </q-td>
            <q-td v-for="(col, index) in props.cols" :key="col.id">
              <div v-if="col.name == 'no'">
                {{ props.rowIndex + 1 }}
              </div>
              <div v-else-if="col.name === 'posLevelAuthority'">
                {{ col.value ? convertPosLevelAuthority(col.value) : "-" }}
              </div>
              <div v-else>
                {{ col.value }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <q-dialog v-model="modalDialog" class="dialog" persistent>
    <q-card style="width: 350px">
      <form @submit.prevent="onClickSubmit">
        <q-card-section class="flex justify-between" style="padding: 0">
          <DialogHeader
            :tittle="isStatusEdit ? 'แก้ไขข้อมูล' : 'เพิ่มข้อมูล'"
            :close="onClickCloseDialog"
          />
        </q-card-section>

        <q-separator color="grey-4" />
        <q-card-section class="row q-gutter-y-md">
          <div class="col-12">
            <q-input
              outlined
              ref="posLevelNameRef"
              v-model="formDataLevel.posLevelName"
              label="ระดับชั้นงาน"
              dense
              lazy-rules
              borderless
              bg-color="white"
              hide-bottom-space
              mask="#######################################"
              :rules="[(val) => !!val || 'กรุณากรอกระดับชั้นงาน']"
            />
          </div>

          <div class="col-12">
            <q-select
              ref="commanderRef"
              outlined
              v-model="formDataLevel.posLevelAuthority"
              emit-value
              map-options
              :options="storeOption.posLevelAuthorityOption"
              option-value="id"
              label="ผู้มีอำนาจสั่งบรรจุ"
              dense
              lazy-rules
              borderless
              bg-color="white"
              hide-bottom-space
              :rules="[(val) => !!val || 'กรุณาเลือกผู้มีอำนาจสั่งบรรจุ']"
            />
          </div>

          <div class="col-12">
            <q-select
              ref="posTypeIdRef"
              v-model="formDataLevel.posTypeName"
              label="กลุ่มงาน"
              outlined
              dense
              bg-color="white"
              options-cover
              hide-bottom-space
              readonly
            />
          </div>
        </q-card-section>

        <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></style>
