<script setup lang="ts">
import { ref, onMounted, computed, reactive } from "vue";
import { useQuasar } from "quasar";
import * as XLSX from "xlsx";

import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useEditPosDataStore } from "@/modules/04_registryPerson/stores/Edit";
import { exportToExcelPosition } from "@/modules/04_registryPerson/utils/exportPosition";

import type { QTableColumn } from "quasar";
import type { FormDataSalary } from "@/modules/04_registryPerson/interface/index/Edit";
import type { DataOption } from "@/modules/04_registryPerson/interface/index/Main";
import type { DataPosition } from "@/modules/04_registryPerson/interface/response/Edit";
import type {
  DataPosType,
  DataPosLevel,
} from "@/modules/04_registryPerson/interface/response/Position";

import DialogForm from "@/modules/04_registryPerson/views/edit/components/DialogForm.vue";
import DialogSort from "@/modules/04_registryPerson/views/edit/components/DialogSort.vue";
import CurruncyInput from "@/components/CurruncyInput.vue";

const $q = useQuasar();
const route = useRoute();
const store = useEditPosDataStore();
const {
  date2Thai,
  findOrgName,
  onSearchDataTable,
  dialogRemove,
  showLoader,
  hideLoader,
  messageError,
  success,
  findOrgNameHtml,
  dialogConfirm,
  convertDateToAPI,
} = useCounterMixin();

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

const tabs = defineModel<string>("tabs", { required: true });
const isConfirmEdit = defineModel<boolean>("isConfirmEdit", { required: true });
const statusCheckEdit = defineModel<string>("statusCheckEdit", {
  required: true,
});

const amountRef = ref<any>(null);
const amountSpecialRef = ref<any>(null);
const currencyPopupRef = ref<any>(null);

//Table
const isLoad = ref<boolean>(true);
const rowIndex = ref<number>(0);
const rows = ref<DataPosition[]>([]);
const rowsMain = ref<DataPosition[]>([]);
const keyword = ref<string>("");
const baseColumns = ref<QTableColumn[]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "commandDateAffect",
    align: "left",
    label: "วันที่คำสั่งมีผล",
    sortable: false,
    field: "commandDateAffect",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
  },
  {
    name: "positionName",
    align: "left",
    label: empType.value === "employee" ? "ตำแหน่ง" : "ตำแหน่งในสายงาน",
    sortable: false,
    field: "positionName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionType",
    align: "left",
    label: empType.value === "employee" ? "กลุ่มงาน" : "ตำแหน่งประเภท",
    sortable: false,
    field: "positionType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionLevel",
    align: "left",
    label: empType.value === "employee" ? "ระดับชั้นงาน" : "ระดับ",
    sortable: false,
    field: "positionLevel",
    format(val, row) {
      return `${
        row.positionLevel
          ? row.positionLevel
          : row.positionCee
          ? row.positionCee
          : "-"
      }`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionExecutive",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: false,
    field: "positionExecutive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionExecutiveField",
    align: "left",
    label: "ด้านทางการบริหาร",
    sortable: false,
    field: "positionExecutiveField",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "amount",
    align: "left",
    label: empType.value === "employee" ? "ค่าจ้าง" : "เงินเดือน",
    sortable: false,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(v, row) {
      return row.amount
        ? `${Number(row.amount).toLocaleString()}${
            row.amountSpecial !== 0 && row.amountSpecial
              ? ` (${Number(row.amountSpecial).toLocaleString()})`
              : ""
          }`
        : "-";
    },
  },
  {
    name: "mouthSalaryAmount",
    align: "left",
    label: "เงินค่าตอบแทนรายเดือน",
    sortable: false,
    field: "mouthSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => (v ? Number(v).toLocaleString() : "-"),
  },
  {
    name: "positionSalaryAmount",
    align: "left",
    label: "เงินประจำตำแหน่ง",
    sortable: false,
    field: "positionSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => (v ? Number(v).toLocaleString() : "-"),
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: false,
    field: "organization",
    headerStyle: "font-size: 14px;min-width: 280px",
    style: "font-size: 14px",
    format(val, row) {
      return findOrgName({
        root: row.orgRoot,
        child1: row.orgChild1,
        child2: row.orgChild2,
        child3: row.orgChild3,
        child4: row.orgChild4,
      });
    },
  },
  {
    name: "posNo",
    align: "left",
    label: empType.value === "employee" ? "ตำแหน่งเลขที่" : "เลขที่ตำแหน่ง",
    sortable: false,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.posNoAbb && row.posNo
        ? `${row.posNoAbb} ${row.posNo}`
        : row.posNo
        ? row.posNo
        : "-";
    },
  },
  {
    name: "posNumCodeSit",
    align: "left",
    label: "หน่วยงานที่ออกคำสั่ง",
    sortable: false,
    field: "posNumCodeSit",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.posNumCodeSitAbb && row.posNumCodeSit
        ? `${row.posNumCodeSit} (${row.posNumCodeSitAbb})`
        : row.posNumCodeSit
        ? row.posNumCodeSit
        : "-";
    },
  },
  {
    name: "commandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: false,
    field: "commandNo",
    format(val, row) {
      return row.commandNo && row.commandYear
        ? `${row.commandNo}/${Number(row.commandYear) + 543}`
        : "-";
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "commandDateSign",
    align: "left",
    label: "วันที่ลงนาม",
    sortable: false,
    field: "commandDateSign",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
  },
  {
    name: "commandCode",
    align: "left",
    label: "ประเภทคำสั่ง",
    sortable: false,
    field: "commandCode",
    format(val, row) {
      return store.convertCommandCodeName(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: false,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "commandDateAffect",
  "positionName",
  "positionType",
  "positionLevel",
  "positionExecutive",
  "positionExecutiveField",
  "amount",
  "mouthSalaryAmount",
  "positionSalaryAmount",
  "organization",
  "posNo",
  "posNumCodeSit",
  "commandNo",
  "commandDateSign",
  "commandCode",
  "remark",
]);
const columns = computed<QTableColumn[]>(() => {
  if (empType.value === "employee") {
    if (baseColumns.value) {
      return baseColumns.value.filter(
        (column) =>
          column.name !== "positionSalaryAmount" &&
          column.name !== "mouthSalaryAmount" &&
          column.name !== "positionExecutive" &&
          column.name !== "positionExecutivefield"
      );
    }
  }
  return baseColumns.value;
});

const modal = ref<boolean>(false);
const modalSort = ref<boolean>(false);
const isAddPosition = ref<boolean>(true); // สถานะการเพิ่มตำแหน่ง

/** function fetch ข้อมูลรายการตำแหน่งเงินเดือน*/
async function fetchData() {
  isLoad.value = true;
  const paht =
    tabs.value === "PENDING"
      ? `/${empType.value}/${profileId.value}`
      : `/${empType.value}/done/${profileId.value}`;
  http
    .get(config.API.salaryTemp + `${paht}`)
    .then((res) => {
      const data = res.data.result;
      rowsMain.value = data;
      rows.value = data;
      serchDataTable();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoad.value = false;
    });
}

/** function ค้นหาข้อมูลรายการในตาราง*/
function serchDataTable() {
  rows.value = onSearchDataTable(
    keyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

/**
 * funciton
 * @param index
 */
function onEditData(index: number) {
  rowIndex.value = index;
  modal.value = true;
  isAddPosition.value = index === -1; // ถ้า index เป็น -1 แสดงว่าเป็นการเพิ่มข้อมูลใหม่
}

/**
 * function สลับตำแหน่งของข้อมูลขึ้นลง
 * @param action up , down
 * @param id id รายการที่ต้องการสลับตะแหน่ง
 */
async function onSwapData(action: string, id: string) {
  showLoader();
  await http
    .get(config.API.salaryTemp + `/swap/${action}/${id}`)
    .then(async () => {
      await fetchData();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function ลบข้อมูลรายการตำแหน่งเงินเดือน
 * @param id id ที่ต้องการลบข้อมูลรายการตำแหน่งเงินเดือน
 * @param isDelete true ลบข้อมูลรานการตำแหน่งเงินเดือน false นำข้อมูลรายการที่ลบไปกลับมา
 */
function onConfirmDeleteData(id: string, isDelete: boolean) {
  isDelete
    ? dialogConfirm(
        $q,
        () => {
          onDeleteData(id, isDelete);
        },
        "ยืนยันการย้อนกลับข้อมูล",
        "ต้องการยืนยันการย้อนกลับข้อมูลนี้ใช่หรือไม่?"
      )
    : dialogRemove($q, () => {
        onDeleteData(id, isDelete);
      });
}

/**
 * function ลบข้อมูลรายการตำแหน่งเงินเดือน
 * @param id id ที่ต้องการลบข้อมูลรายการตำแหน่งเงินเดือน
 * @param isDelete true ลบข้อมูลรานการตำแหน่งเงินเดือน false นำข้อมูลรายการที่ลบไปกลับมา
 */
async function onDeleteData(id: string, isDelete: boolean) {
  showLoader();
  const path = isDelete ? "/delete-renew" : "/delete";
  await http
    .post(config.API.salaryTemp + `${path}`, {
      type: empType.value,
      salaryId: id,
    })
    .then(async () => {
      await fetchData();
      success($q, isDelete ? "ย้อนกลับข้อมูลสำเร็จ" : "ลบข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * class สีของข้อความ
 * @param isDelete รายการที่ลบ
 * @param isEdit รายการที่แก้ไข
 * @param isEntry รายการข้อมูลที่มากจาก Entry
 * @returns class ส
 */
function classColorRow(isDelete: boolean, isEdit: boolean, isEntry: boolean) {
  return isDelete
    ? "text-red"
    : isEdit
    ? "text-orange"
    : isEntry
    ? "text-grey"
    : "";
}

/** ฟังก์ชันดาวน์โหลดไฟล Excel */
function exportToExcel() {
  exportToExcelPosition(rows.value);
  // const newData = rows.value.map((e: DataPosition) => {
  //   return {
  //     commandDateAffect: date2Thai(e.commandDateAffect),
  //     positionName: e.positionName,
  //     positionType: e.positionType,
  //     positionLevel: e.positionLevel
  //       ? e.positionLevel
  //       : e.positionCee
  //       ? e.positionCee
  //       : "",
  //     positionExecutive: e.positionExecutive,
  //     amount: e.amount,
  //     mouthSalaryAmount: e.mouthSalaryAmount,
  //     positionSalaryAmount: e.positionSalaryAmount,
  //     organization: findOrgName({
  //       root: e.orgRoot,
  //       child1: e.orgChild1,
  //       child2: e.orgChild2,
  //       child3: e.orgChild3,
  //       child4: e.orgChild4,
  //     }),
  //     posNo:
  //       e.posNoAbb && e.posNo
  //         ? `${e.posNoAbb} ${e.posNo}`
  //         : e.posNo
  //         ? e.posNo
  //         : "",
  //     posNumCodeSit:
  //       e.posNumCodeSitAbb && e.posNumCodeSit
  //         ? `${e.posNumCodeSit} (${e.posNumCodeSitAbb})`
  //         : e.posNumCodeSit
  //         ? e.posNumCodeSit
  //         : "",
  //     commandNo:
  //       e.commandNo && e.commandYear
  //         ? `${e.commandNo}/${Number(e.commandYear) + 543}`
  //         : "",
  //     commandDateSign: date2Thai(e.commandDateSign),
  //     commandCode: store.convertCommandCodeName(e.commandCode),
  //     remark: e.remark,
  //   };
  // });

  // const headers = columns.value.map((item: any) => item.label) || []; // หัวคอลัมน์ภาษาไทย
  // const worksheet = XLSX.utils.json_to_sheet(newData, {
  //   header: visibleColumns.value,
  // });

  // //แทรกหัวคอลัมน์ภาษาไทย (ใช้ A1, B1, C1 แทน)
  // XLSX.utils.sheet_add_aoa(worksheet, [headers], { origin: "A1" });

  // // Create a new workbook and append the worksheet
  // const workbook = XLSX.utils.book_new();

  // XLSX.utils.book_append_sheet(
  //   workbook,
  //   worksheet,
  //   `รายการประวัติตำแหน่งเงินเดือน`
  // );
  // XLSX.writeFile(workbook, "รายการประวัติตำแหน่งเงินเดือน.xlsx");
}

const commandCodeOptions = ref<DataOption[]>(store.commandCodeData); //รายการปรเภทคำสั่ง
const posTypeOptions = ref<DataOption[]>(store.posTypeData); //รายการประเภทตำแหน่ง | กลุ่มงาน
const posLevelOptions = ref<DataOption[]>(store.posLevelData); //รายการระดับตำแหน่ง | ระดับชั้นงาน
const dataLevel = ref<DataPosType[]>([]); //รายการ ตำแหน่งเงินเดือน

const formData = reactive<FormDataSalary>({
  positionLevel: "",
  positionCee: "",
  amount: 0,
  amountSpecial: 0,
  posNoAbb: "",
  posNo: "",
  orgRoot: "",
  orgChild1: "",
  orgChild2: "",
  orgChild3: "",
  orgChild4: "",
  commandCode: "",
  posNumCodeSit: "",
  posNumCodeSitAbb: "",
  commandNo: "",
  commandYear: null,
});

const isPositionName = ref<boolean>(false); //เช็คว่ามี ตำแหน่งประเภท
const isUpdateData = ref<boolean>(false); // สถานะการแก้ไข
const colNameMain = ref<string>(""); //ชื่อ Coolumn ที่ต้องการแก้ไข
const salaryId = ref<string>(""); // id ที่ต้องการแก้ไข

/**
 * ฟังก์ชันกำหนดค่าที่ต้องการแก้ไข
 * @param data ข้อมูลที่ต้องการแก้ไข
 * @param colName ชื่อ Columns ที่ต้เองการแก้ไข
 */
function onShow(data: DataPosition, colName: string) {
  salaryId.value = data.id;
  isUpdateData.value = false;
  commandCodeOptions.value = store.commandCodeData;
  posTypeOptions.value = store.posTypeData;
  if (colName === "positionLevel" && data.positionType) {
    updateSelectType(data.positionType);
  }
  colNameMain.value = colName;
  isPositionName.value = data.positionType ? true : false;
  formData.positionLevel = data.positionLevel;
  formData.positionCee = data.positionCee;
  formData.amount = data.amount;
  formData.amountSpecial = data.amountSpecial;
  formData.orgRoot = data.orgRoot;
  formData.orgChild1 = data.orgChild1;
  formData.orgChild2 = data.orgChild2;
  formData.orgChild3 = data.orgChild3;
  formData.orgChild4 = data.orgChild4;
  formData.posNoAbb = data.posNoAbb;
  formData.posNo = data.posNo;
  formData.commandCode = data.commandCode;
  formData.posNumCodeSit = data.posNumCodeSit;
  formData.posNumCodeSitAbb = data.posNumCodeSitAbb;
  formData.commandNo = data.commandNo;
  formData.commandYear = data.commandYear;
}

/**
 * ฟังก์ชันบันทึกข้อมูลการแก้ไข
 * @param val
 * @param id
 * @param close
 */
async function onSave(val: any, id: string, close?: () => void) {
  // ตรวจสอบ validation ถ้า amountRef มีค่าและมี validate method
  if (amountRef.value && typeof amountRef.value.validate === "function") {
    const isValid = amountRef.value.validate();
    if (isValid === false) {
      return; // หยุดการบันทึกถ้า validation ไม่ผ่าน
    }
  }

  if (isUpdateData.value) {
    showLoader();
    const isCol = (key: string) => colNameMain.value === key;
    const toNumber = (v: any) =>
      v ? Number(String(v).replace(/,/g, "")) : null;
    const body: Record<string, any> = {};
    if (isCol("commandDateAffect")) {
      body.commandDateAffect = convertDateToAPI(val);
    }
    if (isCol("positionName")) {
      body.positionName = val;
    }
    if (isCol("positionType")) {
      body.positionType = val;
    }
    if (isCol("positionLevel")) {
      body.positionLevel = formData.positionLevel;
      body.positionCee = formData.positionCee;
    }
    if (isCol("positionExecutive")) {
      body.positionExecutive = val;
    }
    if (isCol("positionExecutiveField")) {
      body.positionExecutiveField = val;
    }
    if (isCol("amount")) {
      body.amount = toNumber(formData.amount);
      body.amountSpecial = toNumber(formData.amountSpecial);
    }
    if (isCol("positionSalaryAmount")) {
      body.positionSalaryAmount = toNumber(val);
    }
    if (isCol("mouthSalaryAmount")) {
      body.mouthSalaryAmount = toNumber(val);
    }
    if (isCol("organization")) {
      body.orgRoot = formData.orgRoot;
      body.orgChild1 = formData.orgChild1;
      body.orgChild2 = formData.orgChild2;
      body.orgChild3 = formData.orgChild3;
      body.orgChild4 = formData.orgChild4;
    }
    if (isCol("posNo")) {
      body.posNo = formData.posNo;
      body.posNoAbb = formData.posNoAbb;
    }
    if (isCol("posNumCodeSit")) {
      body.posNumCodeSit = formData.posNumCodeSit;
      body.posNumCodeSitAbb = formData.posNumCodeSitAbb;
    }
    if (isCol("commandDateSign")) {
      body.commandDateSign = convertDateToAPI(val);
    }
    if (isCol("commandNo")) {
      body.commandNo = formData.commandNo;
      body.commandYear = formData.commandYear;
    }
    if (isCol("commandCode")) {
      body.commandCode = formData.commandCode;
    }
    if (isCol("remark")) {
      body.remark = val;
    }

    await http
      .patch(config.API.salaryTemp + `/${salaryId.value}`, body)
      .then(async () => {
        success($q, "บันทึกข้อมูลสำเร็จ");
        const idx = rows.value.findIndex((item) => item.id === salaryId.value);
        // อัปเดทข้อมูลในตาราง
        if (idx !== -1) {
          rows.value[idx] = {
            ...rows.value[idx],
            ...body,
          };
        }

        // อัปเดทข้อมูลหลัก
        const idxMain = rowsMain.value.findIndex(
          (item) => item.id === salaryId.value
        );
        if (idxMain !== -1) {
          rowsMain.value[idxMain] = {
            ...rowsMain.value[idxMain],
            ...body,
          };
        }
      })
      .catch(async (err) => {
        await fetchData?.();
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
        if (close) close();
      });
  } else {
    if (close) {
      close();
    }
  }
}

/**
 * ฟิลเตอร์ข้อมูลจาก input
 * @param val ค่าที่ป้อนให้ input
 * @param update function จาก quasar
 * @param filtername type ที่กำหนด ของ input นั้นๆ
 */
function filterSelector(val: string, update: Function, filtername: string) {
  switch (filtername) {
    case "commandCode":
      update(() => {
        commandCodeOptions.value = store.commandCodeData.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    case "posType":
      update(() => {
        posTypeOptions.value = store.posTypeData.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    case "posLevel":
      update(() => {
        posLevelOptions.value = store.posLevelData.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    default:
      break;
  }
}

/** ฟังก์ชันเรียกข้อมูลปรเภทตำแหน่งข้าราชการ */
async function fetchType() {
  const entpont =
    empType.value === "officer"
      ? config.API.orgPosType
      : config.API.orgEmployeeType;
  await http
    .get(entpont)
    .then((res) => {
      dataLevel.value = res.data.result;
      store.posTypeData = res.data.result.map((e: DataPosType) => ({
        id: e.id,
        name: e.posTypeName,
      }));
      posTypeOptions.value = store.posTypeData;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * ฟังก์ชันเลือกประเภทตำแหน่ง
 * @param val id ประเภทตำแหน่ง
 */
async function updateSelectType(val: string) {
  const listLevel = val
    ? dataLevel.value.find((e: DataPosType) => e.posTypeName === val)
    : null;

  // เช็คประเภทตำแหน่งงาน
  if (listLevel) {
    store.posLevelData = listLevel.posLevels.map((e: DataPosLevel) => ({
      id: e.id,
      name:
        empType.value === "officer"
          ? e.posLevelName
          : `${listLevel.posTypeShortName} ${e.posLevelName}`,
    }));
  }
}

/** ฟังก์ชันอัปเดทการแก้ไข*/
function onUpdateData() {
  isUpdateData.value = true;
}

/**
 * ฟังก์ชันตรวจสอบ validation และบันทึกข้อมูลสำหรับทุกประเภท
 */
async function validateAndSave(
  val: any,
  id: string,
  close?: () => void,
  fieldType: "amount" | "currency" | "normal" = "normal"
) {
  let isValid = true;

  // ตรวจสอบ validation สำหรับ amount fields
  if (fieldType === "amount") {
    // Validate เงินเดือน
    if (formData.amount !== null && formData.amount !== undefined) {
      const amountNum =
        typeof formData.amount === "number"
          ? formData.amount
          : Number(String(formData.amount).replace(/,/g, ""));
      if (amountNum > 10000000) {
        isValid = false;
      }
    }

    // Validate เงินค่าตอบแทนพิเศษ
    if (
      isValid &&
      formData.amountSpecial !== null &&
      formData.amountSpecial !== undefined
    ) {
      const amountSpecialNum =
        typeof formData.amountSpecial === "number"
          ? formData.amountSpecial
          : Number(String(formData.amountSpecial).replace(/,/g, ""));
      if (amountSpecialNum > 10000000) {
        isValid = false;
      }
    }

    // Force validate refs ถ้ามี
    if (
      isValid &&
      amountRef.value &&
      typeof amountRef.value.validate === "function"
    ) {
      const amountValid = amountRef.value.validate();
      isValid = isValid && amountValid !== false;
    }

    if (
      isValid &&
      amountSpecialRef.value &&
      typeof amountSpecialRef.value.validate === "function"
    ) {
      const amountSpecialValid = amountSpecialRef.value.validate();
      isValid = isValid && amountSpecialValid !== false;
    }
  }

  // ตรวจสอบ validation สำหรับ currency fields อื่นๆ
  else if (fieldType === "currency") {
    // Validate ค่าโดยตรงก่อน
    if (val !== null && val !== undefined) {
      const numVal =
        typeof val === "number" ? val : Number(String(val).replace(/,/g, ""));
      if (numVal > 10000000) {
        isValid = false;
      }
    }

    // Force validate ref ถ้ามี
    if (
      isValid &&
      currencyPopupRef.value &&
      typeof currencyPopupRef.value.validate === "function"
    ) {
      const currencyValid = currencyPopupRef.value.validate();
      isValid = isValid && currencyValid !== false;
    }
  }

  // บันทึกข้อมูลถ้า validation ผ่าน
  if (isValid) {
    await onSave(val, id, close);
    return true;
  } else {
    // หยุดการบันทึกถ้า validation ไม่ผ่าน (rules จะแสดง error message เอง)
    return false;
  }
}

/**
 * ฟังก์ชันอัปโหลดไฟล์ Excel
 * ส่งไฟล์ Excel ไปยัง API โดยตรง
 */
function handUploadFile() {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".xlsx,.xls";

  input.onchange = async (e: Event) => {
    try {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;

      // ตรวจสอบชนิดไฟล์โดยตรวจสอบนามสกุล
      const validExtensions = [".xlsx", ".xls"];
      const fileExtension = file.name
        .substring(file.name.lastIndexOf("."))
        .toLowerCase();

      if (!validExtensions.includes(fileExtension)) {
        messageError("กรุณาเลือกไฟล์ Excel เท่านั้น (.xlsx, .xls)");
        return;
      }

      showLoader();
      const type = empType.value === "officer" ? "office" : "employee";
      const formData = new FormData();
      formData.append("file", file);

      await http.post(
        config.API.uploadProfile(type, profileId.value),
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      );

      success($q, "อัปโหลดไฟล์สำเร็จ");
      await fetchData();
    } catch (error) {
      messageError($q, error);
    } finally {
      hideLoader();
    }
  };

  input.click();
}

onMounted(async () => {
  await Promise.all([fetchData(), fetchType()]);
});
</script>

<template>
  <div class="row q-col-gutter-sm">
    <div class="col-12">
      <div class="row q-col-gutter-sm items-center">
        <q-btn
          v-if="
            tabs === 'PENDING' && statusCheckEdit == 'PENDING' && isConfirmEdit
          "
          class="q-ml-sm"
          round
          flat
          dense
          color="primary"
          icon="add"
          @click.stop.prevent="onEditData(-1)"
        >
          <q-tooltip>จัดลำดับข้อมูล</q-tooltip></q-btn
        >
        <q-btn
          v-if="
            tabs === 'PENDING' && statusCheckEdit == 'PENDING' && isConfirmEdit
          "
          class="q-ml-sm"
          round
          flat
          dense
          color="blue"
          icon="mdi-sort"
          @click="modalSort = true"
        >
          <q-tooltip>จัดลำดับข้อมูล</q-tooltip></q-btn
        >
        <q-space />
        <div>
          <q-btn
            v-if="
              tabs === 'PENDING' &&
              statusCheckEdit == 'PENDING' &&
              isConfirmEdit
            "
            flat
            round
            color="blue"
            icon="upload"
            @click="handUploadFile()"
          >
            <q-tooltip>อัปโหลดไฟล์แก้ไข</q-tooltip>
          </q-btn>
          <q-btn
            flat
            round
            color="primary"
            icon="download"
            :disable="rows.length == 0"
            @click="exportToExcel()"
          >
            <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
          </q-btn>
        </div>

        <q-input
          dense
          outlined
          v-model="keyword"
          label="ค้นหา"
          @keydown.enter.prevent="serchDataTable"
        >
          <template v-slot:append>
            <q-icon name="search" />
          </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"
          style="min-width: 140px"
        />
      </div>
    </div>

    <div class="col-12">
      <d-table
        ref="table"
        row-key="id"
        flat
        bordered
        dense
        :columns="columns"
        :rows="rows"
        :paging="true"
        :rows-per-page-options="[20, 50, 100, 150, 200, 0]"
        :visible-columns="visibleColumns"
        :loading="isLoad"
      >
        >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th
              v-if="
                tabs === 'PENDING' &&
                statusCheckEdit == 'PENDING' &&
                isConfirmEdit
              "
            />
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              <span class="text-weight-medium">{{ col.label }}</span>
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td
              v-if="
                tabs === 'PENDING' &&
                statusCheckEdit == 'PENDING' &&
                isConfirmEdit
              "
            >
              <q-btn
                dense
                flat
                round
                :color="props.rowIndex + 1 == 1 ? 'grey' : 'green'"
                :disable="props.rowIndex + 1 == 1"
                icon="mdi-arrow-up-bold"
                @click.stop.prevent="onSwapData('up', props.row.id)"
              />
              <q-btn
                dense
                flat
                round
                :color="rows.length == props.rowIndex + 1 ? 'grey' : 'red'"
                :disable="rows.length == props.rowIndex + 1"
                icon="mdi-arrow-down-bold"
                @click.stop.prevent="onSwapData('down', props.row.id)"
              >
              </q-btn>

              <q-btn
                flat
                dense
                round
                color="edit"
                icon="edit"
                @click.stop.prevent="onEditData(props.rowIndex)"
              >
                <q-tooltip>แก้ไขข้อมูล</q-tooltip>
              </q-btn>
              <q-btn
                flat
                dense
                round
                :icon="props.row.isDelete ? 'mdi-refresh-circle' : 'delete'"
                :color="props.row.isDelete ? 'orange' : 'red'"
                @click.stop.prevent="
                  onConfirmDeleteData(props.row.id, props.row.isDelete)
                "
              >
                <q-tooltip>{{
                  props.row.isDelete ? "ย้อนกลับข้อมูล" : "ลบ"
                }}</q-tooltip>
              </q-btn>
            </q-td>

            <q-td
              v-for="col in props.cols"
              :key="col.id"
              :class="
                tabs === 'PENDING'
                  ? classColorRow(
                      props.row.isDelete,
                      props.row.isEdit,
                      props.row.isEntry
                    )
                  : ''
              "
            >
              <div v-if="col.name === 'no'">
                {{ props.rowIndex + 1 }}
              </div>

              <div
                v-else-if="
                  col.name === 'positionLevel' ||
                  col.name === 'amount' ||
                  col.name === 'posNo' ||
                  col.name === 'posNumCodeSit' ||
                  col.name === 'commandNo' ||
                  col.name === 'commandCode'
                "
              >
                {{ col.value ?? "-" }}
                <q-popup-edit
                  v-if="
                    tabs === 'PENDING' &&
                    statusCheckEdit == 'PENDING' &&
                    isConfirmEdit
                  "
                  v-model="props.row[col.name]"
                  v-slot="scope"
                  label-set="บันทึก"
                  label-cancel="ยกเลิก"
                  @before-show="onShow(props.row, col.name)"
                  :persistent="
                    col.name === 'commandNo' || col.name === 'amount'
                  "
                  :buttons="false"
                  @save="null"
                >
                  <div class="q-mb-xs">
                    {{ `แก้ไข${col.label}` }}
                  </div>
                  <div v-if="col.name === 'positionLevel'">
                    <q-select
                      v-if="isPositionName || props.row.positionLevel"
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.positionLevel"
                      :label="
                        empType === 'officer' ? 'ระดับตำแหน่ง' : 'ระดับชั้นงาน'
                      "
                      emit-value
                      map-options
                      option-label="name"
                      :options="posLevelOptions"
                      option-value="name"
                      hide-bottom-space
                      use-input
                      hide-selected
                      clearable
                      fill-input
                      input-debounce="0"
                      @update:model-value="onUpdateData"
                      @filter="(inputValue: string,
                    doneFn: Function) => filterSelector(inputValue, doneFn, 'posLevel'
                    )"
                      ><template v-slot:no-option>
                        <q-item>
                          <q-item-section class="text-grey">
                            ไม่มีข้อมูล
                          </q-item-section>
                        </q-item>
                      </template>
                    </q-select>

                    <q-input
                      v-else
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.positionCee"
                      hide-bottom-space
                      @update:model-value="onUpdateData"
                    />
                  </div>

                  <div class="q-gutter-sm" v-if="col.name === 'amount'">
                    <CurruncyInput
                      ref="amountRef"
                      :edit="true"
                      dense
                      outlined
                      v-model="formData.amount"
                      label="เงินเดือน"
                      lazy-rules
                      hide-bottom-space
                      @update:model-value="onUpdateData"
                      :rules="[ 
                            (val:number) => {
                              if (!val) return true;
                              const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                              return numVal <= 10000000 || 'เงินเดือนต้องไม่เกิน 10,000,000 บาท';
                            }
                          ]"
                    />
                    <CurruncyInput
                      ref="amountSpecialRef"
                      :edit="true"
                      dense
                      outlined
                      v-model="formData.amountSpecial"
                      label="เงินค่าตอบแทนพิเศษ"
                      hide-bottom-space
                      lazy-rules
                      @update:model-value="onUpdateData"
                      :rules="[ 
                            (val:number) => {
                              if (!val) return true;
                              const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                              return numVal <= 10000000 || 'เงินค่าตอบแทนพิเศษต้องไม่เกิน 10,000,000 บาท';
                            }
                          ]"
                    />

                    <!-- Custom buttons สำหรับ amount -->
                    <div class="row justify-around q-pt-sm">
                      <q-btn
                        flat
                        color="primary"
                        label="ยกเลิก"
                        @click="scope.cancel"
                      />
                      <q-btn
                        flat
                        color="primary"
                        label="บันทึก"
                        @click="
                          validateAndSave(
                            formData,
                            props.row.id,
                            scope.cancel,
                            'amount'
                          )
                        "
                      />
                    </div>
                  </div>

                  <div class="q-gutter-sm" v-else-if="col.name === 'posNo'">
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.posNoAbb"
                      hide-bottom-space
                      :label="`${'ตัวย่อ'}`"
                      @update:model-value="onUpdateData"
                    />

                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.posNo"
                      hide-bottom-space
                      :label="
                        empType === 'officer'
                          ? 'เลขที่ตำแหน่ง'
                          : 'ตำแหน่งเลขที่'
                      "
                      @update:model-value="onUpdateData"
                    >
                    </q-input>
                  </div>

                  <div
                    class="q-gutter-sm"
                    v-else-if="col.name === 'posNumCodeSit'"
                  >
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.posNumCodeSit"
                      hide-bottom-space
                      :label="`${'หน่วยงานที่ออกคำสั่ง'}`"
                      @update:model-value="onUpdateData"
                    />

                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.posNumCodeSitAbb"
                      hide-bottom-space
                      :label="`${'ตัวย่อหน่วยงานที่ออกคำสั่ง'}`"
                      @update:model-value="onUpdateData"
                    />
                  </div>

                  <div class="q-gutter-sm" v-else-if="col.name === 'commandNo'">
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.commandNo"
                      hide-bottom-space
                      :label="`${'เลขที่คำสั่ง'}`"
                      @update:model-value="onUpdateData"
                    />

                    <datepicker
                      v-model="formData.commandYear"
                      :locale="'th'"
                      autoApply
                      year-picker
                      :enableTimePicker="false"
                      @update:model-value="onUpdateData"
                    >
                      <template #year="{ year }">{{ year + 543 }}</template>
                      <template #year-overlay-value="{ value }">{{
                        parseInt(value + 543)
                      }}</template>
                      <template #trigger>
                        <q-input
                          dense
                          outlined
                          hide-bottom-space
                          :model-value="
                            formData.commandYear == null
                              ? null
                              : formData.commandYear + 543
                          "
                          label="ปี พ.ศ."
                          clearable
                          @clear="formData.commandYear = null"
                          @update:model-value="onUpdateData"
                        >
                          <template v-slot:prepend>
                            <q-icon
                              name="event"
                              class="cursor-pointer"
                              style="color: var(--q-primary)"
                            >
                            </q-icon>
                          </template>
                        </q-input>
                      </template>
                    </datepicker>
                  </div>

                  <div
                    class="q-gutter-sm"
                    v-else-if="col.name === 'commandCode'"
                  >
                    <q-select
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.commandCode"
                      emit-value
                      map-options
                      option-label="name"
                      :options="commandCodeOptions"
                      option-value="id"
                      hide-bottom-space
                      use-input
                      hide-selected
                      fill-input
                      input-debounce="0"
                      @update:model-value="onUpdateData"
                      @filter="(inputValue: string,
                doneFn: Function) => filterSelector(inputValue, doneFn, 'commandCode'
                )"
                    >
                      <template v-slot:no-option>
                        <q-item>
                          <q-item-section class="text-grey">
                            ไม่มีข้อมูล
                          </q-item-section>
                        </q-item>
                      </template>
                    </q-select>
                  </div>

                  <!-- Default buttons สำหรับ fields อื่นๆ (ไม่ใช่ amount และ positionLevel) -->
                  <div
                    v-if="col.name !== 'amount' && col.name !== 'positionLevel'"
                    class="row justify-around q-pt-sm"
                  >
                    <q-btn
                      flat
                      color="primary"
                      label="ยกเลิก"
                      @click="scope.cancel"
                    />

                    <q-btn
                      flat
                      color="primary"
                      label="บันทึก"
                      @click="
                        validateAndSave(
                          formData,
                          props.row.id,
                          scope.cancel,
                          'normal'
                        )
                      "
                    />
                  </div>

                  <!-- Custom buttons สำหรับ positionLevel -->
                  <div
                    v-if="col.name === 'positionLevel'"
                    class="row justify-around q-pt-sm"
                  >
                    <q-btn
                      flat
                      color="primary"
                      label="ยกเลิก"
                      @click="scope.cancel"
                    />
                    <q-btn
                      flat
                      color="primary"
                      label="บันทึก"
                      @click="
                        validateAndSave(
                          formData,
                          props.row.id,
                          scope.cancel,
                          'normal'
                        )
                      "
                    />
                  </div>
                </q-popup-edit>
              </div>

              <div v-else-if="col.name === 'organization'" class="text-html">
                {{
                  findOrgNameHtml({
                    root: props.row.orgRoot,
                    child1: props.row.orgChild1,
                    child2: props.row.orgChild2,
                    child3: props.row.orgChild3,
                    child4: props.row.orgChild4,
                  })
                }}

                <q-popup-edit
                  v-if="
                    tabs === 'PENDING' &&
                    statusCheckEdit == 'PENDING' &&
                    isConfirmEdit
                  "
                  v-model="props.row[col.name]"
                  v-slot="scope"
                  label-set="บันทึก"
                  label-cancel="ยกเลิก"
                  @before-show="onShow(props.row, col.name)"
                  :buttons="false"
                  @save="null"
                >
                  <div class="q-mb-xs">
                    {{ `แก้ไข${col.label}` }}
                  </div>

                  <div class="q-gutter-sm">
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.orgRoot"
                      hide-bottom-space
                      :label="`${'หน่วยงาน'}`"
                      @update:model-value="onUpdateData"
                    />
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.orgChild1"
                      hide-bottom-space
                      :label="`${'ส่วนราชการระดับ 1'}`"
                      @update:model-value="onUpdateData"
                    />

                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.orgChild2"
                      hide-bottom-space
                      :label="`${'ส่วนราชการระดับ 2'}`"
                      @update:model-value="onUpdateData"
                    />
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.orgChild3"
                      hide-bottom-space
                      :label="`${'ส่วนราชการระดับ 3'}`"
                      @update:model-value="onUpdateData"
                    />

                    <q-input
                      outlined
                      dense
                      lazy-rules
                      borderless
                      v-model="formData.orgChild4"
                      hide-bottom-space
                      :label="`${'ส่วนราชการระดับ 4'}`"
                      @update:model-value="onUpdateData"
                    />
                  </div>
                  <div class="row justify-around q-pt-sm">
                    <q-btn
                      flat
                      color="primary"
                      label="ยกเลิก"
                      @click="scope.cancel"
                    />

                    <q-btn
                      flat
                      color="primary"
                      label="บันทึก"
                      @click="
                        validateAndSave(
                          formData,
                          props.row.id,
                          scope.cancel,
                          'normal'
                        )
                      "
                    />
                  </div>
                </q-popup-edit>
              </div>

              <div v-else>
                {{ col.value ? col.value : "-" }}
                <q-popup-edit
                  v-if="
                    tabs === 'PENDING' &&
                    statusCheckEdit == 'PENDING' &&
                    isConfirmEdit
                  "
                  v-slot="scope"
                  :persistent="
                    col.name === 'commandDateAffect' ||
                    col.name === 'commandDateSign' ||
                    col.name === 'mouthSalaryAmount' ||
                    col.name === 'positionSalaryAmount'
                  "
                  v-model="props.row[col.name]"
                  :buttons="
                    col.name !== 'mouthSalaryAmount' &&
                    col.name !== 'positionSalaryAmount' &&
                    col.name !== 'commandDateAffect' &&
                    col.name !== 'commandDateSign' &&
                    col.name !== 'positionName' &&
                    col.name !== 'positionExecutive' &&
                    col.name !== 'positionExecutiveField' &&
                    col.name !== 'remark' &&
                    col.name !== 'positionType'
                  "
                  label-set="บันทึก"
                  label-cancel="ยกเลิก"
                  @save="
                    col.name === 'mouthSalaryAmount' ||
                    col.name === 'positionSalaryAmount' ||
                    col.name === 'commandDateAffect' ||
                    col.name === 'commandDateSign' ||
                    col.name === 'positionName' ||
                    col.name === 'positionExecutive' ||
                    col.name === 'positionExecutiveField' ||
                    col.name === 'remark' ||
                    col.name === 'positionType'
                      ? null
                      : onSave
                  "
                  @before-show="onShow(props.row, col.name)"
                >
                  <div class="q-mb-xs">
                    {{ `แก้ไข${col.label}` }}
                  </div>

                  <!-- แก้ไขวันที่คำสั่งมีผล -->
                  <datepicker
                    v-if="
                      col.name === 'commandDateAffect' ||
                      col.name === 'commandDateSign'
                    "
                    v-model="scope.value"
                    :locale="'th'"
                    :enableTimePicker="false"
                    week-start="0"
                    autoApply
                    @update:model-value="onUpdateData"
                  >
                    <template #year="{ year }">{{ year + 543 }}</template>
                    <template #year-overlay-value="{ value }">{{
                      parseInt(value + 543)
                    }}</template>
                    <template #trigger>
                      <q-input
                        outlined
                        dense
                        borderless
                        :model-value="
                          scope.value ? date2Thai(scope.value) : null
                        "
                        hide-bottom-space
                      >
                        <template v-slot:prepend>
                          <q-icon
                            name="event"
                            color="primary"
                            class="cursor-pointer"
                          />
                        </template>
                      </q-input>
                    </template>
                  </datepicker>

                  <q-input
                    v-else-if="
                      col.name === 'positionName' ||
                      col.name === 'positionExecutive' ||
                      col.name === 'positionExecutiveField' ||
                      col.name === 'remark'
                    "
                    outlined
                    dense
                    lazy-rules
                    borderless
                    v-model="scope.value"
                    hide-bottom-space
                    @update:model-value="onUpdateData"
                  />

                  <CurruncyInput
                    v-else-if="
                      col.name === 'mouthSalaryAmount' ||
                      col.name === 'positionSalaryAmount'
                    "
                    :ref="`currencyRef_${col.name}`"
                    :edit="true"
                    dense
                    outlined
                    v-model="scope.value"
                    lazy-rules
                    hide-bottom-space
                    @update:model-value="onUpdateData"
                    :rules="[ 
                            (val:number) => {
                              if (!val) return true;
                              const numVal = typeof val === 'number' ? val : Number(String(val).replace(/,/g, ''));
                              return numVal <= 10000000 || `${col.label}ต้องไม่เกิน 10,000,000 บาท`;
                            }
                          ]"
                  />

                  <q-select
                    v-else-if="col.name === 'positionType'"
                    outlined
                    dense
                    lazy-rules
                    borderless
                    v-model="scope.value"
                    :label="
                      empType === 'officer' ? 'ตำแหน่งประเภท' : 'กลุ่มงาน'
                    "
                    emit-value
                    map-options
                    option-label="name"
                    :options="posTypeOptions"
                    option-value="name"
                    hide-bottom-space
                    use-input
                    hide-selected
                    fill-input
                    clearable
                    input-debounce="0"
                    @update:model-value="updateSelectType, onUpdateData()"
                    @filter="(inputValue: string,
                  doneFn: Function) => filterSelector(inputValue, doneFn, 'posType'
                  )"
                  >
                    <template v-slot:no-option>
                      <q-item>
                        <q-item-section class="text-grey">
                          ไม่มีข้อมูล
                        </q-item-section>
                      </q-item>
                    </template>
                  </q-select>

                  <!-- Custom buttons สำหรับ persistent fields -->
                  <div
                    v-if="
                      col.name === 'mouthSalaryAmount' ||
                      col.name === 'positionSalaryAmount' ||
                      col.name === 'commandDateAffect' ||
                      col.name === 'commandDateSign'
                    "
                    class="row justify-around q-pt-sm"
                  >
                    <q-btn
                      flat
                      color="primary"
                      label="ยกเลิก"
                      @click="scope.cancel"
                    />
                    <q-btn
                      flat
                      color="primary"
                      label="บันทึก"
                      @click="
                        col.name === 'mouthSalaryAmount' ||
                        col.name === 'positionSalaryAmount'
                          ? validateAndSave(
                              scope.value,
                              props.row.id,
                              scope.cancel,
                              'currency'
                            )
                          : validateAndSave(
                              scope.value,
                              props.row.id,
                              scope.cancel,
                              'normal'
                            )
                      "
                    />
                  </div>

                  <!-- Default buttons สำหรับ fields อื่นๆ ที่ไม่ใช่ persistent -->
                  <div
                    v-else-if="
                      col.name === 'positionName' ||
                      col.name === 'positionExecutive' ||
                      col.name === 'positionExecutiveField' ||
                      col.name === 'remark' ||
                      col.name === 'positionType'
                    "
                    class="row justify-around q-pt-sm"
                  >
                    <q-btn
                      flat
                      color="primary"
                      label="ยกเลิก"
                      @click="scope.cancel"
                    />
                    <q-btn
                      flat
                      color="primary"
                      label="บันทึก"
                      @click="
                        validateAndSave(
                          scope.value,
                          props.row.id,
                          scope.cancel,
                          'normal'
                        )
                      "
                    />
                  </div>
                </q-popup-edit>
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </div>

  <DialogForm
    v-model:modal="modal"
    v-model:row-index="rowIndex"
    :emp-type="empType"
    :row-data="rows"
    :fetch-data="fetchData"
    :is-add-position="isAddPosition"
  />

  <DialogSort
    v-model:modal="modalSort"
    :data-sort="rowsMain"
    :fetch-data="fetchData"
    :columns="columns"
  />
</template>

<style scoped></style>
