<script setup lang="ts">
import { ref, onMounted, reactive, watch, computed } from "vue";
import { useQuasar } from "quasar";
import { useRoute, useRouter } from "vue-router";
import moment from "moment";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useComplainstDataStore } from "@/modules/11_discipline/store/ComplaintsStore";
import { useInvestigateDisStore } from "@/modules/11_discipline/store/InvestigateDisStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/Main";

import type {
  FormData,
  Director,
  PersonsArray,
} from "@/modules/11_discipline/interface/request/Disciplinary";
import type {
  DataOption,
  FileLists,
  responseType,
  directorType,
} from "@/modules/11_discipline/interface/index/Main";
import type { OptionData } from "@/modules/07_insignia/interface/index/Main";

import PopupSendToNext from "@/modules/11_discipline/components/PopupSendToNext.vue";
import CalandarDialog from "@/modules/11_discipline/components/3_InvestigateDisciplinary/CalandarDialog.vue";
import DialogDuty from "@/modules/11_discipline/components/DialogDuty.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";
import DialogAddPersonal from "@/components/Dialogs/AddPersonal.vue";
import DialogDirector from "@/modules/11_discipline/components/DialogDirector.vue";
import Table from "@/modules/11_discipline/components/DirectorTable.vue";
import UploadFile from "@/modules/11_discipline/components/UploadFile.vue";

const $q = useQuasar();
const route = useRoute();
const complainstStore = useComplainstDataStore();
const investigateDis = useInvestigateDisStore();
const mainStore = useDisciplineMainStore();
const { filterSelector } = complainstStore; // function จาก store complainstStore
const mixin = useCounterMixin();
const {
  date2Thai,
  showLoader,
  hideLoader,
  dialogConfirm,
  messageError,
  success,
  convertDateToAPI,
} = mixin;

const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");
const isSaveInfo = defineModel<boolean>("isSaveInfo");
const calendarModal = ref<boolean>(false);
const calendarModalclose = () => (calendarModal.value = !calendarModal.value);
const modalPopup = ref<boolean>(false);

const isEmpType = ref<string>("");
const checkRoutePermisson = ref<boolean>(
  route.name == "disciplineDisciplinaryDetail"
);
const organizationOption = ref<DataOption[]>([]);
/** query string*/

const filterKeyword2 = ref<string>("");
const listDirector = ref<any>([]);
const modalEditDirector = ref<boolean>(false);
const editDirectorId = ref<string>();
const dutyVal = ref<string>();
const commandNoVal = ref<string>();

const id = ref<string>(route.params.id as string);
const type = ref<string>("");
const modal = ref<boolean>(false);
const rows = ref<Director[]>([]);
const modalPerson = ref<boolean>(false);
/**  search data table*/

const total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

const isSave = ref<boolean>(false); // มีการแก้ไขรอบันทึก
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const extendStatus = ref<boolean>(false);
const countNum = ref<number>(1);
/** formData*/
const formData = reactive<FormData>({
  respondentType: "",
  organizationId: null,
  organization: "",
  consideredAgency: "",
  disciplinaryDateAllegation: null, //*วันที่รับทราบข้อกล่าวหา
  disciplinaryDateEvident: null, //*วันที่สรุปพยานหลักฐาน
  disciplinaryCaseFault: "", // กรณีความผิด
  disciplinaryInvestigateAt: "", // สอบสวนที่
  disciplinaryFaultLevel: "", // ระดับโทษความผิด
  disciplinaryRefLaw: "", // อ้างอิงมาตราตามกฎหมาย
  disciplinarySummaryEvidence: "", // สรุปพยานหลักฐานสนับสนุนข้อกล่าวหา
  disciplinaryRecordAccuser: "", // บันทึกถ้อยคำของผู้กล่าวหา
  disciplinaryWitnesses: "", // พยานและบันทึกถ้อยคำพยาน
  result: "", // ผลการสอบสวน
  directors: [],
  persons: [],
  extendStatus: false,
  disciplinaryDateStart: null, // วันที่เริ่มการสอบสวน
  disciplinaryDateEnd: null, // วันที่สิ้นสุดการสอบสวน
  daysExtend: 0,
  disciplinaryDateInvestigation: null, // วันที่มีคำสั่งให้สอบสวน
  disciplinaryDateResult: null, //วันที่รายงานผลการสอบสวน
  disciplinaryStatusResult: "",
  disciplinaryCauseText: "",
  disciplinaryResult: "",
  disciplinaryExtendHistory: [],
  disciplinaryFaultLevelOther: "",
});
const disciplineDisciplinary_DocRelevants = ref<FileLists[]>([]); // ยังไม่มีรอ api
const disciplineDisciplinary_DocSummaryEvidences = ref<FileLists[]>([]);
const disciplineDisciplinary_DocRecordAccusers = ref<FileLists[]>([]);
const disciplineDisciplinary_DocWitnessess = ref<FileLists[]>([]);
const disciplineDisciplinary_DocOthers = ref<FileLists[]>([]);

const initialPagination = ref<any>({
  rowsPerPage: 0,
});

/** รับ props มาจากหน้าหลัก */
const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
  fetchData: {
    type: Function,
    default: () => "",
  },
});
const emit = defineEmits(["submit:disciplinary"]);

const dateEndInputStyle = computed(() => {
  if (formData.disciplinaryDateStart) {
    const currentDate = new Date();
    const investigationDateEnd = new Date(formData.disciplinaryDateEnd as Date);

    const isInNext7Days =
      investigationDateEnd >= currentDate &&
      investigationDateEnd <=
        new Date(currentDate.getTime() + 7 * 24 * 60 * 60 * 1000);

    return isInNext7Days ? "input-alert" : "";
  }
});

const option = ref<any[]>(mainStore.statusResultOptions);
const optionOrganization = ref<any[]>(organizationOption.value);
const optionFaultLevel = ref<any[]>(investigateDis.optionsfaultLevel);
const optionCauseText = ref<any[]>(investigateDis.causeTextOptions);

/** เปิด dialog */
function popup() {
  modal.value = true;
  filterKeyword2.value = "";
}

/** ฟังชั่นปิด dialog */
function clickClose() {
  modal.value = false;
}

function toggleModal() {
  modalPerson.value = !modalPerson.value;
}

/**
 * ฟังชั้นคำนวณเวลาวันที่สิ้นสุดจาก วันที่สิ้นสุดการสอบสวน
 * @param val จำนวนวันที่ต้องการขยาย
 */
async function calEndDate(val: string) {
  changeFormData();
  const date = await new Date(props.data.disciplinaryDateEnd);
  formData.disciplinaryDateEnd = await new Date(
    date.setDate(date.getDate() + Number(val))
  );
}

/**
 * ฟังก์ชั่นสำหรับบันทึกข้อมูล ระบบจะแสดง dialog ให้ยืนยันการบันทึก
 * หากยืนยันจะส่งข้อมูลไปบันทึกที่ api
 * หากยกเลิกจะกลับไปหน้าฟอร์ม
 */
function onSubmit() {
  dialogConfirm($q, async () => {
    if (mainStore.rowsAdd) {
      formData.persons = mainStore.rowsAdd as any;
    }

    emit("submit:disciplinary", {
      ...formData,
      disciplinaryDateStart: convertDateToAPI(
        formData.disciplinaryDateStart as Date
      ),
      disciplinaryDateEnd: convertDateToAPI(
        formData.disciplinaryDateEnd as Date
      ),
      disciplinaryDateAllegation: convertDateToAPI(
        formData.disciplinaryDateAllegation
      ),
      disciplinaryDateEvident: convertDateToAPI(
        formData.disciplinaryDateEvident
      ),
      disciplinaryDateInvestigation: convertDateToAPI(
        formData.disciplinaryDateInvestigation
      ),
      disciplinaryDateResult: convertDateToAPI(formData.disciplinaryDateResult),
    });
    isSave.value = false;
    isSaveInfo.value = false;
    extendStatus.value = false;
  });
}

/** ฟังชั่นลบข้อมูลกรรมการ */
async function deleteDirector(id: string) {
  changeFormData();
  const dataRow = rows.value;
  const updatedRows = dataRow.filter((item: any) => item.id !== id);
  rows.value = updatedRows;

  const dataList = updatedRows.map((item: any) => item.id);
  formData.directors = dataList;
}

/** เรียกข้อมูลรายละเอียด*/
async function fetchDatadetail() {
  if (props.data) {
    if (countNum.value === 1) {
      isReadonly.value = props.data.status != "NEW" ? true : false;
      isSave.value = false;
      isSaveInfo.value = false;
      formData.respondentType = props.data.respondentType;
      formData.organizationId = props.data.organizationId;
      formData.organization = props.data.organization;
      organization.value = {
        id: props.data.organizationId,
        name: props.data.organization,
      };
      formData.consideredAgency = props.data.consideredAgency;
      formData.disciplinaryDateAllegation =
        props.data.disciplinaryDateAllegation;
      formData.disciplinaryDateEvident = props.data.disciplinaryDateEvident;
      formData.disciplinaryCaseFault = props.data.disciplinaryCaseFault;
      formData.disciplinaryInvestigateAt = props.data.disciplinaryInvestigateAt;
      formData.disciplinaryFaultLevel = props.data.disciplinaryFaultLevel;
      formData.disciplinaryRefLaw = props.data.disciplinaryRefLaw;
      formData.disciplinarySummaryEvidence =
        props.data.disciplinarySummaryEvidence;
      formData.disciplinaryRecordAccuser = props.data.disciplinaryRecordAccuser;
      formData.disciplinaryWitnesses = props.data.disciplinaryWitnesses;
      formData.result = props.data.result;
      formData.persons = props.data.persons ?? [];
      formData.disciplinaryDateStart = props.data.disciplinaryDateStart ?? null;
      formData.disciplinaryDateEnd = props.data.disciplinaryDateEnd ?? null;
      formData.daysExtend = props.data.daysExtend ?? 0;
      formData.disciplinaryDateInvestigation =
        props.data.disciplinaryDateInvestigation ?? null;
      formData.disciplinaryDateResult =
        props.data.disciplinaryDateResult ?? null;

      disciplineDisciplinary_DocRelevants.value =
        props.data.disciplineDisciplinary_DocRelevants ?? [];
      disciplineDisciplinary_DocSummaryEvidences.value =
        props.data.disciplineDisciplinary_DocSummaryEvidences ?? [];
      disciplineDisciplinary_DocRecordAccusers.value =
        props.data.disciplineDisciplinary_DocRecordAccusers ?? [];
      disciplineDisciplinary_DocRecordAccusers.value =
        props.data.disciplineDisciplinary_DocRecordAccusers ?? [];
      disciplineDisciplinary_DocWitnessess.value =
        props.data.disciplineDisciplinary_DocWitnessess ?? [];
      disciplineDisciplinary_DocOthers.value =
        props.data.disciplineDisciplinary_DocOthers ?? [];

      investigateDis.rowSent = formData.persons.map((person: any) => ({
        id: person.id,
        idcard: person.idcard,
        name: person.name,
        profileType: person.profileType,
        prefix: person.prefix,
        firstName: person.firstName,
        lastName: person.lastName,
        position: person.position === null ? "-" : person.position,
        positionLevel:
          person.positionLevel === null ? "-" : person.positionLevel,
        salary: person.salary === null ? "-" : person.salary,
        personId: person.personId,
        posNo: person.posNo === null ? "-" : person.posNo,
        organization: person.organization,
        isSend: person.isSend,
        isSuspend: person.isSuspend,
        status: person.status,
        statusDiscard: person.statusDiscard,
        root: person.root,
        rootId: person.rootId,
        rootShortName: person.rootShortName,
        child1: person.child1,
        child1Id: person.child1Id,
        child1ShortName: person.child1ShortName,
        child2: person.child2,
        child2Id: person.child2Id,
        child2ShortName: person.child2ShortName,
        child3: person.child3,
        child3Id: person.child3Id,
        child3ShortName: person.child3ShortName,
        child4: person.child4,
        child4Id: person.child4Id,
        child4ShortName: person.child4ShortName,
        posMasterNo: person.posMasterNo,
        posTypeId: person.posTypeId,
        posTypeName: person.posTypeName,
        posLevelId: person.posLevelId,
        posLevelName: person.posLevelName,
      }));

      formData.disciplinaryStatusResult = props.data.disciplinaryStatusResult
        ? props.data.disciplinaryStatusResult
        : "NOT_SPECIFIED";
      formData.disciplinaryCauseText = props.data.disciplinaryCauseText;
      formData.disciplinaryResult = props.data.disciplinaryResult;
      formData.disciplinaryExtendHistory = props.data.disciplinaryExtendHistory;

      const listDataMain = props.data.persons.map((person: any) => ({
        id: person.id,
        idcard: person.idcard,
        name: person.name,
        prefix: person.prefix,
        profileType: person.profileType,
        firstName: person.firstName,
        lastName: person.lastName,
        posLevelName: person.posLevelName,
        position: person.position === null ? "-" : person.position,
        positionLevel:
          person.positionLevel === null ? "-" : person.positionLevel,
        salary: person.salary === null ? "" : person.salary,
        personId: person.personId,
        posNo: person.posNo === null ? "-" : person.posNo,
        organization: person.organization,
        isSend: person.isSend,
        isSuspend: person.isSuspend,
        status: person.status,
        statusDiscard: person.statusDiscard,
        isAncestorDNA: person.isAncestorDNA,

        root: person.root,
        rootId: person.rootId,
        rootShortName: person.rootShortName,
        child1: person.child1,
        child1Id: person.child1Id,
        child1ShortName: person.child1ShortName,
        child2: person.child2,
        child2Id: person.child2Id,
        child2ShortName: person.child2ShortName,
        child3: person.child3,
        child3Id: person.child3Id,
        child3ShortName: person.child3ShortName,
        child4: person.child4,
        child4Id: person.child4Id,
        child4ShortName: person.child4ShortName,
        posMasterNo: person.posMasterNo,
        posTypeId: person.posTypeId,
        posTypeName: person.posTypeName,
        posLevelId: person.posLevelId,
        citizenId: person.idcard,

        rootDnaId: person.rootDnaId,
        child1DnaId: person.child1DnaId,
        child2DnaId: person.child2DnaId,
        child3DnaId: person.child3DnaId,
        child4DnaId: person.child4DnaId,
      }));
      mainStore.rowsAdd = listDataMain;
      mainStore.rowsAddCheck = listDataMain;
      mainStore.rowsCheck = mainStore.rowsAdd.filter(
        (item: any) => item.isSuspend === "NEW" && item.isSend === "NEW"
      );
      /** MAP รายชื่อกรรมการ หน้าหลัก */
      const dataMap = props.data.director.map((item: any) => ({
        idRaw: item.id ? item.id : "-",
        id: item.directorId ? item.directorId : "-",
        name: `${item.prefix}${item.firstName} ${item.lastName}`,
        prefix: item.prefix,
        firstName: item.firstName,
        lastName: item.lastName,
        position: item.position == "" ? "-" : item.position,
        email: item.email == "" ? "-" : item.email,
        phone: item.phone == "" ? "-" : item.phone,
        commandNo: item.commandNo == "" ? "-" : item.commandNo,
        duty: item.duty == "" ? "-" : item.duty,
        check: "props",
      }));

      rows.value = dataMap;
      const dataList = dataMap.map((item: any) => item.id);
      formData.directors = dataList;
    } else if (countNum.value >= 2) {
      disciplineDisciplinary_DocRelevants.value =
        props.data.disciplineDisciplinary_DocRelevants ?? [];
      disciplineDisciplinary_DocSummaryEvidences.value =
        props.data.disciplineDisciplinary_DocSummaryEvidences ?? [];
      disciplineDisciplinary_DocRecordAccusers.value =
        props.data.disciplineDisciplinary_DocRecordAccusers ?? [];
      disciplineDisciplinary_DocRecordAccusers.value =
        props.data.disciplineDisciplinary_DocRecordAccusers ?? [];
      disciplineDisciplinary_DocWitnessess.value =
        props.data.disciplineDisciplinary_DocWitnessess ?? [];
      disciplineDisciplinary_DocOthers.value =
        props.data.disciplineDisciplinary_DocOthers ?? [];
    }
  }
}

function returnCount(num: number) {
  countNum.value = num;
}

async function addPerson(data: any, type?: string) {
  await mainStore.fetchData(data, type);
  changeFormData();
}

/** function เรียกรายชื่อหน่วยงาน*/
/** ดึงข้อมูล active */
async function getActive() {
  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then((res) => {
      getOc(res.data.result.activeId);
    })
    .catch((err) => {
      messageError($q, err);
      hideLoader();
    })
    .finally(() => {});
}

async function getOc(activeId: string) {
  showLoader();
  await http
    .get(config.API.orgByIdSystem(activeId, route.meta.Key as string))
    .then(async (res) => {
      organizationOption.value = await res.data.result.map((item: any) => ({
        id: item.orgTreeId,
        name: item.orgName,
      }));
    })
    .catch((err) => {
      messageError($q, err);
      hideLoader();
    })
    .finally(() => {});
}

/** function เรียกรายชื่อกรรมการ*/
async function fetchDListDirector() {
  showLoader();
  await http
    .get(
      config.API.directorList(
        pagination.value.page,
        pagination.value.rowsPerPage,
        filterKeyword2.value.trim(),
        mainStore.pathDirector(route.name as string)
      )
    )
    .then((res) => {
      total.value = res.data.result.total;

      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      const data = res.data.result.data;
      let datalistDirector: responseType[] = data.map((e: directorType) => ({
        id: e.id,
        directorId: e.directorId,
        name: `${e.prefix}${e.firstName} ${e.lastName}`,
        prefix: e.prefix,
        firstName: e.firstName,
        lastName: e.lastName,
        position: e.position,
        email: e.email == "" ? "-" : e.email,
        phone: e.phone == "" ? "-" : e.phone,
        total: e.total,
        duty: e.duty,
      }));

      /** หารานชื่อกรรมการที่ไม่ซ้ำ*/
      listDirector.value = datalistDirector.filter(
        (i) => !rows.value.some((e) => e.directorId === i.id)
      );
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function return รายชื่อกรรมการที่เลือก
 * @param data รายชื่อกรรมการที่เลือก
 */
function returnDirector(data: any) {
  const dataList = data.map((item: any) => item.id);
  formData.directors = dataList;
  rows.value = data;
  changeFormData();
  clickClose();
}

const organization = ref<OptionData>();

async function selectComplainant(val: string) {
  formData.organizationId = "";
  formData.consideredAgency = "";
}

/** ฟังก์ชั่นเช็คการแก้ไขฟอร์มแล้วไม่ได้กดบันทึก */
function changeFormData() {
  isSave.value = true;
  isSaveInfo.value = true;
  if (formData.disciplinaryFaultLevel !== "อื่นๆ") {
    formData.disciplinaryFaultLevelOther = "";
  }

  if (organization.value) {
    formData.organizationId = organization.value.id as string;
    formData.organization = organization.value.name;
  }
}

/** เช็ควันที่สิ้นสุดต้องมากกว่า หรือเท่ากับวันเริ่ม */
function changeFormDataDate() {
  isSave.value = true;
  isSaveInfo.value = true;
  const startDate = new Date(formData.disciplinaryDateStart as Date);
  const endDate = new Date(formData.disciplinaryDateEnd as Date);

  if (startDate > endDate) {
    formData.disciplinaryDateEnd = null;
  }
}

function calendarOpen() {
  calendarModal.value = true;
}

function resetExtend() {
  formData.disciplinaryDateEnd = props.data.disciplinaryDateEnd;
  formData.daysExtend = 0;
}

/** เปลี่ยนสี เมื่อ readonly
 * @param val true/false
 */
function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

/** เปลี่ยนสี เมื่อ readonly
 * @param val true/false
 */
function inputEditExtend(val: boolean) {
  if (formData.disciplinaryExtendHistory.length > 0) {
    return {
      "full-width cursor-pointer ": val,
    };
  } else {
    return {
      "full-width cursor-pointer ": val,
      "full-width cursor-pointer inputgreen": !val,
    };
  }
}

function openModal() {
  modalPopup.value = true;
}
function closePopup() {
  modalPopup.value = false;
}

function fetchDataList() {
  setTimeout(() => {
    props.fetchData();
  }, 500);
}

function emitPerson(data: PersonsArray[]) {
  const dataMapId = data.map((item: PersonsArray) => item.id);
  showLoader();
  http
    .post(config.API.disciplinaryReport(), {
      Id: dataMapId,
    })
    .then((res) => {
      getActive();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function openEditDirector(data: any) {
  editDirectorId.value = data.idRaw;
  modalEditDirector.value = true;
  dutyVal.value = data.duty;
  commandNoVal.value = data.commandNo;
}

function closeEditDirector() {
  modalEditDirector.value = false;
}

async function saveDuty(id: string, duty: string, resolution: string) {
  showLoader();
  await http
    .put(config.API.disciplinaryEditDuty(props.data.id, id), {
      duty: duty,
      commandNo: resolution,
    })
    .then((res: any) => {
      success($q, "บันทึกสำเร็จ");
      closeEditDirector();
      props.fetchData();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}

function onclickViewinfo(id: string, type: string) {
  modalPersonal.value = true;
  personId.value = id;
  isEmpType.value = type;
}

function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

watch(
  () => formData.disciplinaryStatusResult,
  () => {
    if (formData.disciplinaryStatusResult !== "HAVE_CAUSE") {
      formData.disciplinaryCauseText = "";
    }
  }
);

function deletePerson(id: string) {
  changeFormData();
  const dataRow = mainStore.rowsAdd;
  const updatedRows = dataRow.filter((item: any) => item.personId !== id);
  mainStore.rowsAdd = updatedRows;
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFn(val: string, update: Function) {
  update(() => {
    option.value = mainStore.statusResultOptions.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFnOrganization(val: string, update: Function) {
  update(() => {
    optionOrganization.value = organizationOption.value.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFnFaultLevel(val: string, update: Function) {
  update(() => {
    optionFaultLevel.value = investigateDis.optionsfaultLevel.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFnCauseText(val: string, update: Function) {
  update(() => {
    optionCauseText.value = investigateDis.causeTextOptions.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

function getSearch() {
  pagination.value.page = 1;
  fetchDListDirector();
}

watch(
  () => pagination.value.rowsPerPage,
  async () => {
    getSearch();
  }
);

watch(
  () => formData.disciplinaryFaultLevel,
  () => {
    if (formData.disciplinaryFaultLevel !== "อื่นๆ") {
      formData.disciplinaryFaultLevelOther = "";
    }
  }
);

/**
 * เช็คข้อมูลจาก props
 * เมื่อมีข้อมูล
 * เก็บข้อมูลลง formData
 */
watch(
  () => props.data,
  async () => {
    await fetchDatadetail();
  }
);

/** Hook */
onMounted(async () => {
  mainStore.rowsAdd = [];
  getActive();
});
</script>

<template>
  <div class="row col-12 bg-white">
    <div v-if="isSave" class="col-12 q-pa-sm q-gutter-sm">
      <q-banner inline-actions bordered class="bg-red-1 text-red border-orange">
        <q-icon name="mdi-information-outline" size="20px" /> แจ้งเตือน
        ยังไม่ได้บันทึกข้อมูล
      </q-banner>
    </div>

    <q-form
      greedy
      @submit.prevent
      @validation-success="onSubmit"
      class="col-12 row"
    >
      <div class="row col-12">
        <div class="col-xs-12 col-sm-12 col-md-9 row no-wrap">
          <div class="col-12 row q-pl-md q-py-md">
            <div class="col-12 row q-col-gutter-md">
              <div class="row col-12 q-col-gutter-x-md">
                <div class="col-xs-12 col-sm-3">
                  <q-select
                    :class="inputEdit(isReadonly)"
                    :readonly="isReadonly || checkRoutePermisson"
                    for="SelectrespondentType"
                    v-model="formData.respondentType"
                    ref="respondentTypeRef"
                    dense
                    outlined
                    label="ผู้ถูกร้องเรียน"
                    option-value="id"
                    option-label="name"
                    emit-value
                    use-input
                    hide-selected
                    fill-input
                    map-options
                    hide-bottom-space
                    :options="complainstStore.complainantoptions"
                    @update:model-value="
                      selectComplainant(formData.respondentType);
                      changeFormData();
                    "
                    @filter="(inputValue: any,
                doneFn: Function) => filterSelector(inputValue, doneFn, 'filterrespondentType'
                )"
                  >
                    <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-12 col-sm-3"
                  v-if="formData.respondentType === 'ORGANIZATION'"
                  id="organizationId"
                >
                  <q-select
                    :readonly="isReadonly || checkRoutePermisson"
                    for="inputOffice"
                    name="organizationId"
                    ref="organizationIdRef"
                    dense
                    hide-bottom-space
                    outlined
                    option-label="name"
                    option-value="id"
                    hide-selected
                    fill-input
                    map-options
                    v-model="organization"
                    :options="optionOrganization"
                    label="หน่วยงานที่ถูกร้องเรียน"
                    @update:model-value="changeFormData()"
                    use-input
                    @filter="filterOptionFnOrganization"
                    ><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-12 col-sm-4"
                  v-if="
                    route.name === 'disciplineDisciplinaryEdit' &&
                    props.data &&
                    props.data.status === 'NEW' &&
                    mainStore.rowsCheck.length > 0
                  "
                >
                  <q-btn
                    class="q-pa-sm"
                    color="orange"
                    label="ส่งรายชื่อไปออกคำสั่งยุติเรื่อง"
                    @click="openModal"
                  />
                </div>
              </div>
              <div
                class="row col-12"
                v-if="formData.respondentType === 'PERSON'"
              >
                <q-card
                  bordered
                  class="row col-12"
                  style="border: 1px solid #d6dee1"
                >
                  <div
                    class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
                  >
                    ผู้ถูกร้องเรียน
                    <q-btn
                      v-if="!isReadonly && !checkRoutePermisson"
                      flat
                      round
                      dense
                      color="primary"
                      class="q-ml-sm"
                      icon="mdi-plus"
                      @click="toggleModal"
                    >
                      <q-tooltip>เพิ่มผู้ถูกร้องเรียน</q-tooltip>
                    </q-btn>
                  </div>
                  <div class="col-12"><q-separator /></div>

                  <div class="col-xs-12 q-pa-sm">
                    <d-table
                      ref="table"
                      :columns="mainStore.columnsRespondent"
                      :rows="mainStore.rowsAdd"
                      row-key="personId"
                      flat
                      bordered
                      :paging="true"
                      dense
                      class="custom-header-table"
                    >
                      <template v-slot:header="props">
                        <q-tr :props="props">
                          <q-th auto-width></q-th>
                          <q-th
                            v-for="col in props.cols"
                            :key="col.name"
                            :props="props"
                            style="color: #000000; font-weight: 500"
                          >
                            <span class="text-weight-medium">{{
                              col.label
                            }}</span>
                          </q-th>
                        </q-tr>
                      </template>
                      <template v-slot:body="props">
                        <q-tr :props="props">
                          <td>
                            <q-btn
                              dense
                              flat
                              round
                              color="info"
                              icon="mdi-eye"
                              @click="
                                onclickViewinfo(
                                  props.row.personId,
                                  props.row.profileType
                                )
                              "
                            >
                              <q-tooltip>ดูข้อมูลในทะเบียนประวัติ</q-tooltip>
                            </q-btn>
                            <q-btn
                              v-if="
                                (!checkRoutePermisson &&
                                  !isReadonly &&
                                  props.row.isAncestorDNA === false) ||
                                !mainStore.rowsAddCheck.some(
                                  (row) => row.personId === props.row.personId
                                )
                              "
                              flat
                              round
                              dense
                              color="red"
                              class="q-ml-sm"
                              icon="mdi-delete"
                              @click="deletePerson(props.row.personId)"
                              ><q-tooltip>ลบผู้ถูกร้องเรียน</q-tooltip></q-btn
                            >
                          </td>
                          <q-td
                            v-for="col in props.cols"
                            :key="col.name"
                            :props="props"
                          >
                            <div v-if="col.name == 'no'">
                              {{ props.rowIndex + 1 }}
                            </div>
                            <div
                              v-else-if="col.name === 'organization'"
                              class="table_ellipsis"
                            >
                              {{ props.row.organization }}
                            </div>
                            <div v-else-if="col.name === 'salary'">
                              {{ props.row.salary.toLocaleString() }}
                            </div>
                            <div v-else-if="col.name === 'profileType'">
                              {{
                                props.row.profileType
                                  ? mainStore.convertType(props.row.profileType)
                                  : "-"
                              }}
                            </div>
                            <div v-else>
                              {{ col.value ? col.value : "-" }}
                            </div>
                          </q-td>
                        </q-tr>
                      </template>
                    </d-table>
                  </div>
                </q-card>
              </div>

              <div class="row col-12 q-col-gutter-x-md">
                <datepicker
                  :readonly="isReadonly || checkRoutePermisson"
                  menu-class-name="modalfix"
                  for="#dateAllegation"
                  v-model="formData.disciplinaryDateInvestigation"
                  class="col-xs-12 col-sm-3"
                  :locale="'th'"
                  autoApply
                  borderless
                  :enableTimePicker="false"
                  week-start="0"
                  @update:model-value="changeFormData()"
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      :readonly="isReadonly || checkRoutePermisson"
                      outlined
                      dense
                      :class="inputEdit(isReadonly)"
                      hide-bottom-space
                      :model-value="
                        formData.disciplinaryDateInvestigation != null
                          ? date2Thai(formData.disciplinaryDateInvestigation)
                          : null
                      "
                      :label="`${'วันที่มีคำสั่งให้สอบสวน'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                      <template
                        v-if="
                          formData.disciplinaryDateInvestigation &&
                          isReadonly === false &&
                          !checkRoutePermisson
                        "
                        v-slot:append
                      >
                        <q-icon
                          name="cancel"
                          @click.stop.prevent="
                            formData.disciplinaryDateInvestigation = null
                          "
                          class="cursor-pointer"
                        />
                      </template>
                    </q-input>
                  </template>
                </datepicker>

                <datepicker
                  :readonly="isReadonly || checkRoutePermisson"
                  menu-class-name="modalfix"
                  for="#dateAllegation"
                  v-model="formData.disciplinaryDateAllegation"
                  class="col-xs-12 col-sm-3"
                  :locale="'th'"
                  autoApply
                  borderless
                  :enableTimePicker="false"
                  week-start="0"
                  @update:model-value="changeFormData()"
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      :readonly="isReadonly || checkRoutePermisson"
                      ref="disciplinaryDateAllegationRef"
                      outlined
                      :class="inputEdit(isReadonly)"
                      dense
                      hide-bottom-space
                      :model-value="
                        formData.disciplinaryDateAllegation != null
                          ? date2Thai(formData.disciplinaryDateAllegation)
                          : null
                      "
                      :label="`${'วันที่รับทราบข้อกล่าวหา'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                      <template
                        v-if="
                          formData.disciplinaryDateAllegation &&
                          isReadonly === false &&
                          !checkRoutePermisson
                        "
                        v-slot:append
                      >
                        <q-icon
                          name="cancel"
                          @click.stop.prevent="
                            formData.disciplinaryDateAllegation = null
                          "
                          class="cursor-pointer"
                        />
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="row col-12">
                <q-card
                  bordered
                  class="col-12"
                  style="border: 1px solid #d6dee1"
                >
                  <div
                    class="row col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-sm q-px-md"
                  >
                    <div>
                      วันที่สอบสวน
                      <q-checkbox
                        v-if="
                          formData.disciplinaryExtendHistory.length > 0 &&
                          !isReadonly &&
                          !checkRoutePermisson
                        "
                        :disable="isReadonly"
                        for="#extendStatus"
                        size="md"
                        v-model="extendStatus"
                        label="ขยายเวลา"
                        color="primary"
                        dense
                        class="text-weight-medium q-ml-sm"
                        keep-color
                        @update:model-value="
                          changeFormData();
                          resetExtend();
                        "
                      />
                    </div>
                    <q-space style="height: 1px" />
                    <div>
                      <q-btn
                        name="calendar"
                        round
                        flat
                        dense
                        icon="mdi-calendar-month"
                        class="self-center items-center"
                        color="primary"
                        @click="calendarOpen"
                      >
                        <q-tooltip>ปฏิทิน</q-tooltip>
                      </q-btn>
                    </div>
                  </div>
                  <div class="col-12"><q-separator /></div>
                  <div class="q-pa-sm">
                    <div class="q-col-gutter-sm row col-12">
                      <div class="col-12">
                        <div class="row q-col-gutter-sm">
                          <div v-if="extendStatus" class="col-3">
                            <q-select
                              :class="inputEdit(isReadonly)"
                              :readonly="isReadonly || checkRoutePermisson"
                              for="#daysExtend"
                              outlined
                              dense
                              ref="daysExtendRef"
                              v-model="formData.daysExtend"
                              :options="investigateDis.daysExtendOps"
                              label="จำนวนวันที่ต้องการขยาย"
                              emit-value
                              hide-bottom-space
                              map-options
                              option-label="name"
                              option-value="id"
                              use-input
                              @update:model-value="calEndDate"
                              ><template v-slot:no-option>
                                <q-item>
                                  <q-item-section class="text-grey">
                                    ไม่มีข้อมูล
                                  </q-item-section>
                                </q-item>
                              </template>
                              <template
                                v-if="formData.daysExtend === 0"
                                v-slot:append
                              >
                                <q-icon
                                  name="cancel"
                                  @click.stop.prevent="formData.daysExtend = 0"
                                  class="cursor-pointer"
                                />
                              </template>
                            </q-select>
                          </div>

                          <div v-if="!extendStatus" class="col-3">
                            <datepicker
                              menu-class-name="modalfix"
                              :readonly="
                                checkRoutePermisson ||
                                isReadonly ||
                                formData.disciplinaryExtendHistory.length > 0
                              "
                              v-model="formData.disciplinaryDateStart"
                              :locale="'th'"
                              autoApply
                              :enableTimePicker="false"
                              week-start="0"
                              @update:model-value="changeFormDataDate()"
                            >
                              <template #year="{ year }">{{
                                year + 543
                              }}</template>
                              <template #year-overlay-value="{ value }">{{
                                parseInt(value + 543)
                              }}</template>
                              <template #trigger>
                                <q-input
                                  for="#date"
                                  class="full-width cursor-pointer"
                                  ref="dateRef"
                                  :class="inputEditExtend(isReadonly)"
                                  :readonly="
                                    checkRoutePermisson ||
                                    isReadonly ||
                                    formData.disciplinaryExtendHistory.length >
                                      0
                                  "
                                  outlined
                                  dense
                                  borderless
                                  hide-bottom-space
                                  :model-value="
                                      formData.disciplinaryDateStart
                                        ? date2Thai(
                                            formData.disciplinaryDateStart as Date
                                          )
                                        : null
                                    "
                                  :label="`${'วันที่เริ่มการสอบสวน'}`"
                                >
                                  <template v-slot:prepend>
                                    <q-icon
                                      name="event"
                                      class="cursor-pointer"
                                      color="primary"
                                    >
                                    </q-icon>
                                  </template>
                                  <template
                                    v-if="
                                      !checkRoutePermisson &&
                                      formData.disciplinaryDateStart &&
                                      isReadonly === false &&
                                      formData.disciplinaryExtendHistory
                                        .length === 0
                                    "
                                    v-slot:append
                                  >
                                    <q-icon
                                      name="cancel"
                                      @click.stop.prevent="
                                        (formData.disciplinaryDateStart = null),
                                          (formData.disciplinaryDateEnd = null)
                                      "
                                      class="cursor-pointer"
                                    />
                                  </template>
                                </q-input>
                              </template>
                            </datepicker>
                          </div>

                          <div class="col-3">
                            <datepicker
                              :class="isReadonly ? '' : dateEndInputStyle"
                              menu-class-name="modalfix"
                              v-model="formData.disciplinaryDateEnd"
                              :readonly="
                                checkRoutePermisson ||
                                formData.disciplinaryDateStart === null ||
                                isReadonly ||
                                formData.disciplinaryExtendHistory.length > 0
                              "
                              :locale="'th'"
                              autoApply
                              :enableTimePicker="false"
                              week-start="0"
                              @update:model-value="changeFormData()"
                              :min-date="formData.disciplinaryDateStart"
                            >
                              <template #year="{ year }">{{
                                year + 543
                              }}</template>
                              <template #year-overlay-value="{ value }">{{
                                parseInt(value + 543)
                              }}</template>
                              <template #trigger>
                                <q-input
                                  for="#dateEnd"
                                  :class="inputEditExtend(isReadonly)"
                                  ref="dateEndRef"
                                  :readonly="
                                    checkRoutePermisson ||
                                    formData.disciplinaryDateStart === null ||
                                    isReadonly ||
                                    formData.disciplinaryExtendHistory.length >
                                      0
                                  "
                                  outlined
                                  dense
                                  hide-bottom-space
                                  borderless
                                  :model-value="
                                      formData.disciplinaryDateEnd
                                        ? date2Thai(
                                            formData.disciplinaryDateEnd as Date
                                          )
                                        : null
                                    "
                                  :label="`${'วันที่สิ้นสุดการสอบสวน'}`"
                                >
                                  <template v-slot:prepend>
                                    <q-icon
                                      name="event"
                                      class="cursor-pointer"
                                      color="primary"
                                    >
                                    </q-icon>
                                  </template>
                                  <template
                                    v-if="
                                      !checkRoutePermisson &&
                                      formData.disciplinaryDateEnd &&
                                      isReadonly === false &&
                                      formData.disciplinaryExtendHistory
                                        .length === 0
                                    "
                                    v-slot:append
                                  >
                                    <q-icon
                                      name="cancel"
                                      @click.stop.prevent="
                                        formData.disciplinaryDateEnd = null
                                      "
                                      class="cursor-pointer"
                                    />
                                  </template>
                                </q-input>
                              </template>
                            </datepicker>
                          </div>
                        </div>
                      </div>

                      <!-- วันที่สอบสวน (List Log) -->
                      <div
                        v-if="
                          formData.disciplinaryExtendHistory !== null &&
                          formData.disciplinaryExtendHistory.length > 1
                        "
                        class="col-12 fixed-height-history"
                      >
                        <q-list bordered separator>
                          <q-item
                            v-for="(
                              e, key
                            ) in formData.disciplinaryExtendHistory.slice(1)"
                          >
                            <q-item-section :key="key">
                              {{ e.name }} ({{ e.daysExtend }} วัน)
                              <p class="q-mb-none">
                                {{ date2Thai(e.dateStart) }} -
                                {{ date2Thai(e.dateEnd) }}
                              </p>
                            </q-item-section>
                          </q-item>
                        </q-list>
                      </div>
                    </div>
                  </div>
                </q-card>
              </div>

              <datepicker
                :readonly="isReadonly || checkRoutePermisson"
                menu-class-name="modalfix"
                for="#dateEvident"
                v-model="formData.disciplinaryDateEvident"
                :locale="'th'"
                autoApply
                class="col-xs-12 col-sm-3"
                borderless
                :enableTimePicker="false"
                week-start="0"
                @update:model-value="changeFormData()"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    :readonly="isReadonly || checkRoutePermisson"
                    ref="disciplinaryDateEvidentRef"
                    outlined
                    dense
                    hide-bottom-space
                    :class="inputEdit(isReadonly)"
                    :model-value="
                      formData.disciplinaryDateEvident != null
                        ? date2Thai(formData.disciplinaryDateEvident)
                        : null
                    "
                    :label="`${'วันที่สรุปพยานหลักฐาน'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                    <template
                      v-if="
                        formData.disciplinaryDateEvident &&
                        isReadonly === false &&
                        !checkRoutePermisson
                      "
                      v-slot:append
                    >
                      <q-icon
                        name="cancel"
                        @click.stop.prevent="
                          formData.disciplinaryDateEvident = null
                        "
                        class="cursor-pointer"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>

              <datepicker
                :readonly="isReadonly || checkRoutePermisson"
                menu-class-name="modalfix"
                for="#dateResult"
                v-model="formData.disciplinaryDateResult"
                :locale="'th'"
                autoApply
                class="col-xs-12 col-sm-3"
                borderless
                :enableTimePicker="false"
                week-start="0"
                @update:model-value="changeFormData()"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>

                <template #trigger>
                  <q-input
                    :readonly="isReadonly || checkRoutePermisson"
                    ref="disciplinaryDateResultRef"
                    outlined
                    :class="inputEdit(isReadonly)"
                    dense
                    hide-bottom-space
                    :model-value="
                      formData.disciplinaryDateResult != null
                        ? date2Thai(formData.disciplinaryDateResult)
                        : null
                    "
                    :label="`${'วันที่รายงานผลการสอบสวน'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                    <template
                      v-if="
                        formData.disciplinaryDateResult &&
                        isReadonly === false &&
                        !checkRoutePermisson
                      "
                      v-slot:append
                    >
                      <q-icon
                        name="cancel"
                        @click.stop.prevent="
                          formData.disciplinaryDateResult = null
                        "
                        class="cursor-pointer"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>

              <div class="row col-12">
                <q-card
                  bordered
                  class="row col-12"
                  style="border: 1px solid #d6dee1"
                >
                  <div
                    class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
                  >
                    รายชื่อกรรมการเพื่อพิจารณาความผิดทางวินัย
                    <q-btn
                      v-if="!isReadonly && !checkRoutePermisson"
                      flat
                      round
                      dense
                      color="primary"
                      class="q-ml-sm"
                      @click="popup()"
                      icon="mdi-plus"
                    >
                      <q-tooltip>เพิ่มกรรมการ</q-tooltip>
                    </q-btn>
                  </div>
                  <div class="col-12"><q-separator /></div>
                  <div class="col-xs-12 q-pa-sm row">
                    <Table
                      class="col-12"
                      style="max-height: 80vh"
                      :rows="rows"
                      :columns="investigateDis.columnsDirector"
                      :visible-columns="investigateDis.visibleColumnsDirector"
                      v-model:inputvisible="
                        investigateDis.visibleColumnsDirector
                      "
                      :pagination="initialPagination"
                      :nornmalData="true"
                      :paging="true"
                      :titleText="''"
                    >
                      <template #columns="props">
                        <q-tr :props="props">
                          <q-td class="text-right">
                            <!-- แก้ไขกรรมการ -->
                            <q-btn
                              v-if="
                                !isReadonly &&
                                props.row.check === 'props' &&
                                !checkRoutePermisson
                              "
                              dense
                              flat
                              round
                              color="edit"
                              @click="openEditDirector(props.row)"
                              icon="edit"
                            >
                              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                            </q-btn>

                            <q-btn
                              v-if="!isReadonly && !checkRoutePermisson"
                              dense
                              flat
                              round
                              color="red"
                              @click="deleteDirector(props.row.id)"
                              icon="mdi-delete"
                            >
                              <q-tooltip>ลบข้อมูล</q-tooltip>
                            </q-btn>
                          </q-td>
                          <q-td
                            v-for="col in props.cols"
                            :key="col.name"
                            :props="props"
                          >
                            <div
                              v-if="col.name == 'no'"
                              class="table_ellipsis2"
                            >
                              {{ props.rowIndex + 1 }}
                            </div>
                            <div v-else class="table_ellipsis2">
                              {{ col.value ? col.value : "-" }}
                            </div>
                          </q-td>
                        </q-tr>
                      </template>
                    </Table>
                  </div>
                </q-card>
              </div>
              <div class="row col-12 q-col-gutter-sm">
                <div class="col-xs-12 col-sm-3">
                  <q-input
                    :class="inputEdit(isReadonly)"
                    :readonly="isReadonly || checkRoutePermisson"
                    dense
                    outlined
                    ref="disciplinaryCaseFaultRef"
                    v-model="formData.disciplinaryCaseFault"
                    for="#casefault"
                    label="กรณีมีความผิด"
                    hide-bottom-space
                    @update:model-value="changeFormData()"
                  />
                </div>

                <div class="col-xs-12 col-sm-3">
                  <q-input
                    :class="inputEdit(isReadonly)"
                    :readonly="isReadonly || checkRoutePermisson"
                    dense
                    hide-bottom-space
                    outlined
                    for="#whereInvestigate"
                    ref="disciplinaryInvestigateAtRef"
                    v-model="formData.disciplinaryInvestigateAt"
                    label="สอบสวนที่"
                    @update:model-value="changeFormData()"
                  />
                </div>

                <div class="col-xs-12 col-sm-3">
                  <q-select
                    :class="inputEdit(isReadonly)"
                    :readonly="isReadonly || checkRoutePermisson"
                    dense
                    outlined
                    for="#faultLevel"
                    ref="disciplinaryFaultLevelRef"
                    v-model="formData.disciplinaryFaultLevel"
                    option-label="name"
                    option-value="id"
                    emit-value
                    map-options
                    hide-bottom-space
                    :options="optionFaultLevel"
                    label="ระดับโทษความผิด"
                    group-label="group"
                    group-values="options"
                    clearable
                    @update:model-value="changeFormData()"
                    use-input
                    @filter="filterOptionFnFaultLevel"
                    ><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-3"
                  v-if="formData.disciplinaryFaultLevel === 'อื่นๆ'"
                >
                  <q-input
                    :class="inputEdit(isReadonly)"
                    outlined
                    dense
                    label="ระดับโทษความผิดอื่นๆ"
                    v-model="formData.disciplinaryFaultLevelOther"
                  />
                </div>
                <div class="col-xs-12 col-sm-3">
                  <q-input
                    :class="inputEdit(isReadonly)"
                    :readonly="isReadonly || checkRoutePermisson"
                    dense
                    for="#refLaw"
                    hide-bottom-space
                    outlined
                    ref="disciplinaryRefLawRef"
                    v-model="formData.disciplinaryRefLaw"
                    label="อ้างอิงมาตราตามกฎหมาย"
                    @update:model-value="changeFormData()"
                  />
                </div>
              </div>

              <div class="col-xs-12 col-sm-6">
                <q-input
                  :readonly="isReadonly || checkRoutePermisson"
                  :class="inputEdit(isReadonly)"
                  dense
                  outlined
                  for="#evidence"
                  ref="disciplinarySummaryEvidenceRef"
                  hide-bottom-space
                  v-model="formData.disciplinarySummaryEvidence"
                  label="สรุปพยานหลักฐานสนับสนุนข้อกล่าวหา"
                  type="textarea"
                  @update:model-value="changeFormData()"
                />
              </div>

              <div class="col-xs-12 col-sm-6">
                <q-input
                  :readonly="isReadonly || checkRoutePermisson"
                  :class="inputEdit(isReadonly)"
                  dense
                  outlined
                  ref="disciplinaryRecordAccuserRef"
                  for="#recordAccuser"
                  v-model="formData.disciplinaryRecordAccuser"
                  label="บันทึกถ้อยคำของผู้กล่าวหา"
                  hide-bottom-space
                  type="textarea"
                  @update:model-value="changeFormData()"
                />
              </div>

              <div class="col-xs-12 col-sm-6">
                <q-input
                  :readonly="isReadonly || checkRoutePermisson"
                  :class="inputEdit(isReadonly)"
                  dense
                  outlined
                  for="#witnesses"
                  ref="disciplinaryWitnessesRef"
                  v-model="formData.disciplinaryWitnesses"
                  label="พยานและบันทึกถ้อยคำพยาน"
                  hide-bottom-space
                  type="textarea"
                  @update:model-value="changeFormData()"
                />
              </div>

              <div class="col-xs-12 col-sm-6">
                <q-input
                  :readonly="isReadonly || checkRoutePermisson"
                  :class="inputEdit(isReadonly)"
                  dense
                  outlined
                  for="#InvestResults"
                  ref="resultRef"
                  v-model="formData.result"
                  label="ผลการสอบสวน"
                  hide-bottom-space
                  type="textarea"
                  @update:model-value="changeFormData()"
                />
              </div>

              <div class="row col-12">
                <q-card
                  bordered
                  class="col-12"
                  style="border: 1px solid #d6dee1"
                >
                  <div
                    class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
                  >
                    ผลการพิจารณาความผิดทางวินัย
                  </div>

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

                  <div class="q-pa-sm row q-col-gutter-sm">
                    <div class="col-3">
                      <q-select
                        :class="inputEdit(isReadonly)"
                        for="#fault"
                        outlined
                        dense
                        :readonly="isReadonly || checkRoutePermisson"
                        ref="disciplinaryStatusResultRef"
                        v-model="formData.disciplinaryStatusResult"
                        :options="option"
                        label="ผลการสอบสวน"
                        emit-value
                        hide-selected
                        fill-input
                        hide-bottom-space
                        map-options
                        option-label="name"
                        option-value="id"
                        use-input
                        @filter="filterOptionFn"
                        @update:model-value="changeFormData()"
                        ><template v-slot:no-option>
                          <q-item>
                            <q-item-section class="text-grey">
                              ไม่มีข้อมูล
                            </q-item-section>
                          </q-item>
                        </template>
                      </q-select>
                    </div>
                    <div
                      v-if="formData.disciplinaryStatusResult == 'HAVE_CAUSE'"
                      class="col-3"
                    >
                      <q-select
                        :class="inputEdit(isReadonly)"
                        :readonly="isReadonly || checkRoutePermisson"
                        for="#fault"
                        outlined
                        hide-selected
                        fill-input
                        dense
                        ref="disciplinaryCauseTextRef"
                        v-model="formData.disciplinaryCauseText"
                        :options="optionCauseText"
                        label="ร้ายแรง/ไม่ร้ายแรง"
                        emit-value
                        map-options
                        option-label="name"
                        option-value="id"
                        use-input
                        @filter="filterOptionFnCauseText"
                        clearable
                        @update:model-value="changeFormData()"
                        ><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">
                      <q-input
                        :class="inputEdit(isReadonly)"
                        :readonly="isReadonly || checkRoutePermisson"
                        class="full-width cursor-pointer"
                        outlined
                        ref="disciplinaryResultRef"
                        dense
                        borderless
                        v-model="formData.disciplinaryResult"
                        hide-bottom-space
                        :label="`${'เหตุผล'}`"
                        type="textarea"
                        @update:model-value="changeFormData()"
                      />
                    </div>
                  </div>
                </q-card>
              </div>
            </div>
          </div>
          <div class="row"><q-separator vertical /></div>
        </div>
        <!-- อัพโหลดไฟล์ -->
        <div class="col-xs-12 col-sm-12 col-md-3">
          <div class="q-col-gutter-md row q-pa-md">
            <!-- ยังไม่มี api  -->
            <div class="col-xs-12">
              <UploadFile
                title="อัปโหลดไฟล์เอกสารที่เกี่ยวข้องกับการสอบสวน"
                label="เลือกไฟล์"
                :files="disciplineDisciplinary_DocRelevants"
                :id="id"
                type="relevant"
                :fetchData="props.fetchData"
                :is-readonly="isReadonly || checkRoutePermisson"
                :return-count="returnCount"
              />
            </div>
            <div class="col-xs-12">
              <UploadFile
                title="อัปโหลดหลักฐานสนับสนุนข้อกล่าวหา"
                label="เลือกไฟล์"
                :files="disciplineDisciplinary_DocSummaryEvidences"
                :id="id"
                type="summaryEvidence"
                :fetchData="props.fetchData"
                :is-readonly="isReadonly || checkRoutePermisson"
                :return-count="returnCount"
              />
            </div>
            <div class="col-xs-12">
              <UploadFile
                title="อัปโหลดบันทึกถ้อยคำของผู้กล่าวหา"
                label="เลือกไฟล์"
                :files="disciplineDisciplinary_DocRecordAccusers"
                :id="id"
                type="recordAccuser"
                :fetchData="props.fetchData"
                :is-readonly="isReadonly || checkRoutePermisson"
                :return-count="returnCount"
              />
            </div>
            <div class="col-xs-12">
              <UploadFile
                title="อัปโหลดพยานและการบันทึกถ้อยคำ"
                label="เลือกไฟล์"
                :files="disciplineDisciplinary_DocWitnessess"
                :id="id"
                type="witnesses"
                :fetchData="props.fetchData"
                :is-readonly="isReadonly || checkRoutePermisson"
                :return-count="returnCount"
              />
            </div>
            <div class="col-xs-12">
              <UploadFile
                title="อัปโหลดไฟล์เอกสารหลักฐานอื่นๆ"
                label="เลือกไฟล์"
                :files="disciplineDisciplinary_DocOthers"
                :id="id"
                type="other"
                :fetchData="props.fetchData"
                :is-readonly="isReadonly || checkRoutePermisson"
                :return-count="returnCount"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="col-12"><q-separator /></div>
      <div
        v-if="!isReadonly && !checkRoutePermisson"
        class="row col-12 q-pa-sm"
      >
        <q-space />
        <q-btn
          for="ButtonOnSubmit"
          id="formSubmit"
          color="secondary"
          label="บันทึก"
          type="submit"
          ><q-tooltip>บับทึกข้อมูล</q-tooltip></q-btn
        >
      </div>
    </q-form>
  </div>

  <DialogDuty
    :modal="modalEditDirector"
    :close-popup="closeEditDirector"
    :id="editDirectorId"
    :duty="dutyVal"
    :command="commandNoVal"
    :save="saveDuty"
  />

  <!-- Popup ผู้ถูกร้องเรียน -->
  <DialogAddPersonal
    title="ผู้ถูกร้องเรียน"
    v-model:modal="modalPerson"
    btn-title="เพิ่มรายชื่อผู้ถูกสอบสวน"
    :save="addPerson"
    :selected-data="mainStore.rowsAdd"
  />

  <DialogDirector
    v-model:Modal="modal"
    :get-search="getSearch"
    :clickClose="clickClose"
    :rows2="listDirector"
    v-model:filterKeyword2="filterKeyword2"
    v-model:type="type"
    :get-list="fetchDListDirector"
    v-model:pagination="pagination"
    v-model:total="total"
    v-model:total-list="totalList"
    :selected-row="rows"
    @returnDirector="returnDirector"
  />

  <CalandarDialog
    :modal="calendarModal"
    :close="calendarModalclose"
    :lists="formData.disciplinaryExtendHistory"
  />

  <PopupSendToNext
    v-model:modal="modalPopup"
    :close="closePopup"
    title="ส่งรายชื่อไปออกคำสั่งยุติเรื่อง"
    :rows="mainStore.rowsCheck"
    :columns="mainStore.columnsDirector"
    :visibleColumns="mainStore.visibleColumnsDirector"
    @return-person="emitPerson"
    :checked-val="false"
    :fetch-data="fetchDataList"
  />

  <PopupPersonal
    :modal="modalPersonal"
    :id="personId"
    @update:modal="updatemodalPersonal"
    :type="isEmpType"
  />
</template>

<style scoped>
.fixed-height-history {
  overflow-y: auto;
  max-height: 150px;
}
</style>
