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

import type { QTableProps } from "quasar";
import type {
  FormDataPosition,
  FormPositionRef,
  DataOption,
  FormPositionSelect,
  RowDetailPositions,
  FormPositionSelectRef,
  ListMenu,
} from "@/modules/16_positionEmployee/interface/index/Main";
import type {
  OptionType,
  OptionLevel,
  OptionExecutive,
  DataPosition,
} from "@/modules/16_positionEmployee/interface/response/organizational";
import type { FilterMaster } from "@/modules/16_positionEmployee/interface/request/organizational";
import DialogHeader from "@/components/DialogHeader.vue";
import DialogAddPosition from "@/modules/16_positionEmployee/components/DialogAddPosition.vue";

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

const props = defineProps({
  modal: Boolean,
  close: Function,
  orgLevel: Number,
  treeId: String,
  actionType: String,
  rowId: { type: String, default: "" },
  fetchDataTable: Function,
  getSummary: Function,
  shortName: { type: String, required: true },
});

const isEdit = ref<boolean>(false);
const modalAdd = ref<boolean>(false);
const reqMaster = defineModel<FilterMaster>("reqMaster", { required: true });
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const isDisValidate = ref<boolean>(false);
const isPosition = ref<boolean>(false);

const dataCopy = ref<any>();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  dialogRemove,
  dialogMessageNotify,
} = mixin;

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

const listMenu = ref<ListMenu[]>([
  {
    label: "คัดลอก",
    icon: "mdi-content-copy",
    type: "copy",
    color: "blue-6",
  },
  {
    label: "แก้ไข",
    icon: "mdi-pencil",
    type: "edit",
    color: "edit",
  },
  {
    label: "ลบ",
    icon: "delete",
    type: "remove",
    color: "red",
  },
]);

const rows = ref<RowDetailPositions[]>([]);
const rowsPositionSelect = ref<RowDetailPositions[]>([]);

const prefixNoRef = ref<Object | null>(null);
const positionNoRef = ref<Object | null>(null);

const formData = reactive<FormDataPosition>({
  shortName: props.shortName,
  prefixNo: "",
  positionNo: "",
  suffixNo: "",
  reason: "",
});

/** maping ref เข้าตัวแปรเพื่อเตรียมตรวจสอบ */
const objectPositionRef: FormPositionRef = {
  prefixNo: prefixNoRef,
  positionNo: positionNoRef,
};

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",
]);

async function fetchPosition(id: string) {
  showLoader();
  await http
    .get(config.API.orgPosPositionEmpById(id))
    .then((res) => {
      const data = res.data.result;

      formData.prefixNo = data.posMasterNoPrefix;
      formData.positionNo = data.posMasterNo;
      formData.suffixNo = data.posMasterNoSuffix;
      formData.reason = data.reason;
      rows.value = data.positions.map((e: any) => ({
        ...e,
        posDictName: e.positionName,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ฟังก์ชั่นตรวจสอบความถูกต้องของข้อมูลในฟอร์ม */
function validateForm() {
  const hasError = [];
  for (const key in objectPositionRef) {
    if (Object.prototype.hasOwnProperty.call(objectPositionRef, key)) {
      const property = objectPositionRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    if (rows.value.length == 0) {
      dialogMessageNotify($q, "กรุณาเลือกตำแหน่งอย่างน้อย 1 ตำแหน่ง");
    } else {
      onSubmit();
    }
  }
}

/** ฟังชั่น บันทึก */
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const positionsData = rows.value.map((e: any) => ({
      posDictName: e.posDictName, //ชื่อตำแหน่งในสายงาน (ชื่อตำแหน่ง)
      posTypeId: e.posTypeId, //*ประเภทตำแหน่ง
      posLevelId: e.posLevelId, //*ระดับตำแหน่ง
    }));
    const body = {
      posMasterNoPrefix: formData.prefixNo, //*Prefix นำหน้าเลขที่ตำแหน่ง เป็น Optional (ไม่ใช่อักษรย่อของหน่วยงาน/ส่วนราชการ)
      posMasterNo: Number(formData.positionNo), //*เลขที่ตำแหน่ง เป็นตัวเลข
      posMasterNoSuffix: formData.suffixNo, //Suffix หลังเลขที่ตำแหน่ง เช่น ช.
      reason: formData.reason, //Suffix หลังเลขที่ตำแหน่ง เช่น ช.
      orgRootId: props.orgLevel === 0 ? props.treeId : null, //Id สำนัก
      orgChild1Id: props.orgLevel === 1 ? props.treeId : null,
      orgChild2Id: props.orgLevel === 2 ? props.treeId : null,
      orgChild3Id: props.orgLevel === 3 ? props.treeId : null,
      orgChild4Id: props.orgLevel === 4 ? props.treeId : null,
      positions: positionsData,
      // succession: succession.value,
    };
    try {
      const url =
        props.actionType === "ADD"
          ? config.API.orgPosMasterEmp
          : config.API.orgPosMasterByIdEmp(props.rowId);
      await http[props.actionType === "ADD" ? "post" : "put"](url, body);
      success($q, "บันทีกข้อมูลสำเร็จ");
      props.getSummary?.();
      props.fetchDataTable?.(reqMaster.value.id, reqMaster.value.type, false);
      close();
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

/** input ค้นหา */
const searchRef = ref<any>(null);
async function searchInput() {
  searchRef.value.validate();
  if (!searchRef.value.hasError) {
    showLoader();
    await http
      .get(
        config.API.orgEmployeePos +
          `?keyword=${search.value}&type=${type.value}`
      )
      .then((res) => {
        rowsPositionSelect.value = res.data.result;
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/**
 * คัดลอกข้อมูล
 * @param data ข้อมูลตำแหน่ง
 */
function copyDetiail(data: RowDetailPositions) {
  modalAdd.value = true;
  dataCopy.value = data;
}
/**
 * แก้ไขข้อมูล
 * @param data ข้อมูลตำแหน่ง
 */
function editDetiail(data: RowDetailPositions) {
  isEdit.value = true;
  modalAdd.value = true;
  dataCopy.value = data;
}

/**
 * ส่งค่า css ออกไปตามเงื่อนไข
 * @param val true/false
 */
function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer inputgreen ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}
function addPosition(data: RowDetailPositions) {
  rows.value = [];
  rows.value.push(data);
}

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

function clearFormPositionSelect() {
  isDisValidate.value = true;
  search.value = "";
  type.value = "positionName";

  setTimeout(() => {
    isDisValidate.value = false;
  }, 1000);
}

function close() {
  props.close?.();
  isPosition.value = false;
  clearFormPositionSelect();
}

async function emitSearch(keyword: string, typeSelect: string) {
  search.value = keyword;
  type.value = typeSelect;
  await searchInput();
}

watch(
  () => props.modal,
  () => {
    if (props.modal === true) {
      if (props.actionType === "ADD") {
        rowsPositionSelect.value = [];
        search.value = "";
        rows.value = [];
        clearFormPositionSelect();
        formData.prefixNo = "";
        formData.positionNo = "";
        formData.suffixNo = "";
      } else {
        props.rowId && fetchPosition(props.rowId);
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="min-width: 80vw">
      <DialogHeader
        :tittle="
          props.actionType === 'ADD' ? 'เพิ่มอัตรากำลัง' : 'แก้ไขอัตรากำลัง111'
        "
        :close="close"
      />
      <q-separator />
      <form @submit.prevent="validateForm">
        <q-card-section class="q-pa-sm fixed-height">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-card bordered class="col-12" style="border: 1px solid #d6dee1">
                <div
                  class="col-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
                >
                  ข้อมูลอัตรากำลัง
                </div>
                <div class="col-12"><q-separator /></div>
                <div class="row q-col-gutter-sm col-12 q-pa-sm">
                  <div class="row col-8 q-col-gutter-sm">
                    <div class="col-12">
                      <q-input
                        v-model="formData.shortName"
                        dense
                        outlined
                        readonly
                        for="#shortName"
                        label="อักษรย่อ"
                      />
                    </div>
                    <div class="col-4">
                      <q-input
                        v-model="formData.prefixNo"
                        :class="inputEdit(isReadonly)"
                        ref="prefixNoRef"
                        dense
                        outlined
                        for="#prefixNo"
                        label="Prefix เลขที่ตำเเหน่ง"
                      />
                    </div>
                    <div class="col-4">
                      <q-input
                        v-model="formData.positionNo"
                        :class="inputEdit(isReadonly)"
                        ref="positionNoRef"
                        dense
                        outlined
                        for="#positionNo"
                        label="เลขที่ตำแหน่ง"
                        lazy-rules
                        hide-bottom-space
                        :rules="[
                          (val) => !!val || `${'กรุณากรอกเลขที่ตำแหน่ง'}`,
                        ]"
                        mask="########################"
                      />
                    </div>
                    <div class="col-4">
                      <q-input
                        v-model="formData.suffixNo"
                        :class="inputEdit(isReadonly)"
                        dense
                        outlined
                        for="#suffixNo"
                        label="Suffix เลขที่ตำแหน่ง"
                      />
                    </div>
                  </div>
                  <div class="col-4">
                    <q-input
                      v-model="formData.reason"
                      :class="inputEdit(isReadonly)"
                      dense
                      outlined
                      for="#reason"
                      label="หมายเหตุ"
                      type="textarea"
                      rows="4"
                    />
                  </div>

                  <div class="col-12">
                    <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-if="col.name === 'posExecutiveName'">
                              {{ col.value ? col.value : "-" }}
                            </div>

                            <div
                              v-else-if="col.name === 'positionExecutiveField'"
                            >
                              {{ col.value ? col.value : "-" }}
                            </div>
                            <div v-else-if="col.name === 'posLevelName'">
                              {{
                                props.row.posLevelName
                                  ? props.row.isSpecial == true
                                    ? `${props.row.posLevelName} (ฉ)`
                                    : props.row.posLevelName
                                  : "-"
                              }}
                            </div>
                            <div v-else-if="col.name === 'positionArea'">
                              {{ col.value ? col.value : "-" }}
                            </div>
                            <div v-else>
                              {{ col.value }}
                            </div>
                          </q-td>
                        </q-tr>
                      </template>
                    </d-table>
                  </div>
                </div>
                <q-separator />

                <q-card-actions class="bg-white q-pa-xs">
                  <q-btn
                    :icon="!isPosition ? 'mdi-menu-right' : 'mdi-menu-down'"
                    flat
                    color="teal"
                    class="q-ml-sm"
                    label="เพิ่มตำแหน่ง"
                    @click="isPosition = !isPosition"
                    ><q-tooltip>{{
                      !isPosition
                        ? "คลิกเพื่อแสดงส่วนของการเพิ่มตำแหน่ง"
                        : "ปิดหน้าต่างการเพิ่มตำแหน่ง"
                    }}</q-tooltip></q-btn
                  >
                  <q-space />
                </q-card-actions>
              </q-card>
            </div>
          </div>

          <div v-if="isPosition" class="row q-col-gutter-sm q-mt-sm">
            <div class="col-12">
              <q-card bordered class="col-12" style="border: 1px solid #d6dee1">
                <div
                  class="col-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
                >
                  เลือกตำแหน่งที่ต้องการเพิ่ม
                  <q-btn
                    icon="mdi-plus"
                    flat
                    round
                    color="teal"
                    @click="() => (modalAdd = true)"
                    ><q-tooltip>สร้างตำแหน่ง</q-tooltip></q-btn
                  >
                </div>
                <div class="col-12"><q-separator /></div>
                <div class="q-pa-sm">
                  <div class="row col-12 q-col-gutter-sm items-start">
                    <div class="col-12 col-sm-6 col-md-3">
                      <q-select
                        label="ค้นหาจาก"
                        v-model="type"
                        :options="optionFilter"
                        emit-value
                        dense
                        map-options
                        outlined
                        option-label="name"
                        option-value="id"
                      />
                    </div>

                    <div class="col-12 col-sm-6 col-md-6">
                      <q-input
                        ref="searchRef"
                        :class="inputEdit(isReadonly)"
                        v-model="search"
                        outlined
                        clearable
                        dense
                        lazy-rules
                        label="คำค้น"
                        hide-bottom-space
                        :rules="[(val) => !!val || `กรุณากรอกคำค้น`]"
                        @keydown.enter.prevent="searchInput()"
                      />
                    </div>

                    <div class="col-12 col-sm-6 col-md-3">
                      <q-btn
                        color="primary"
                        icon="search"
                        label="ค้นหา"
                        class="full-width q-pa-sm"
                        @click="searchInput()"
                      >
                      </q-btn>
                    </div>
                  </div>

                  <div class="full-width q-mt-sm">
                    <d-table
                      ref="table"
                      :columns="columns"
                      :rows="rowsPositionSelect"
                      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"
                            @click="addPosition(props.row)"
                          >
                            <div v-if="col.name == 'no'">
                              {{ props.rowIndex + 1 }}
                            </div>
                            <div v-else-if="col.name === 'posExecutiveName'">
                              {{ col.value ? col.value : "-" }}
                            </div>

                            <div
                              v-else-if="col.name === 'positionExecutiveField'"
                            >
                              {{ col.value ? col.value : "-" }}
                            </div>
                            <div v-else-if="col.name === 'posLevelName'">
                              {{
                                props.row.posLevelName
                                  ? props.row.isSpecial == true
                                    ? `${props.row.posLevelName} (ฉ)`
                                    : props.row.posLevelName
                                  : "-"
                              }}
                            </div>

                            <div v-else-if="col.name === 'positionArea'">
                              {{ col.value ? col.value : "-" }}
                            </div>
                            <div v-else>
                              {{ col.value }}
                            </div>
                          </q-td>
                          <q-td auto-width>
                            <q-btn
                              flat
                              dense
                              icon="mdi-dots-vertical"
                              class="q-pa-none q-ml-xs"
                              color="grey-13"
                            >
                              <q-menu anchor="bottom middle" self="top middle">
                                <q-list
                                  dense
                                  v-for="(item, index) in listMenu"
                                  :key="index"
                                >
                                  <q-item
                                    clickable
                                    v-close-popup
                                    @click="
                                      item.type === 'copy'
                                        ? copyDetiail(props.row)
                                        : item.type === 'edit'
                                        ? editDetiail(props.row)
                                        : deletePos(props.row.id)
                                    "
                                  >
                                    <q-item-section avatar>
                                      <q-icon
                                        :color="item.color"
                                        :name="item.icon"
                                        size="sm"
                                      />
                                    </q-item-section>
                                    <q-item-section>{{
                                      item.label
                                    }}</q-item-section>
                                  </q-item>
                                </q-list>
                              </q-menu>
                            </q-btn>
                          </q-td>
                        </q-tr>
                      </template>
                    </d-table>
                  </div>
                </div>
              </q-card>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn type="submit" :label="`บันทึก`" color="public" />
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
  <DialogAddPosition
    v-model:modalAdd="modalAdd"
    :emitSearch="emitSearch"
    :data="dataCopy"
    v-model:is-edit="isEdit"
    :get-data="searchInput"
  />
</template>

<style scoped>
.fixed-height {
  overflow-y: auto;
  height: 80vh;
}
</style>
