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

/** importType*/
import type { QTableProps } from "quasar";
import type {
  ObjectPosRef,
  FormQuery,
} from "@/modules/01_metadataNew/interface/index/positionEmployee";
import type {
  DataOption,
  RowDetailPositions,
} from "@/modules/01_metadataNew/interface/request/position/index";
import type {
  ResGroup,
  ResLevel,
  ResPossition,
} from "@/modules/01_metadataNew/interface/response/positionEmployee/Main";

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

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

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

const rows = ref<ResPossition[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posDictName",
    align: "left",
    label: "ชื่อตำแหน่ง",
    sortable: true,
    field: "posDictName",
    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: "posLevelName",
    align: "left",
    label: "ระดับชั้นงาน",
    sortable: true,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "posDictName",
  "posTypeName",
  "posLevelName",
]);

const formQuery = reactive<FormQuery>({
  type: "positionName",
  keyword: "",
});

const optionFilter = ref<DataOption[]>([
  { id: "positionName", name: "ชื่อตำแหน่ง" },
  { id: "positionType", name: "กลุ่มงาน" },
  { id: "positionLevel", name: "ระดับชั้นงาน" },
]);

const modalDialog = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const posId = ref<string>("");
const formDataPos = reactive({
  posName: "",
  posTypeName: "",
  posLevelName: "",
});
const posNameRef = ref<object | null>(null);
const posTypeNameRef = ref<object | null>(null);
const posLevelNameRef = ref<object | null>(null);
const objectRef: ObjectPosRef = {
  posName: posNameRef,
  posTypeName: posTypeNameRef,
  posLevelName: posLevelNameRef,
};

const posTypeMain = ref<ResGroup[]>([]);
const posTypeOp = ref<DataOption[]>([]);
const posLevelOp = ref<DataOption[]>([]);

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

async function onClickOpenDialog(typeEdit: boolean = false, data: any = []) {
  modalDialog.value = true;
  isStatusEdit.value = typeEdit;
  await fetchType();
  updatePosTypeName(data.posTypeId);
  if (data) {
    posId.value = data.id;
    setTimeout(() => {
      formDataPos.posName = data.posDictName;
      formDataPos.posTypeName = data.posTypeId;
      formDataPos.posLevelName = data.posLevelId;
    }, 200);
  }
}

async function fetchData(statusFetch: boolean = false) {
  showLoader();
  await http
    .get(
      config.API.orgEmployeePos +
        `?keyword=${formQuery.keyword}&type=${
          statusFetch ? "" : formQuery.type
        }`
    )
    .then((res) => {
      rows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function fetchType() {
  if (posTypeMain.value.length === 0) {
    showLoader();
    await http
      .get(config.API.orgEmployeeType)
      .then((res) => {
        const data = res.data.result;
        posTypeMain.value = data;
        posTypeOp.value = data.map((e: ResGroup) => ({
          id: e.id,
          name: e.posTypeName,
        }));
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

async function onClickSubmit() {
  const hasError = [];
  for (const key in objectRef) {
    if (Object.prototype.hasOwnProperty.call(objectRef, key)) {
      const property = objectRef[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 = {
    posDictName: formDataPos.posName,
    posTypeId: formDataPos.posTypeName,
    posLevelId: formDataPos.posLevelName,
  };
  showLoader();
  try {
    const url = !isStatusEdit.value
      ? config.API.orgEmployeePos
      : config.API.orgEmployeePosById(posId.value);
    await http[!isStatusEdit.value ? "post" : "put"](url, body);
    success($q, "บันทีกข้อมูลสำเร็จ");
    fetchData();
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
    closeDialog();
  }
}

function updatePosTypeName(id: string) {
  const posLevel = posTypeMain.value.find((e: ResGroup) => e.id === id);
  posLevelOp.value =
    posLevel?.posLevels.map((e: ResLevel) => ({
      id: e.id,
      name: e.posLevelName.toString(),
    })) ?? [];
  formDataPos.posLevelName = "";
}

function closeDialog() {
  modalDialog.value = false;
  formDataPos.posName = "";
  formDataPos.posTypeName = "";
  formDataPos.posLevelName = "";
}

onMounted(() => {
  fetchData(true);
});
</script>
<template>
  <div class="row col-12 q-mb-sm">
    <div class="col-md-2">
      <q-btn
        id="addComplaints"
        for="addComplaints"
        size="12px"
        flat
        round
        color="primary"
        icon="mdi-plus"
        @click="onClickOpenDialog()"
        ><q-tooltip>เพิ่มตำเเหน่ง </q-tooltip></q-btn
      >
    </div>

    <div class="row col-md-10 q-col-gutter-sm">
      <div class="col-md-4">
        <q-select
          label="ค้นหาจาก"
          v-model="formQuery.type"
          :options="optionFilter"
          emit-value
          dense
          map-options
          outlined
          option-label="name"
          option-value="id"
        />
      </div>

      <div class="col-md-6">
        <q-input
          ref="searchRef"
          v-model="formQuery.keyword"
          outlined
          dense
          lazy-rules
          label="คำค้น"
          hide-bottom-space
          @keydown.enter="fetchData()"
        >
          <template v-slot:append>
            <q-icon
              v-if="formQuery.keyword"
              name="cancel"
              @click="(formQuery.keyword = ''), fetchData()"
              class="cursor-pointer"
            ></q-icon>
          </template>
        </q-input>
      </div>

      <div class="row col-md-2">
        <q-btn
          color="primary"
          icon="search"
          label="ค้นหา"
          class="full-width"
          @click="fetchData()"
        />
      </div>
    </div>
  </div>

  <div class="full-width q-mt-sm">
    <d-table
      ref="table"
      :columns="columns"
      :rows="rows"
      row-key="id"
      flat
      bordered
      :paging="true"
      dense
      class="custom-header-table"
      :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"
            style="color: #000000; font-weight: 500"
          >
            <span class="text-weight-medium">{{ col.label }}</span>
          </q-th>
          <q-th auto-width></q-th>
        </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.name" :props="props">
            <div v-if="col.name == 'no'">
              {{ props.rowIndex + 1 }}
            </div>

            <div v-else>
              {{ col.value ? col.value : "-" }}
            </div>
          </q-td>
          <q-td auto-width>
            <q-btn
              color="blue-6"
              flat
              dense
              round
              class="q-mr-xs"
              size="12px"
              icon="mdi-content-copy"
              clickable
              @click.stop="
                () => {
                  onClickOpenDialog(false, props.row);
                }
              "
            >
              <q-tooltip>คัดลอกข้อมูล</q-tooltip>
            </q-btn>
            <q-btn
              color="edit"
              flat
              dense
              round
              size="12px"
              icon="mdi-pencil"
              clickable
              @click.stop="onClickOpenDialog(true, props.row)"
              v-close-popup
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
            <q-btn
              color="red"
              flat
              dense
              round
              size="12px"
              icon="mdi-delete"
              clickable
              @click.stop="deletePos(props.row.id)"
              v-close-popup
            >
              <q-tooltip>ลบข้อมูล</q-tooltip>
            </q-btn>
          </q-td>
        </q-tr>
      </template>
    </d-table>
  </div>

  <q-dialog v-model="modalDialog" class="dialog" persistent>
    <q-card style="width: 350px">
      <form @submit.prevent="onClickSubmit">
        <DialogHeader
          :tittle="`${
            isStatusEdit
              ? 'แก้ไขข้อมูลตำแหน่งลูกจ้างประจำ'
              : 'เพิ่มข้อมูลตำแหน่งลูกจ้างประจำ'
          }`"
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm col-12">
            <div class="col-12">
              <q-input
                ref="posNameRef"
                v-model="formDataPos.posName"
                dense
                outlined
                for="#positionName"
                label="ชื่อตำแหน่ง"
                lazy-rules
                hide-bottom-space
                :rules="[(val) => !!val || `${'กรุณากรอกชื่อตำแหน่ง'}`]"
              />
            </div>

            <div class="col-6">
              <q-select
                ref="posTypeNameRef"
                label="กลุ่มงาน"
                v-model="formDataPos.posTypeName"
                :options="posTypeOp"
                emit-value
                dense
                map-options
                outlined
                option-label="name"
                option-value="id"
                lazy-rules
                hide-bottom-space
                :rules="[(val) => !!val || `${'กรุณาเลือกกลุ่มงาน'}`]"
                @update:model-value="updatePosTypeName"
              />
            </div>

            <div class="col-6">
              <q-select
                ref="posLevelNameRef"
                label="ระดับชั้นงาน"
                v-model="formDataPos.posLevelName"
                :disable="formDataPos.posTypeName === ''"
                :options="posLevelOp"
                emit-value
                dense
                map-options
                outlined
                option-label="name"
                option-value="id"
                lazy-rules
                hide-bottom-space
                :rules="[(val) => !!val || `${'กรุณาเลือกระดับชั้นงาน'}`]"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn type="submit" :label="`บันทึก`" color="public" />
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
</template>
