<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { checkPermission } from "@/utils/permissions";

import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

import { useCounterMixin } from "@/stores/mixin";
import { useSalaryDataStore } from "@/modules/04_registryPerson/stores/salary";

import type { QTableColumn } from "quasar";
import type {
  DataPositions,
  DataCommandCode,
  DataPosType,
  DataPosLevel,
  DataPosPosition,
  DataPosExecutive,
} from "@/modules/04_registryPerson/interface/response/Position";
import type { DataOption } from "@/modules/04_registryPerson/interface/index/Main";
import type { FormSalary } from "@/modules/04_registryPerson/interface/request/Salary";
import type { ResListSalary } from "@/modules/04_registryPerson/interface/response/Salary";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogHistory from "@/modules/04_registryPerson/components/detail/DialogHistory.vue";
import DialogPreviewCommand from "@/modules/18_command/components/DialogPreviewCommand.vue";

const { findOrgName } = useCounterMixin();
const $q = useQuasar();
const route = useRoute();
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);

/** props*/
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});

const store = useSalaryDataStore();
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  pathRegistryEmp,
  onSearchDataTable,
  convertDateToAPI,
  findOrgNameHtml,
} = useCounterMixin();

const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));

//Table
const rows = ref<ResListSalary[]>([]); //รายการตำแหน่งเงินเดือน
const rowsMain = ref<ResListSalary[]>([]); //รายการตำแหน่งเงินเดือน
const keyword = ref<string>(""); //คำค้นหา
const modalCommand = ref<boolean>(false);
const command = ref<string>("");
const commandId = ref<string>("");
const baseColumns = ref<QTableColumn[]>([
  {
    name: "commandDateAffect",
    align: "left",
    label: "วันที่คำสั่งมีผล",
    sortable: true,
    field: "commandDateAffect",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandDateSign",
    align: "left",
    label: "วันที่ลงนาม",
    sortable: true,
    field: "commandDateSign",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posNo",
    align: "left",
    label: empType.value === "-employee" ? "ตำแหน่งเลขที่" : "เลขที่ตำแหน่ง",
    sortable: true,
    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
        : "-";
    },
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionName",
    align: "left",
    label: empType.value === "-employee" ? "ตำแหน่ง" : "ตำแหน่งในสายงาน",
    sortable: true,
    field: "positionName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionType",
    align: "left",
    label: empType.value === "-employee" ? "กลุ่มงาน" : "ตำแหน่งประเภท",
    sortable: true,
    field: "positionType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionLevel",
    align: "left",
    label: empType.value === "-employee" ? "ระดับชั้นงาน" : "ระดับ",
    sortable: true,
    field: "positionLevel",
    format(val, row) {
      return `${
        row.positionLevel
          ? row.positionLevel
          : row.positionCee
          ? row.positionCee
          : "-"
      }`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionExecutive",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "positionExecutive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "commandNo",
    format(val, row) {
      return row.commandNo && row.commandYear
        ? `${row.commandNo}/${Number(row.commandYear) + 543}`
        : "";
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandCode",
    align: "left",
    label: "ประเภทคำสั่ง",
    sortable: true,
    field: "commandCode",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return findOrgName({
        root: row.orgRoot,
        child1: row.orgChild1,
        child2: row.orgChild2,
        child3: row.orgChild3,
        child4: row.orgChild4,
      });
    },
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "amount",
    align: "left",
    label: empType.value === "-employee" ? "ค่าจ้าง" : "เงินเดือน",
    sortable: true,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(v, row) {
      return row.amount
        ? `${row.amount.toLocaleString()}${
            row.amountSpecial !== 0 && row.amountSpecial
              ? ` (${row.amountSpecial.toLocaleString()})`
              : ""
          }`
        : "-";
    },
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "mouthSalaryAmount",
    align: "left",
    label: "เงินค่าตอบแทนรายเดือน",
    sortable: true,
    field: "mouthSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionSalaryAmount",
    align: "left",
    label: "เงินประจำตำแหน่ง",
    sortable: true,
    field: "positionSalaryAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Number(v).toLocaleString(),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },

  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v, false, true),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const baseVisibleColumns = ref<string[]>([
  "commandDateAffect",
  "posNo",
  "positionName",
  "positionType",
  "positionLevel",
  "positionExecutive",
  "amount",
  "positionSalaryAmount",
  "mouthSalaryAmount",
  "commandNo",
  "commandCode",
  "commandDateSign",
  "organization",
  "remark",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

const columns = computed<QTableColumn[]>(() => {
  if (empType.value === "-employee") {
    if (baseColumns.value) {
      return baseColumns.value.filter(
        (column) =>
          column.name !== "positionSalaryAmount" &&
          column.name !== "mouthSalaryAmount"
      );
    }
  }
  return baseColumns.value.filter(
    (e: QTableColumn) =>
      e.name !== "lastUpdateFullName" && e.name !== "lastUpdatedAd"
  );
});
const visibleColumns = ref<string[]>(
  baseVisibleColumns.value.filter(
    (e: string) => e !== "lastUpdateFullName" && e !== "lastUpdatedAd"
  )
);
const pagination = ref({
  sortBy: "",
});

const columnsHistory = computed<QTableColumn[]>(() => {
  if (empType.value === "-employee") {
    if (baseColumns.value) {
      return baseColumns.value.filter(
        (column) =>
          column.name !== "positionSalaryAmount" &&
          column.name !== "mouthSalaryAmount"
      );
    }
  }
  return baseColumns.value;
});
const visibleColumnsHistory = ref<string[]>(baseVisibleColumns.value);

const formData = reactive<FormSalary>({
  commandCode: "", //ประเภทคำสั่ง
  commandNo: "", //เลขที่คำสั่ง
  commandYear: null, //ปี
  commandDateAffect: null, //วันที่มีผล
  commandDateSign: null, //วันที่ลงนาม
  posNoAbb: "", //ตัวย่อเลขที่ตำแหน่ง
  posNo: "", //เลขที่ตำแหน่ง
  positionName: "", //ตำแหน่ง
  positionType: "", //ประเภทตำแหน่ง | กลุ่มงาน
  positionLevel: "", //ระดับตำแหน่ง | ระดับชั้นงาน
  positionCee: "", //ตำแหน่งซี
  positionLine: "", // สายงาน
  positionPathSide: "", //ด้าน/สาขา
  positionExecutive: "", //ตำแหน่งทางการบริหาร
  amount: null, //เงินเดือน
  amountSpecial: null, //เงินค่าตอบแทนพิเศษ
  positionSalaryAmount: null, //เงินประจำตำแหน่ง
  mouthSalaryAmount: null, //เงินค่าตอบแทนรายเดือน
  orgRoot: "", //หน่วยงาน
  orgChild1: "", //ส่วนราชการระดับ 1
  orgChild2: "", //ส่วนราชการระดับ 2
  orgChild3: "", //ส่วนราชการระดับ 3
  orgChild4: "", //ส่วนราชการระดับ 4
  remark: "", //หมายเหตุ
});

const modalDialogSalary = ref<boolean>(false); //แสดง popup ตำแหน่งเงินเดือน
const isStatusEdit = ref<boolean>(false); //สถานะแก้ไขข้อมูลตำแหน่งเงินเดือน
const salaryId = ref<string>(""); //id ที่ต้องการแก้ไข
const dataLevel = ref<DataPosType[]>([]); //รายการ ตำแหน่งเงินเดือน

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

/** function fetch รายการ ตำแหน่งเงินเดือน*/
async function fetchListSalary() {
  showLoader();
  await http
    .get(config.API.profileListSalaryNew(profileId.value, empType.value))
    .then((res) => {
      rows.value = res.data.result;
      rowsMain.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function fetch ข้อมูลประเภทคำสั่ง*/
async function fetchDataCommandCode() {
  if (store.commandCodeData.length > 0) return false;
  await http
    .get(config.API.orgCommandCode)
    .then((res) => {
      const data = res.data.result;
      const DataCommandCode = data.filter((e: DataCommandCode) =>
        store.salaryCode.includes(e.code)
      );

      const options = DataCommandCode.map((e: DataCommandCode) => ({
        id: e.code.toString(),
        name: e.name,
      }));

      store.commandCodeData = options;
      commandCodeOptions.value = options;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function fetch ข้อมูลปรเภทตำแหน่งข้าราชการ */
async function fetchType() {
  await http
    .get(config.API.orgPosType)
    .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);
    });
}

/** function fetch ข้อมูลปรเภทตำแหน่งลูกจ้าง*/
async function fetchOptionGroup() {
  await http
    .get(config.API.orgEmployeeType)
    .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);
    });
}

/** function fetch ข้อมูลสายงาน*/
async function fetchDataOption() {
  if (store.posLineData.length > 0 && store.posPathSideData.length > 0)
    return false;

  await http
    .get(config.API.orgPosPosition + `?keyword=&type=ALL`)
    .then((res) => {
      const data = res.data.result;

      const seen = new Set();
      const seen2 = new Set();

      const listPositionField = data.filter((item: DataPosPosition) => {
        if (seen.has(item.positionField)) {
          return false;
        } else {
          seen.add(item.positionField);
          return true;
        }
      });
      store.posLineData = listPositionField.map((e: DataPosPosition) => ({
        id: e.positionField,
        name: e.positionField,
      }));

      const listPositionArea = data.filter((item: DataPosPosition) => {
        if (
          item.positionArea === null ||
          item.positionArea === "" ||
          item.positionArea === "-" ||
          seen2.has(item.positionArea)
        ) {
          return false;
        } else {
          seen2.add(item.positionArea);
          return true;
        }
      });
      store.posPathSideData = listPositionArea.map((e: DataPosPosition) => ({
        id: e.positionArea,
        name: e.positionArea,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** function fetch ข้อมูลตำแหน่งข้อมูลทางการบริหาร*/
async function fetchDataOptionExecutive() {
  await http
    .get(config.API.orgPosExecutive)
    .then((res) => {
      const data = res.data.result;
      store.posExecutiveData = data.map((e: DataPosExecutive) => ({
        id: e.posExecutiveName,
        name: e.posExecutiveName,
      }));
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/**
 * function เลือกประเภทตำแหน่ง
 * @param val id ประเภทตำแหน่ง
 * @param status แก่ไข , เพิ่ม
 */
async function updateSelectType(val: string, status: boolean = false) {
  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 === ""
          ? e.posLevelName
          : `${listLevel.posTypeShortName} ${e.posLevelName}`,
    }));

    formData.positionLevel = !status ? "" : formData.positionLevel;
  } else {
    store.posLevelData = [];
    formData.positionLevel = "";
  }
}

/**
 * function  เปิด dialog ตำแหน่งเงินเดือน
 * @param statusEdit แก้ไข,เพิ่ม
 * @param data
 */
async function onClickOpenDialog(
  statusEdit: boolean = false,
  data: DataPositions = {} as DataPositions
) {
  showLoader();
  if (empType.value === "") {
    await Promise.all([
      fetchType(),
      fetchDataOption(),
      fetchDataOptionExecutive(),
    ]);
  } else {
    await fetchOptionGroup();
  }
  commandCodeOptions.value = store.commandCodeData;
  posTypeOptions.value = store.posTypeData;
  posLevelOptions.value = store.posLevelData;
  posLineOptions.value = store.posLineData;
  posPathSideOptions.value = store.posPathSideData;
  posExecutiveOptions.value = store.posExecutiveData;

  //  หาระดับตำแหน่ง
  statusEdit && (await updateSelectType(data.positionType, true));
  isStatusEdit.value = statusEdit;

  store.posLevelData = !statusEdit ? [] : store.posLevelData;
  modalDialogSalary.value = true;
  salaryId.value = data.id;
  formData.commandCode = statusEdit ? data.commandCode : "";
  formData.commandNo = statusEdit ? data.commandNo : "";
  formData.commandYear = statusEdit ? data.commandYear : null;
  formData.commandDateAffect = statusEdit ? data.commandDateAffect : null;
  formData.commandDateSign = statusEdit ? data.commandDateSign : null;
  formData.posNoAbb = statusEdit ? data.posNoAbb : "";
  formData.posNo = statusEdit ? data.posNo : "";
  formData.positionName = statusEdit ? data.positionName : "";
  formData.positionType = statusEdit ? data.positionType : "";
  formData.positionLevel = statusEdit ? data.positionLevel : "";
  formData.positionCee = statusEdit ? data.positionCee : "";
  formData.positionLine = statusEdit ? data.positionLine : "";
  formData.positionPathSide = statusEdit ? data.positionPathSide : "";
  formData.positionExecutive = statusEdit ? data.positionExecutive : "";
  formData.amount = statusEdit ? data.amount : null;
  formData.amountSpecial = statusEdit ? data.amountSpecial : null;
  formData.positionSalaryAmount = statusEdit ? data.positionSalaryAmount : null;
  formData.mouthSalaryAmount = statusEdit ? data.mouthSalaryAmount : null;
  formData.orgRoot = statusEdit ? data.orgRoot : "";
  formData.orgChild1 = statusEdit ? data.orgChild1 : "";
  formData.orgChild2 = statusEdit ? data.orgChild2 : "";
  formData.orgChild3 = statusEdit ? data.orgChild3 : "";
  formData.orgChild4 = statusEdit ? data.orgChild4 : "";
  formData.remark = statusEdit ? data.remark : "";
  hideLoader();
}

/** function  ปิด dialog ตำแหน่งเงินเดือน*/
function onClickCloseDialog() {
  modalDialogSalary.value = false;
}

/** function ยืนยันการบันทึกข้อมูล */
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    try {
      const url = isStatusEdit.value
        ? config.API.profileListSalaryNew(salaryId.value, empType.value)
        : config.API.profileSalaryNew(empType.value);
      const method = isStatusEdit.value ? "patch" : "post";
      await http[method](url, {
        profileEmployeeId:
          !isStatusEdit.value && empType.value !== ""
            ? profileId.value
            : undefined,
        profileId:
          !isStatusEdit.value && empType.value === ""
            ? profileId.value
            : undefined,
        ...formData,
        commandDateAffect: convertDateToAPI(formData.commandDateAffect),
        commandDateSign: convertDateToAPI(formData.commandDateSign),
        amount: Number(String(formData.amount)?.replace(/,/g, "")),
        amountSpecial: Number(
          String(formData.amountSpecial)?.replace(/,/g, "")
        ),
        positionSalaryAmount: Number(
          String(formData.positionSalaryAmount)?.replace(/,/g, "")
        ),
        mouthSalaryAmount: Number(
          String(formData.mouthSalaryAmount)?.replace(/,/g, "")
        ),
      });
      await fetchListSalary();
      onClickCloseDialog();
      success($q, "บันทึกข้อมูลสำเร็จ");
    } catch (e) {
      messageError($q, e);
    } finally {
      hideLoader();
    }
  });
}

const modalHistory = ref<boolean>(false);

/**
 * ฟิลเตอร์ข้อมูลจาก 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;

    case "posLine":
      update(() => {
        posLineOptions.value = store.posLineData.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    case "posPathSide":
      update(() => {
        posPathSideOptions.value = store.posPathSideData.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    case "posExecutive":
      update(() => {
        posExecutiveOptions.value = store.posExecutiveData.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;

    default:
      break;
  }
}
/**
 * function ดูข้อมูลประวัติการแก้ไขรายการเงินเดือน
 * @param id รายการเงินเดือน
 */
function onClikcHistory(id: string) {
  salaryId.value = id;
  modalHistory.value = true;
}

/** function fetch ข้อมูลประวัติการแก้ไข*/
async function fetchDataHistory() {
  showLoader();
  try {
    const res = await http.get(
      config.API.profileListSalaryHistoryNew(salaryId.value, empType.value)
    );

    return res.data.result;
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

const classInput = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};

function onRefCommand(data: ResListSalary) {
  modalCommand.value = true;
  command.value = data.refCommandNo;
  commandId.value = data.commandId;
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    keyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

/** ทำงานเมื่อ Components ถูกเรียกใช้งาน*/
onMounted(async () => {
  showLoader();
  try {
    await Promise.all([fetchListSalary(), fetchDataCommandCode()]);
  } finally {
    hideLoader();
  }
});
</script>

<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
      flat
      color="primary"
      round
      dense
      icon="add"
      @click="onClickOpenDialog()"
    >
      <q-tooltip>เพิ่มข้อมูล</q-tooltip>
    </q-btn>
    <q-space />
    <q-input
      dense
      outlined
      v-model="keyword"
      label="ค้นหา"
      class="q-mr-sm"
      @keydown.enter.pervent="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 class="col-12">
    <d-table
      ref="table"
      row-key="id"
      flat
      bordered
      dense
      :columns="columns"
      :rows="rows"
      v-model:pagination="pagination"
      :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-medium">{{ col.label }}</span>
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td>
            <q-btn
              flat
              dense
              round
              color="deep-purple"
              icon="mdi-history"
              @click="onClikcHistory(props.row.id)"
            >
              <q-tooltip>ประวัติแก้ไขตำแหน่ง/เงินเดือน</q-tooltip>
            </q-btn>

            <q-btn
              v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
              flat
              :disable="
                props.row.commandId !== null && props.row.commandId !== ''
              "
              :color="props.row.commandId ? 'grey' : 'edit'"
              dense
              round
              icon="edit"
              clickable
              @click="onClickOpenDialog(true, props.row)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
          </q-td>

          <q-td
            v-for="col in props.cols"
            :key="col.id"
            :class="props.row.isEntry ? 'text-red' : ''"
          >
            <div
              v-if="col.name == 'commandNo' && props.row.commandId"
              @click="col.value ? onRefCommand(props.row) : null"
              :class="
                col.value
                  ? 'table_ellipsis text-blue cursor-pointer'
                  : 'table_ellipsis'
              "
            >
              {{ col.value ? col.value : "-" }}
              <q-tooltip v-if="col.value">ดูคำสั่ง</q-tooltip>
            </div>

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

  <q-dialog v-model="modalDialogSalary" persistent>
    <q-card style="min-width: 40vw">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="isStatusEdit ? 'แก้ไขเงินเดือน' : 'เพิ่มเงินเดือน'"
          :close="onClickCloseDialog"
        />
        <q-separator color="grey-4" />

        <q-card-section style="max-height: 100%" class="scroll">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-12 col-sm-12 col-md-8">
              <!-- :rules="[(val: string) => !!val || 'กรุณาเลือกประเภทคำสั่ง']" -->
              <q-select
                outlined
                :class="classInput(true)"
                dense
                lazy-rules
                borderless
                v-model="formData.commandCode"
                :label="`${'ประเภทคำสั่ง'}`"
                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="updateSelectType"
                @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>

            <div class="col-xs-6 col-sm-6 col-md-4">
              <!-- :rules="[ (val: string) => !!val || `${'กรุณาเลือกวันที่คำสั่งมีผล'}`, ]" -->
              <datepicker
                v-model="formData.commandDateAffect"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                :class="classInput(true)"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    outlined
                    dense
                    borderless
                    :model-value="date2Thai(formData.commandDateAffect)"
                    :label="`${'วันที่คำสั่งมีผล'}`"
                    hide-bottom-space
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        color="primary"
                        class="cursor-pointer"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <div class="col-xs-6 col-sm-12 col-md-8">
              <div class="row q-col-gutter-sm">
                <div class="col-6">
                  <q-input
                    :class="classInput(true)"
                    outlined
                    dense
                    lazy-rules
                    borderless
                    v-model="formData.commandNo"
                    hide-bottom-space
                    :label="`${'เลขที่คำสั่ง'}`"
                  />
                </div>
                <label class="col-1 flex justify-center items-center">/</label>
                <div class="col-5">
                  <!-- :rules="[(val:string) => !!val || `${'กรุณากรอก พ.ศ.'}`]" -->
                  <datepicker
                    menu-class-name="modalfix"
                    v-model="formData.commandYear"
                    :locale="'th'"
                    autoApply
                    year-picker
                    :enableTimePicker="false"
                    class="inputgreen"
                  >
                    <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="`${'พ.ศ.'}`"
                      >
                        <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>
            </div>

            <div class="col-xs-6 col-sm-6 col-md-4">
              <!-- :rules="[ (val: string) => !!val || `${'กรุณาเลือก วันที่ลงนาม'}`,]" -->
              <datepicker
                v-model="formData.commandDateSign"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                :class="classInput(true)"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    outlined
                    dense
                    borderless
                    :model-value="date2Thai(formData.commandDateSign)"
                    :label="`${'วันที่ลงนาม'}`"
                    hide-bottom-space
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        color="primary"
                        class="cursor-pointer"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <div class="col-12">
              <q-separator />
            </div>

            <div class="col-xs-6 col-sm-6 col-md-4">
              <q-input
                :class="classInput(true)"
                outlined
                dense
                lazy-rules
                borderless
                v-model="formData.posNoAbb"
                hide-bottom-space
                :label="`${'ตัวย่อ'}`"
              >
              </q-input>
            </div>

            <div class="col-xs-6 col-sm-6 col-md-4">
              <!-- :rules="[(val: string) => !!val || `${'กรุณากรอกตำแหน่งเลขที่'}`]" -->
              <q-input
                :class="classInput(true)"
                outlined
                dense
                lazy-rules
                borderless
                v-model="formData.posNo"
                hide-bottom-space
                :label="empType === '' ? 'เลขที่ตำแหน่ง' : 'ตำแหน่งเลขที่'"
              >
              </q-input>
            </div>

            <div class="col-xs-12 col-sm-6 col-md-4">
              <!-- :rules="empType == '' ? [(val: string) => !!val || 'กรุณากรอกตำแหน่งในสายงาน' ] : [(val: string) => !!val ||   'กรุณากรอกตำแหน่ง']" -->
              <q-input
                :class="classInput(true)"
                outlined
                dense
                lazy-rules
                borderless
                v-model="formData.positionName"
                :label="empType == '' ? 'ตำแหน่งในสายงาน' : 'ตำแหน่ง'"
                hide-bottom-space
              />
            </div>

            <div class="col-xs-6 col-sm-6 col-md-4">
              <!-- :rules="empType == '' ? [(val: string) => !!val || 'กรุณาเลือกประเภทตำแหน่ง'  ]:[(val: string) => !!val ||  'กรุณาเลือกกลุ่มงาน' ]" -->
              <q-select
                ref="positionType Ref"
                outlined
                :class="classInput(true)"
                dense
                lazy-rules
                borderless
                v-model="formData.positionType"
                :label="empType == '' ? 'ประเภทตำแหน่ง' : 'กลุ่มงาน'"
                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"
                @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>
            </div>

            <div class="col-xs-6 col-sm-6 col-md-4">
              <!-- :rules="empType == '' ? [(val: string) => !!val || 'กรุณาเลือกระดับตำแหน่ง' ] : [(val: string) => !!val ||   'กรุณาเลือกระดับชั้นงาน']" -->
              <q-select
                :class="classInput(true)"
                :disable="!formData.positionType"
                outlined
                dense
                lazy-rules
                borderless
                v-model="formData.positionLevel"
                :label="empType == '' ? 'ระดับตำแหน่ง' : 'ระดับชั้นงาน'"
                emit-value
                map-options
                option-label="name"
                :options="posLevelOptions"
                option-value="name"
                hide-bottom-space
                use-input
                hide-selected
                fill-input
                input-debounce="0"
                @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>
            </div>

            <div class="col-xs-6 col-sm-6 col-md-4" v-if="empType == ''">
              <q-input
                :class="classInput(true)"
                outlined
                dense
                lazy-rules
                borderless
                v-model="formData.positionCee"
                hide-bottom-space
                :label="`${'ระดับซี'}`"
              >
              </q-input>
            </div>

            <div class="col-xs-6 col-sm-6 col-md-4" v-if="empType == ''">
              <q-select
                outlined
                :class="classInput(true)"
                dense
                lazy-rules
                borderless
                v-model="formData.positionLine"
                :label="`${'สายงาน'}`"
                emit-value
                map-options
                option-label="name"
                :options="posLineOptions"
                option-value="id"
                hide-bottom-space
                use-input
                hide-selected
                fill-input
                clearable
                input-debounce="0"
                @filter="(inputValue: string,
                      doneFn: Function) => filterSelector(inputValue, doneFn, 'posLine'
                      )"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template></q-select
              >
            </div>

            <div class="col-xs-6 col-sm-6 col-md-4" v-if="empType == ''">
              <q-select
                :class="classInput(true)"
                outlined
                dense
                lazy-rules
                borderless
                v-model="formData.positionPathSide"
                :label="`${'ด้าน/สาขา'}`"
                emit-value
                map-options
                option-label="name"
                :options="posPathSideOptions"
                option-value="id"
                hide-bottom-space
                use-input
                hide-selected
                fill-input
                clearable
                input-debounce="0"
                @filter="(inputValue: string,
                      doneFn: Function) => filterSelector(inputValue, doneFn, 'posPathSide'
                      )"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </div>

            <div class="col-xs-6 col-sm-6 col-md-4" v-if="empType == ''">
              <q-select
                :class="classInput(true)"
                outlined
                dense
                lazy-rules
                borderless
                v-model="formData.positionExecutive"
                :label="`${'ตำแหน่งทางการบริหาร'}`"
                emit-value
                map-options
                option-label="name"
                :options="posExecutiveOptions"
                option-value="id"
                hide-bottom-space
                use-input
                hide-selected
                fill-input
                input-debounce="0"
                clearable
                @filter="(inputValue: string,
                    doneFn: Function) => filterSelector(inputValue, doneFn, 'posExecutive'
                    )"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </div>

            <div class="col-12">
              <div class="row q-col-gutter-sm">
                <div class="col-xs-6 col-sm-6 col-md-4">
                  <q-input
                    :class="classInput(true)"
                    ref="salaryRef"
                    dense
                    outlined
                    v-model="formData.amount"
                    label="เงินเดือน"
                    mask="###,###,###,###"
                    reverse-fill-mask
                    :rules="[(val:string) => !!val || `${'กรุณากรอกเงินเดือน'}`]"
                    lazy-rules
                    hide-bottom-space
                  />
                </div>

                <div class="col-xs-6 col-sm-6 col-md-4">
                  <q-input
                    :class="classInput(true)"
                    ref="amountSpecialRef"
                    dense
                    outlined
                    v-model="formData.amountSpecial"
                    label="เงินค่าตอบแทนพิเศษ"
                    mask="###,###,###,###"
                    reverse-fill-mask
                    hide-bottom-space
                  />
                </div>

                <div class="col-xs-6 col-sm-6 col-md-4">
                  <q-input
                    :class="classInput(true)"
                    dense
                    outlined
                    v-model="formData.positionSalaryAmount"
                    label="เงินประจำตำแหน่ง"
                    mask="###,###,###,###"
                    reverse-fill-mask
                    lazy-rules
                    hide-bottom-space
                  />
                </div>

                <div class="col-xs-6 col-sm-6 col-md-4">
                  <q-input
                    :class="classInput(true)"
                    dense
                    outlined
                    v-model="formData.mouthSalaryAmount"
                    label="เงินค่าตอบแทนรายเดือน"
                    mask="###,###,###,###"
                    reverse-fill-mask
                    lazy-rules
                    hide-bottom-space
                  />
                </div>
              </div>
            </div>

            <div class="col-xs-12 col-sm-12 col-md-12">
              <div class="row q-col-gutter-sm">
                <div class="col-xs-12 col-sm-4 col-md-4">
                  <q-input
                    :class="classInput(true)"
                    outlined
                    dense
                    lazy-rules
                    borderless
                    v-model="formData.orgRoot"
                    hide-bottom-space
                    :label="`${'หน่วยงาน'}`"
                  />
                </div>

                <div class="col-xs-12 col-sm-4 col-md-4">
                  <q-input
                    :class="classInput(true)"
                    outlined
                    dense
                    lazy-rules
                    borderless
                    v-model="formData.orgChild1"
                    hide-bottom-space
                    :label="`${'ส่วนราชการระดับ 1'}`"
                  />
                </div>

                <div class="col-xs-12 col-sm-4 col-md-4">
                  <q-input
                    :class="classInput(true)"
                    outlined
                    dense
                    lazy-rules
                    borderless
                    v-model="formData.orgChild2"
                    hide-bottom-space
                    :label="`${'ส่วนราชการระดับ 2'}`"
                  />
                </div>

                <div class="col-xs-12 col-sm-4 col-md-4">
                  <q-input
                    :class="classInput(true)"
                    outlined
                    dense
                    lazy-rules
                    borderless
                    v-model="formData.orgChild3"
                    hide-bottom-space
                    :label="`${'ส่วนราชการระดับ 3'}`"
                  />
                </div>

                <div class="col-xs-12 col-sm-4 col-md-4">
                  <q-input
                    :class="classInput(true)"
                    outlined
                    dense
                    lazy-rules
                    borderless
                    v-model="formData.orgChild4"
                    hide-bottom-space
                    :label="`${'ส่วนราชการระดับ 4'}`"
                  />
                </div>
              </div>
            </div>

            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                :class="classInput(true)"
                ref="docRef"
                outlined
                dense
                borderless
                v-model="formData.remark"
                :label="`${'หมายเหตุ'}`"
                type="textarea"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" id="onSubmit" type="submit" color="public">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <!-- <DialogHistory v-model:modal="modalHistory" v-model:salaryId="salaryId" /> -->

  <DialogHistory
    v-model:modal="modalHistory"
    :visible-columns="visibleColumnsHistory"
    :title="`ประวัติแก้ไขเงินเดือน`"
    :columns="columnsHistory"
    :fetch-data="fetchDataHistory"
  />

  <DialogPreviewCommand
    v-model:modal="modalCommand"
    v-model:command="command"
    v-model:commandId="commandId"
  />
</template>

<style scoped></style>
