<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
import { onMounted, ref, watch, reactive, computed } from "vue";
import { useQuasar } from "quasar";
import moment from "moment";
import PopupSendToNext from "@/modules/11_discipline/components/PopupSendToNext.vue";
import DialogDirector from "@/modules/11_discipline/components/DialogDirector.vue";
import DialogAddPersonal from "@/components/Dialogs/AddPersonal.vue";
import Table from "@/modules/11_discipline/components/DirectorTable.vue";
import { useCounterMixin } from "@/stores/mixin";
import { useInvestigateDisStore } from "@/modules/11_discipline/store/InvestigateDisStore";
import { useInvestigateFactStore } from "@/modules/11_discipline/store/InvestigateFactStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/main";

import CalandarDialog from "@/modules/11_discipline/components/2_InvestigateFacts/CalandarDialog.vue";
import DialogDuty from "@/modules/11_discipline/components/DialogDuty.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";

import type { FormData } from "@/modules/11_discipline/interface/request/investigateFact";

import config from "@/app.config";
import http from "@/plugins/http";
import type { OptionData } from "@/modules/07_insignia/interface/index/Main";

const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");

const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const checkRoutePermisson = ref<boolean>(
  route.name == "disciplineInvestigatefactsDetail"
);
const id = ref<string>(route.params.id as string);
const modalPerson = ref<boolean>(false);
const toggleModal = () => (modalPerson.value = !modalPerson.value);

/**เรียกใช้ store */
const investigateFactStore = useInvestigateFactStore();
const mainStore = useDisciplineMainStore();
const modalPopup = ref<boolean>(false);
const mixin = useCounterMixin();
const { filterFnOptionsType } = investigateFactStore;
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  success,
  messageError,
  dialogRemove,
  downloadRenameFileByLink
} = mixin;
const investigateDis = useInvestigateDisStore();
const countNum = ref<number>(1);

const modal = ref<boolean>(false);
const filterKeyword2 = ref<string>("");
const type = ref<string>("");
const modalEditDirector = ref<boolean>(false);
const editDirectorId = ref<string>();
const dutyVal = ref<string>();
const commandNoVal = ref<string>();

const filter = ref<string>("");
const isUpdate = ref<boolean>(false);
const filterTable = ref<string>("");
const filterKeyword = ref<string>("");
const maxPage = ref<number>(1);
const page = ref<number>(1);
const rowsPerPage = ref<number>(10);

const investigationExtendStatus = ref<boolean>(false);

const isSave = ref<boolean>(false); // มีการแก้ไขรอบันทึก
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว

const option = ref<any[]>(investigateFactStore.organizationIdOp);
const optionStatusResult = ref<any[]>(mainStore.statusResultOptions);
const optionCauseText = ref<any[]>(mainStore.statusResultOptions);

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

/** ข้อมูล v-model ของฟอร์ม */
const formData = reactive<FormData>({
  id: "",
  idComplaint: "",
  complaint: "",
  complaintdetail: "",
  investigationDescription: "",
  fault: "",
  investigationDetailOther: "",
  evidenceFiles: null,
  fileComplaint: null,
  investigationExtendStatus: false,
  investigationDateStart: null,
  investigationDateEnd: null,
  investigationDetail: "",
  investigationDaysExtend: null,
  investigationStatusResult: "",
  investigationCauseText: "",
  complaintStatus: "",
  result: "",
  directors: [],
  disciplineInvestigateDocs: [],
  disciplineInvestigateRelevantDocs: [],
  status: "",
  documentFile: null,
  respondentType: "",
  organizationId: "",
  organization: "",
  persons: [],
  investigationExtendHistory: [],
  isDisciplinary: false,
  isAncestorDNA: false,
});

const rows = ref([]);
const dateEndInputStyle = computed(() => {
  if (formData.investigationDateStart) {
    const currentDate = new Date();
    const investigationDateEnd = new Date(
      formData.investigationDateEnd as Date
    );

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

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

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

const calendarModal = ref<boolean>(false);
const calendarModalclose = () => (calendarModal.value = !calendarModal.value);

/**
 * ฟังก์ชั่นสำหรับบันทึกข้อมูล ระบบจะแสดง dialog ให้ยืนยันการบันทึก
 * หากยืนยันจะส่งข้อมูลไปบันทึกที่ api
 * หากยกเลิกจะกลับไปหน้าฟอร์ม
 */
function onSubmit() {
  countNum.value = 1;
  dialogConfirm($q, async () => {
    if (
      formData.investigationDateStart !== null &&
      formData.investigationDateEnd !== null
    ) {
      const investigationDateStart = new Date(formData.investigationDateStart);
      const investigationDateEnd = new Date(formData.investigationDateEnd);

      formData.investigationDateStart = moment(investigationDateStart).format(
        "YYYY-MM-DD"
      );
      formData.investigationDateEnd =
        moment(investigationDateEnd).format("YYYY-MM-DD");
    }

    if (mainStore.rowsAdd) {
      formData.persons = mainStore.rowsAdd;
    }

    props.onSubmit(formData);
    isSave.value = false;
    investigationExtendStatus.value = false;
  });
}

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

function resetExtend() {
  formData.investigationDateEnd = props.data.investigationDateEnd;
  formData.investigationDaysExtend = 0;
}

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

/**
 * เช็คข้อมูลจาก props
 * เมื่อมีข้อมูล
 * เก็บข้อมูลลง formData
 */
watch(props.data, async () => {
  if (props.data !== null) {
    if (countNum.value === 1) {
      isReadonly.value = props.data.status != "NEW" ?? true;
      isSave.value = false;

      isUpdate.value = true;
      formData.id = props.data.id;
      formData.complaint = props.data.complaint;
      formData.organizationId = props.data.organizationId;
      formData.organization = props.data.organization;
      organization.value = {
        id: props.data.organizationId,
        name: props.data.organization,
      };
      formData.respondentType = props.data.respondentType;
      formData.complaintdetail = props.data.complaintdetail;
      formData.investigationDescription = props.data.investigationDescription;
      formData.fault = props.data.fault;
      formData.investigationDetailOther = props.data.investigationDetailOther;
      formData.fileComplaint = props.data.fileComplaint;
      formData.investigationDateStart = props.data.investigationDateStart;
      formData.investigationDateEnd = props.data.investigationDateEnd;
      formData.investigationDetail = props.data.investigationDetail;
      formData.investigationDaysExtend = props.data.investigationDaysExtend;
      formData.investigationExtendStatus = props.data.investigationExtendStatus;
      formData.investigationStatusResult = props.data.investigationStatusResult;
      formData.investigationCauseText = props.data.investigationCauseText;
      formData.result = props.data.result;
      formData.disciplineInvestigateDocs = props.data.disciplineInvestigateDocs;
      formData.disciplineInvestigateRelevantDocs =
        props.data.disciplineInvestigateRelevantDocs;
      formData.status = props.data.status;
      formData.investigationExtendHistory =
        props.data.investigationExtendHistory;

      mainStore.rowsAdd = props.data.persons.map((person: any) => ({
        id: person.id,
        idcard: person.idcard,
        name: person.name,
        prefix: person.prefix,
        firstName: person.firstName,
        lastName: person.lastName,
        position: person.position,
        positionLevel: person.positionLevel,
        salary: person.salary === null ? "" : person.salary,
        personId: person.personId,
        posNo: person.posNo === null ? "-" : person.posNo,
        organization: person.organization,
        isSend: person.isSend,
        isDisciplinary: person.isDisciplinary,
        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,
        posLevelName: person.posLevelName,
      }));
      mainStore.rowsCheck = mainStore.rowsAdd.filter(
        (item: any) => item.isDisciplinary === false && item.isSend === "NEW"
      );

      const dataMap = props.data.directors.map((item: any) => ({
        id: item.id ? item.id : "-",
        directorId: 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) {
      formData.disciplineInvestigateRelevantDocs =
        props.data.disciplineInvestigateRelevantDocs;
    } else if (countNum.value === 3) {
      formData.disciplineInvestigateDocs = props.data.disciplineInvestigateDocs;
    }
  }
});

function uploadFileRelevant() {
  const Data = new FormData();
  Data.append("file", formData.evidenceFiles);
  showLoader();
  http
    .put(config.API.investigateRelevantUploadFile(formData.id), Data)
    .then((res) => {
      success($q, "อัปโหลดไฟล์สำเร็จ");
      countNum.value = 2;
      props.getData();
      // router.push(`/discipline/complaints`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      formData.evidenceFiles = null;
    });
}

/** อัปโหลดไฟล์ */
function uploadFile() {
  const Data = new FormData();
  Data.append("file", formData.documentFile);
  showLoader();
  http
    .put(config.API.investigateUploadFile(formData.id), Data)
    .then((res) => {
      success($q, "อัปโหลดไฟล์สำเร็จ");
      countNum.value = 3;
      props.getData();
      // router.push(`/discipline/complaints`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      formData.documentFile = null;
    });
}

/**
 * เปิดลิงค์ไฟล์
 * @param link รับมาเป็น https ลิงค์
 */
function downloadFile(link: string) {
  window.open(link, "_blank");
}

/**
 * เปิดลิงค์ไฟล์
 * @param link รับมาเป็น https ลิงค์
 */
function downloadFileRelevant(link: string) {
  window.open(link, "_blank");
}

/**
 * ลบไฟล์
 * @param id id file
 */
function deleteFileRelevant(id: string) {
  dialogRemove($q, () => confirmDeleteRelevant(id));
}

/**
 * ยืนยัน ลบ ไฟล์
 * @param id id file
 */
function confirmDeleteRelevant(id: string) {
  showLoader();
  http
    .delete(config.API.investigateRelevantFileDelete(formData.id, id))
    .then((res) => {
      success($q, `ลบไฟล์สำเร็จ`);
      props.getData();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {});
}

/**
 * ลบไฟล์
 * @param id id file
 */
function deleteFile(id: string) {
  dialogRemove($q, () => confirmDelete(id));
}

/**
 * ยืนยัน ลบ ไฟล์
 * @param id id file
 */
function confirmDelete(id: string) {
  showLoader();
  http
    .delete(config.API.investigateFileDelete(formData.id, id))
    .then((res) => {
      success($q, `ลบไฟล์สำเร็จ`);
      props.getData();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {});
}
async function addPerson(data: any) {
  await mainStore.fetchData(data);
}

/**
 * ฟังชั่น รับค่าจาก คอมโพเเนน
 * @param returnData ค่าที่ได้คืนมา
 */
function handleSave(returnData: any) {
  addPerson(returnData);
  changeFormData();
  toggleModal();
}

/** ดึงข้อมูล active */
async function getActive() {
  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then((res) => {
      getOc(res.data.result.activeId);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function getOc(activeId: string) {
  showLoader();
  await http
    .get(config.API.orgByid(activeId))
    .then(async (res) => {
      const data = await res.data.result.map((item: any) => ({
        organizationId: item.orgTreeId,
        organizationName: item.orgName,
      }));

      investigateFactStore.ocListFn(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });

  // http.get(config.API.typeOc()).then((res) => {
  //   const data = res.data.result;
  //   investigateFactStore.ocListFn(data);
  // });
}

async function updatePagingProp(rowPerpage: number, pageCurrent: number) {
  rowsPerPage.value = rowPerpage;
  page.value = pageCurrent;
  await getList();
}

async function getList() {
  showLoader();
  await http
    .get(
      config.API.directorList(
        page.value,
        rowsPerPage.value,
        filterKeyword.value
      )
    )
    //
    .then((res) => {
      maxPage.value = Math.ceil(res.data.result.total / rowsPerPage.value);
      const data = res.data.result.data;
      investigateDis.fecthDirector(data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function returnDirector(data: any) {
  const dataList = data.map((item: any) => item.id);
  formData.directors = dataList;

  rows.value = data;
  changeFormData();
  clickClose();
}

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

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;
}

/** ฟังก์ชั่นเช็คการแก้ไขฟอร์มแล้วไม่ได้กดบันทึก */
function changeFormData() {
  isSave.value = true;

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

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

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

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

/** เปลี่ยนสี เมื่อ 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.investigationExtendHistory.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 fetchData() {
  setTimeout(() => {
    props.getData();
  }, 500);
}

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

function openEditDirector(data: any) {
  editDirectorId.value = data.directorId;
  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.investigateEditDuty(formData.id, id), {
      duty: duty,
      commandNo: resolution,
    })
    .then((res: any) => {
      success($q, "บันทึกสำเร็จ");
      closeEditDirector();
      props.getData?.();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}

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

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

watch(
  () => formData.investigationDetail,
  (newValue, oldValue) => {
    if (newValue !== "OTHER") {
      formData.investigationDetailOther = "";
    }
  }
);

watch(
  () => formData.respondentType,
  () => {
    if (formData.respondentType !== "ORGANIZATION") {
      formData.organizationId = "";
    }
  }
);
watch(
  () => formData.investigationStatusResult,
  () => {
    if (formData.investigationStatusResult !== "HAVE_CAUSE") {
      formData.investigationCauseText = "";
    }
  }
);

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

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

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

<template>
  <div class="row col-12 bg-white">
    <div v-if="isSave" class="col-12">
      <q-banner
        inline-actions
        bordered
        rounded
        class="bg-red-1 text-red border-orange q-ma-md"
      >
        <q-icon name="mdi-information-outline" size="20px" /> แจ้งเตือน
        ยังไม่ได้บันทึกข้อมูล
      </q-banner>
      <q-separator />
    </div>
    <q-form
      greedy
      @submit.prevent
      @validation-success="onSubmit"
      class="col-12 row"
    >
      <div class="col-12 row">
        <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="row col-12 q-col-gutter-md">
              <div class="col-xs-12 col-sm-5" id="respondentType">
                <q-select
                  :class="inputEdit(isReadonly)"
                  for="SelectrespondentType"
                  v-model="formData.respondentType"
                  ref="respondentTypeRef"
                  dense
                  outlined
                  :readonly="isReadonly || checkRoutePermisson"
                  label="ผู้ถูกร้องเรียน"
                  option-value="id"
                  option-label="name"
                  emit-value
                  use-input
                  map-options
                  hide-bottom-space
                  :options="investigateFactStore.respondentTypeOps"
                  @filter="(inputValue: any,
              doneFn: Function) => investigateFactStore.filterSelector(inputValue, doneFn, 'filterrespondentType'
              )"
                  @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-xs-12 col-sm-7"
                v-if="formData.respondentType === 'ORGANIZATION'"
                id="organizationId"
              >
                <q-select
                  :class="inputEdit(isReadonly)"
                  for="inputOffice"
                  name="organizationId"
                  ref="organizationIdRef"
                  dense
                  hide-bottom-space
                  :readonly="isReadonly || checkRoutePermisson"
                  outlined
                  option-label="name"
                  option-value="id"
                  v-model="organization"
                  :options="option"
                  label="หน่วยงานที่ถูกร้องเรียน"
                  clearable
                  @update:model-value="changeFormData()"
                  use-input
                  @filter="filterOptionFn"
                  ><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 === 'disciplineInvestigatefactsEdit' &&
                  mainStore.rowsCheck.length > 0
                "
              >
                <q-btn
                  class="q-pa-sm"
                  color="orange"
                  label="ส่งรายชื่อไปออกคำสั่งยุติเรื่อง"
                  @click="openModal"
                />
              </div>
              <div class="col-xs-12 col-sm-5">
                <q-select
                  :class="inputEdit(isReadonly)"
                  :readonly="isReadonly || checkRoutePermisson"
                  for="#investigationDetail"
                  outlined
                  hide-bottom-space
                  dense
                  ref="investigationDetailRef"
                  v-model="formData.investigationDetail"
                  :options="investigateFactStore.investigationDetailOp"
                  label="ลักษณะการสืบสวน"
                  emit-value
                  map-options
                  clearable
                  option-label="name"
                  option-value="id"
                  use-input
                  @filter="(inputValue: any,
      doneFn: Function) => filterFnOptionsType(inputValue, doneFn, 'investigationOp'
      )"
                  @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="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"
                      size="12px"
                      flat
                      round
                      dense
                      color="add"
                      class="q-ml-sm"
                      @click="toggleModal"
                      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">
                    <d-table
                      ref="table"
                      :columns="mainStore.columnsRespondent"
                      :rows="mainStore.rowsAdd"
                      row-key="idcard"
                      flat
                      bordered
                      :paging="true"
                      dense
                      class="custom-header-table"
                      :visible-columns="mainStore.visibleColumnsRespondent"
                    >
                      <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" class="cursor-pointer">
                          <td>
                            <q-btn
                              dense
                              flat
                              round
                              color="info"
                              icon="mdi-eye"
                              @click="onclickViewinfo(props.row.personId)"
                            >
                              <q-tooltip>ดูข้อมูลในทะเบียนประวัติ</q-tooltip>
                            </q-btn>
                            <q-btn
                              v-if="
                                !isReadonly &&
                                !checkRoutePermisson &&
                                props.row.isAncestorDNA === false
                              "
                              flat
                              round
                              dense
                              color="red"
                              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>
                              {{ col.value ?? "-" }}
                            </div>
                          </q-td>
                        </q-tr>
                      </template>
                    </d-table>
                  </div>
                </q-card>
              </div>
              <div
                v-if="formData.investigationDetail === 'OTHER'"
                class="col-12"
              >
                <q-input
                  :class="inputEdit(isReadonly)"
                  :readonly="isReadonly || checkRoutePermisson"
                  for="#investigationDetailOther"
                  outlined
                  ref="investigationDetailOtherRef"
                  dense
                  borderless
                  v-model="formData.investigationDetailOther"
                  hide-bottom-space
                  :label="`${'รายการอื่นๆ(โปรดระบุ)'}`"
                  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="row col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-sm q-px-md"
                  >
                    <div>
                      วันที่สืบสวน
                      <q-checkbox
                        v-if="
                          props.data.investigationExtendHistory.length > 0 &&
                          !isReadonly &&
                          !checkRoutePermisson
                        "
                        :disable="isReadonly"
                        for="#extendStatus"
                        size="md"
                        v-model="investigationExtendStatus"
                        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
                        size="12px"
                        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="investigationExtendStatus" class="col-3">
                            <q-select
                              :class="inputEdit(isReadonly)"
                              :readonly="isReadonly || checkRoutePermisson"
                              for="#daysExtend"
                              outlined
                              dense
                              ref="daysExtendRef"
                              v-model="formData.investigationDaysExtend"
                              :options="investigateFactStore.daysExtendOp"
                              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>
                            </q-select>
                          </div>

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

                      <!-- วันที่สืบสวน (List Log) -->
                      <div
                        v-if="
                          formData.investigationExtendHistory !== null &&
                          formData.investigationExtendHistory.length > 1
                        "
                        class="col-12 fixed-height-history"
                      >
                        <q-list bordered separator>
                          <q-item
                            v-for="(
                              e, key
                            ) in formData.investigationExtendHistory.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>

              <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"
                      size="12px"
                      flat
                      round
                      dense
                      color="add"
                      class="q-ml-sm"
                      icon="mdi-plus"
                      @click="onClickOpenPopup"
                    >
                      <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"
                      :filter="filter"
                      :visible-columns="investigateDis.visibleColumnsDirector"
                      v-model:inputfilter="filter"
                      v-model:inputvisible="
                        investigateDis.visibleColumnsDirector
                      "
                      :pagination="initialPagination"
                      :nornmalData="true"
                      :paging="true"
                      :titleText="''"
                    >
                      <template #columns="props">
                        <q-tr :props="props" class="cursor-pointer">
                          <q-td class="text-right">
                            <!-- แก้ไขกรรมการ -->
                            <q-btn
                              v-if="
                                !checkRoutePermisson &&
                                !isReadonly &&
                                props.row.check === 'props'
                              "
                              dense
                              flat
                              round
                              color="edit"
                              @click="openEditDirector(props.row)"
                              icon="edit"
                            >
                              <q-tooltip>แก้ไข</q-tooltip>
                            </q-btn>
                            <q-btn
                              v-if="!checkRoutePermisson && !isReadonly"
                              dense
                              flat
                              round
                              color="red"
                              icon="mdi-delete"
                              @click="deleteDirector(props.row.id)"
                            >
                              <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 ?? "-" }}
                            </div>
                          </q-td>
                        </q-tr>
                      </template>
                    </Table>
                  </div>
                </q-card>
              </div>

              <div class="col-12">
                <q-input
                  :class="inputEdit(isReadonly)"
                  :readonly="isReadonly || checkRoutePermisson"
                  for="#investigationDescription"
                  outlined
                  ref="investigationDescriptionRef"
                  dense
                  borderless
                  v-model="formData.investigationDescription"
                  hide-bottom-space
                  :label="`${'รายละเอียด'}`"
                  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="row col-12 q-col-gutter-sm q-pa-sm">
                    <div class="col-3">
                      <q-select
                        :class="inputEdit(isReadonly)"
                        for="#fault"
                        outlined
                        dense
                        :readonly="isReadonly || checkRoutePermisson"
                        ref="investigationStatusResultRef"
                        v-model="formData.investigationStatusResult"
                        :options="optionStatusResult"
                        label="ผลการสืบสวน"
                        emit-value
                        map-options
                        option-label="name"
                        option-value="id"
                        use-input
                        @filter="filterOptionFnStatusResult"
                        @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.investigationStatusResult == 'HAVE_CAUSE'"
                      class="col-3"
                    >
                      <q-select
                        :class="inputEdit(isReadonly)"
                        :readonly="isReadonly || checkRoutePermisson"
                        for="#fault"
                        outlined
                        clearable
                        dense
                        ref="investigationCauseTextRef"
                        v-model="formData.investigationCauseText"
                        :options="optionCauseText"
                        label="ร้ายแรง/ไม่ร้ายแรง"
                        emit-value
                        map-options
                        option-label="name"
                        option-value="id"
                        use-input
                        @update:model-value="changeFormData()"
                        @filter="filterOptionFnCauseText"
                        ><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)"
                        outlined
                        ref="resultRef"
                        :readonly="isReadonly || checkRoutePermisson"
                        dense
                        borderless
                        v-model="formData.result"
                        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">
            <div class="col-xs-12">
              <q-card
                bordered
                class="row col-12"
                style="border: 1px solid #d6dee1"
              >
                <div
                  class="col-12 text-weight-medium bg-grey-1 q-py-sm q-px-md"
                >
                  อัปโหลดไฟล์เอกสารที่เกี่ยวข้องกับการสืบสวน
                </div>
                <div class="col-12"><q-separator /></div>
                <div class="row col-12 q-col-gutter-y-sm q-pa-sm">
                  <div
                    v-if="
                      !checkRoutePermisson && !isReadonly && formData.id !== ''
                    "
                    class="col-12 row"
                  >
                    <q-file
                      class="col-12"
                      for="#evidenceFiles"
                      outlined
                      dense
                      v-model="formData.evidenceFiles"
                      label="เอกสารที่เกี่ยวข้องกับการสืบสวน"
                      hide-bottom-space
                    >
                      <template v-slot:prepend>
                        <q-icon name="attach_file" color="primary" />
                      </template>
                      <template v-slot:after>
                        <q-btn
                          v-if="formData.evidenceFiles"
                          flat
                          round
                          dense
                          color="add"
                          icon="mdi-upload"
                          @click="uploadFileRelevant"
                          ><q-tooltip>อัปโหลดเอกสาร</q-tooltip></q-btn
                        >
                      </template>
                    </q-file>
                  </div>

                  <div
                    v-if="
                      props.data.disciplineInvestigateRelevantDocs.length > 0
                    "
                    class="col-xs-12 row"
                  >
                    <q-list
                      class="full-width rounded-borders"
                      bordered
                      separator
                    >
                      <q-item
                        v-for="file in props.data
                          .disciplineInvestigateRelevantDocs"
                        :key="file.id"
                        clickable
                        v-ripple
                      >
                        <q-item-section>{{ file.fileName }}</q-item-section>
                        <q-item-section avatar>
                          <div class="row">
                            <div>
                              <q-btn
                                dense
                                flat
                                round
                                color="blue"
                                icon="mdi-download-outline"
                                @click="downloadRenameFileByLink(file.pathName, file.fileName)"
                              >
                                <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
                              </q-btn>
                            </div>
                            <div>
                              <q-btn
                                v-if="!isReadonly && !checkRoutePermisson"
                                dense
                                flat
                                round
                                color="red"
                                icon="mdi-delete"
                                @click="deleteFileRelevant(file.id)"
                                ><q-tooltip>ลบไฟล์</q-tooltip></q-btn
                              >
                            </div>
                          </div>
                        </q-item-section>
                      </q-item>
                    </q-list>
                  </div>

                  <div class="col-12" v-else>
                    <q-card class="q-pa-md" bordered>
                      ไม่มีรายการเอกสาร
                    </q-card>
                  </div>
                </div>
              </q-card>
            </div>
            <div class="col-xs-12">
              <q-card
                bordered
                class="row col-12"
                style="border: 1px solid #d6dee1"
              >
                <div
                  class="col-12 text-weight-medium bg-grey-1 q-py-sm q-px-md"
                >
                  อัปโหลดไฟล์เอกสารหลักฐาน
                </div>
                <div class="col-12"><q-separator /></div>
                <div class="row col-12 q-col-gutter-y-sm q-pa-sm">
                  <div
                    v-if="
                      !checkRoutePermisson && !isReadonly && formData.id !== ''
                    "
                    class="col-12 row"
                  >
                    <!-- accept=".pdf,.xlsx,.docx" -->
                    <q-file
                      for="inputFiles"
                      class="col-12"
                      outlined
                      dense
                      v-model="formData.documentFile"
                      @added="uploadFile"
                      label="ไฟล์เอกสารหลักฐาน"
                      clearable
                    >
                      <template v-slot:prepend>
                        <q-icon name="attach_file" color="primary" />
                      </template>
                      <template v-slot:after>
                        <q-btn
                          v-if="formData.documentFile"
                          flat
                          round
                          dense
                          color="add"
                          icon="mdi-upload"
                          @click="uploadFile"
                          ><q-tooltip>อัปโหลดไฟล์</q-tooltip></q-btn
                        >
                      </template>
                    </q-file>
                  </div>

                  <div
                    v-if="props.data.disciplineInvestigateDocs.length > 0"
                    class="col-xs-12 row"
                  >
                    <q-list
                      class="full-width rounded-borders"
                      bordered
                      separator
                    >
                      <q-item
                        v-for="file in props.data.disciplineInvestigateDocs"
                        :key="file.id"
                        clickable
                        v-ripple
                      >
                        <q-item-section>{{ file.fileName }}</q-item-section>
                        <q-item-section avatar>
                          <div class="row">
                            <div>
                              <q-btn
                                dense
                                flat
                                round
                                color="blue"
                                icon="mdi-download-outline"
                                @click="downloadRenameFileByLink(file.pathName, file.fileName)"
                              >
                                <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
                              </q-btn>
                            </div>
                            <div>
                              <q-btn
                                v-if="!isReadonly && !checkRoutePermisson"
                                dense
                                flat
                                round
                                color="red"
                                icon="mdi-delete"
                                @click="deleteFile(file.id)"
                                ><q-tooltip>ลบไฟล์</q-tooltip></q-btn
                              >
                            </div>
                          </div>
                        </q-item-section>
                      </q-item>
                    </q-list>
                  </div>

                  <div class="col-12" v-else>
                    <q-card class="q-pa-md" bordered>
                      ไม่มีรายการเอกสาร
                    </q-card>
                  </div>
                </div>
              </q-card>
            </div>
          </div>
        </div>

        <div class="col-12"><q-separator v-if="!checkRoutePermisson" /></div>
        <div
          class="row col-12 q-pa-sm"
          v-if="!isReadonly && !checkRoutePermisson"
        >
          <q-space />
          <q-btn id="onSubmit" type="submit" label="บันทึก" color="secondary"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </div>
      </div>
    </q-form>
  </div>

  <!-- อัพโหลดไฟล์ -->

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

  <DialogAddPersonal
    title="ผู้ถูกร้องเรียน"
    :modal="modalPerson"
    btn-title="เพิ่มรายชื่อผู้ถูกร้องเรียน"
    :close="toggleModal"
    :selected-data="mainStore.rowsAdd"
    @returnData="handleSave"
  />

  <DialogDirector
    :get-list="getList"
    v-model:Modal="modal"
    :clickClose="clickClose"
    :rows2="investigateDis.rows2"
    v-model:filterKeyword2="filterKeyword2"
    v-model:type="type"
    :filterTable="filterTable"
    :rowsPerPage="rowsPerPage"
    :page="page"
    :maxPage="maxPage"
    :selected-row="rows"
    @update:pagination="updatePagingProp"
    @returnDirector="returnDirector"
  />

  <CalandarDialog
    :modal="calendarModal"
    :close="calendarModalclose"
    :lists="props.data.investigationExtendHistory"
  />

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

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

<style scope>
.q-banner {
  min-height: 25px;
}
.fixed-height-history {
  overflow-y: auto;
  max-height: 150px;
}
</style>
