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

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

import type { OptionData } from "@/modules/07_insignia/interface/index/Main";
import type { DataOption } from "@/modules/11_discipline/interface/index/Main";
import type {
  FormData,
  ArrayFileList,
} from "@/modules/11_discipline/interface/request/complaint";

import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";
import DialogAddPersonal from "@/components/Dialogs/AddPersonal.vue";

const $q = useQuasar();
const fileDocDataUpload = ref<File[]>([]);
const channelOptions = ref<DataOption[]>([]);
const route = useRoute();
/** เรียกใช้ store */
const mixin = useCounterMixin();
const mainStore = useDisciplineMainStore();
const complainstStore = useComplainstDataStore();
const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");
const organization = ref<OptionData>();
const consideredAgency = ref<OptionData>();
const checkRoutePermisson = ref<boolean>(
  route.name == "disciplineComplaintsDetail"
);
/**ชั่งฟังเพิ่มข้อมูล ลง ตาราง */
const modal = ref<boolean>(false);
const toggleModal = () => (modal.value = !modal.value);
const {
  date2Thai,
  dialogConfirm,
  dialogRemove,
  success,
  messageError,
  hideLoader,
  showLoader,
  downloadRenameFileByLink,
} = mixin;
const { filterSelector } = complainstStore; // function จาก store complainstStore

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

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

const formData = reactive<FormData>({
  id: "",
  respondentType: "",
  organizationId: null,
  consideredAgency: "",
  title: "",
  description: "",
  dateReceived: null,
  dateConsideration: null,
  offenseDetails: "NOT_SPECIFIED",
  levelConsideration: "",
  dateNotification: null,
  complaintFrom: "",
  appellant: "",
  documentFile: null,
  status: "",
  result: "",
  persons: [],
  disciplineComplaintDocs: fileList.value ?? null,
  activeId: null,
  organization: "",
  consideredAgencyId: null,
});

/**
 * ฟังชั่นอัปโหลดไฟล์
 * @param documentFile ไฟล์ที่รับมา
 */
async function fileUploadDoc(documentFile: any) {
  documentFile.forEach((file: any) => {
    fileDocDataUpload.value.push(file);
  });
}

/**
 * เลือกระดับการพิจารณา
 * @param val รับตัวเลข ในรูปแบบ string
 */
function selectLevel(val: string) {
  let dayNum = 0;
  if (val == "VERY_URGENT") {
    dayNum = 15; // ด่วนมาก
  } else if (val == "URGENT") {
    dayNum = 30; // ด่วน
  } else {
    dayNum = 45; // ปกติ
  }
  // วันแจ้งเตือนล่วงหน้า
  if (formData.dateReceived) {
    const currentDate = new Date(formData.dateReceived);
    const newDate = new Date(
      currentDate.getTime() + dayNum * 24 * 60 * 60 * 1000
    );
    formData.dateConsideration = newDate;
  }
}

/** ฟังชั่น บันทึก */
function onSubmit() {
  dialogConfirm($q, async () => {
    if (mainStore.rowsAdd) {
      formData.persons = await mainStore.rowsAdd;
    }
    await props.onSubmit(formData);
    isSave.value = false;
  });
}

/**
 * ลบไฟล์
 * @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.complaintFileDelete(formData.id, id))
    .then(async (res) => {
      await props.getData();
      success($q, `ลบไฟล์สำเร็จ`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {});
}

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

/**
 * ฟังก์ชั่นสำหรับอัพโหลดไฟล์เอกสารหลักฐาน
 */
function upLoadFileDoc() {
  const Data = new FormData();
  Data.append("file", formData.documentFile);
  showLoader();
  http
    .put(config.API.complaintFileUpload(formData.id), Data)
    .then(async (res) => {
      await props.getData();
      countNum.value = 2;
      formData.documentFile = null;

      success($q, "อัพโหลดไฟล์สำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}

/**
 * ฟังก์ชั่นเพิ่มรายชื่อผู้ถูกสอบสวนจาก popup มายังรายการผู้ถูกสอบสวนหน้าหลัก
 * @param data ข้อมูลรายชื่อผู้ถูกสอบสวนเป็น array
 */
async function addPerson(data: any) {
  toggleModal();
  changeFormData();
  await mainStore.fetchData(data);
}

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

/** ดึงข้อมูลหน่วยงานจาก api */
async function getOc(activeId: string) {
  showLoader();
  await http
    .get(config.API.orgByIdSystem(activeId, route.meta.Key as string))
    .then(async (res) => {
      const data = await res.data.result.map((item: any) => ({
        organizationId: item.orgTreeId,
        organizationName: item.orgName,
      }));
      complainstStore.ocListFn(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชั่นลบผู้ถูกร้องเรียนออกจากรายการ
 * @param id id ของผู้ถูกร้อง
 */
function deletePerson(id: string) {
  const dataRow = mainStore.rowsAdd;
  const updatedRows = dataRow.filter((item: any) => item.personId !== id);
  mainStore.rowsAdd = updatedRows;
  changeFormData();
}

/** ช่องทางการร้องเรียน และฟังก์ชั่นการดึงข้อมูลช่องทางการร้องเรียนมาจาก api*/
function getListChannel() {
  http
    .get(
      config.API.complaintListOp(
        mainStore.pathComplaintsChannal(route.name as string)
      )
    )
    .then((res) => {
      channelOptions.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** ฟังก์ชั่นเช็คการแก้ไขฟอร์มแล้วไม่ได้กดบันทึก */
function changeFormData() {
  isSave.value = props.data != null ? true : false;
  if (organization.value) {
    formData.organizationId = organization.value.id;
    formData.organization = organization.value.name;
  }
  if (consideredAgency.value) {
    formData.consideredAgencyId = consideredAgency.value.id;
    formData.consideredAgency = consideredAgency.value.name;
  }
}

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

/**
 * pop up รายละเอียดบุคคล
 * @param id id ของบุคคล
 */
function onclickViewinfo(id: string) {
  modalPersonal.value = true;
  personId.value = id;
}

/**
 * ปิด modal
 * @param modal false
 */
function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

const optionOrganization = ref<any[]>(complainstStore.organizationIdOp);
function filterOptionFnOrganization(val: string, update: Function) {
  update(() => {
    optionOrganization.value = complainstStore.organizationIdOp.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}
const optionAgency = ref<any[]>(complainstStore.consideredAgencytoptions);
function filterOptionFnAgency(val: string, update: Function) {
  update(() => {
    optionAgency.value = complainstStore.consideredAgencytoptions.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

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

      fileList.value = props.data.disciplineComplaintDocs;
      mainStore.fetchData(props.data.persons);

      formData.id = props.data.id;
      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.consideredAgencyId = props.data.consideredAgencyId;
      consideredAgency.value = {
        id: props.data.consideredAgencyId,
        name: props.data.consideredAgency,
      };
      formData.title = props.data.title;
      formData.description = props.data.description;
      formData.dateReceived = props.data.dateReceived;
      formData.dateConsideration = props.data.dateConsideration;
      formData.offenseDetails = props.data.offenseDetails;
      formData.levelConsideration = props.data.levelConsideration;
      formData.dateNotification = props.data.dateNotification;
      formData.complaintFrom = props.data.complaintFrom;
      formData.appellant = props.data.appellant;
      formData.status = props.data.status;
      formData.result = props.data.result;
      formData.persons = mainStore.rowsAdd;
      formData.activeId = props.data.activeId ? props.data.activeId : null;
    } else if (countNum.value === 2) {
      fileList.value = props.data.disciplineComplaintDocs;
    }
  }
});

/** โหลดข้อมูลเมื่อเข้าหน้านี้ */
onMounted(async () => {
  mainStore.rowsAdd = [];
  await Promise.all([getActive(), getListChannel()]);
});
</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
      autocomplete="off"
      @validation-success="onSubmit"
      class="col-12 row"
    >
      <div class="col-12 row">
        <div class="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-4" 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
                  hide-selected
                  fill-input
                  map-options
                  hide-bottom-space
                  :options="complainstStore.complainantoptions"
                  :rules="[(val:string) => !!val || `${'กรุณาเลือกผู้ร้องเรียน'}`]"
                  @filter="(inputValue: any,
              doneFn: Function) => 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-8"
                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"
                  hide-selected
                  fill-input
                  map-options
                  v-model="organization"
                  :options="optionOrganization"
                  label="หน่วยงานที่ถูกร้องเรียน"
                  :rules="[
                    (val:string) => !!val || `${'กรุณาเลือกหน่วยงานที่ถูกร้องเรียน'}`,
                  ]"
                  @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-8" id="consideredAgency">
                <q-select
                  :class="inputEdit(isReadonly)"
                  ref="consideredAgencyRef"
                  for="selectAgency"
                  dense
                  outlined
                  v-model="consideredAgency"
                  :options="optionAgency"
                  label="หน่วยงานที่พิจารณา"
                  option-value="id"
                  option-label="name"
                  :readonly="isReadonly || checkRoutePermisson"
                  hide-bottom-space
                  map-options
                  hide-selected
                  fill-input
                  :rules="[(val:string) => !!val || `${'กรุณาเลือกหน่วยงาน'}`]"
                  @update:model-value="changeFormData()"
                  use-input
                  @filter="filterOptionFnAgency"
                >
                  <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-12 row q-pa-sm">
                    <d-table
                      ref="table"
                      :columns="mainStore.columnsRespondent"
                      :rows="mainStore.rowsAdd"
                      row-key="idcard"
                      flat
                      bordered
                      :paging="true"
                      dense
                      class="col-12"
                      :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 auto-width>
                            <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"
                              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 === 'positionLevel'"
                              class="table_ellipsis"
                            >
                              {{
                                props.row.positionLevel
                                  ? props.row.positionLevel
                                  : "-"
                              }}
                            </div>
                            <div v-else-if="col.name === 'salary'">
                              {{
                                props.row.salary
                                  ? props.row.salary.toLocaleString()
                                  : "-"
                              }}
                            </div>
                            <div v-else>
                              {{ col.value }}
                            </div>
                          </q-td>
                        </q-tr>
                      </template>
                    </d-table>
                  </div>
                </q-card>
              </div>

              <div class="col-xs-12 col-sm-12" id="title">
                <q-input
                  for="inputTopicComplaint"
                  ref="titleRef"
                  dense
                  :class="inputEdit(isReadonly)"
                  outlined
                  :readonly="isReadonly || checkRoutePermisson"
                  hide-bottom-space
                  v-model="formData.title"
                  :rules="[(val:string) => !!val || 'กรุณากรอกเรื่องร้องเรียน']"
                  label="เรื่องร้องเรียน"
                  type="textarea"
                  rows="5"
                  @update:model-value="changeFormData()"
                />
              </div>

              <div class="col-xs-12 col-sm-12" id="description">
                <q-input
                  :class="inputEdit(isReadonly)"
                  for="inputDetail"
                  ref="descriptionRef"
                  dense
                  outlined
                  :readonly="isReadonly || checkRoutePermisson"
                  hide-bottom-space
                  v-model="formData.description"
                  label="รายละเอียดเรื่องร้องเรียน"
                  type="textarea"
                  rows="5"
                  @update:model-value="changeFormData()"
                />
              </div>

              <div class="col-xs-12 col-sm-3" id="dateReceived">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="formData.dateReceived"
                  :locale="'th'"
                  autoApply
                  borderless
                  :readonly="isReadonly || checkRoutePermisson"
                  :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
                      for="inputDatereceive"
                      ref="dateReceivedRef"
                      outlined
                      dense
                      :class="inputEdit(isReadonly)"
                      :readonly="isReadonly || checkRoutePermisson"
                      hide-bottom-space
                      :model-value="
                        formData.dateReceived != null
                          ? date2Thai(formData.dateReceived)
                          : null
                      "
                      label="วันที่รับเรื่อง"
                      :rules="[
                        (val:any) => !!val || `${'กรุณาเลือกวันที่รับเรื่อง'}`,
                      ]"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="col-xs-12 col-sm-3" id="levelConsideration">
                <q-select
                  :class="inputEdit(isReadonly)"
                  for="selectConsiderationLevel"
                  ref="levelConsiderationRef"
                  dense
                  outlined
                  :readonly="isReadonly || checkRoutePermisson"
                  v-model="formData.levelConsideration"
                  :options="complainstStore.levelConsiderationtOptions"
                  label="ระดับการพิจารณา"
                  option-value="id"
                  option-label="name"
                  emit-value
                  clearable
                  hide-bottom-space
                  map-options
                  @update:model-value="
                    selectLevel(formData.levelConsideration);
                    changeFormData();
                  "
                />
              </div>

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

              <div class="col-xs-12 col-sm-3" id="offenseDetails">
                <q-select
                  :class="inputEdit(isReadonly)"
                  for="selectOffenseDescription"
                  ref="offenseDetailsRef"
                  dense
                  outlined
                  :readonly="isReadonly || checkRoutePermisson"
                  v-model="formData.offenseDetails"
                  :options="mainStore.offenseDetailstOptions"
                  label="ลักษณะความผิด"
                  option-value="id"
                  option-label="name"
                  emit-value
                  hide-bottom-space
                  map-options
                  clearable
                  @update:model-value="changeFormData()"
                />
              </div>

              <div class="col-xs-12 col-sm-3" id="dateNotification">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="formData.dateNotification"
                  :locale="'th'"
                  autoApply
                  :readonly="isReadonly || checkRoutePermisson"
                  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
                      for="inputDatewarn"
                      ref="dateNotificationRef"
                      outlined
                      :class="inputEdit(isReadonly)"
                      dense
                      :readonly="isReadonly || checkRoutePermisson"
                      hide-bottom-space
                      :model-value="
                        formData.dateNotification != null
                          ? date2Thai(formData.dateNotification)
                          : 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.dateNotification &&
                          !isReadonly &&
                          !checkRoutePermisson
                        "
                        v-slot:append
                      >
                        <q-icon
                          name="cancel"
                          @click.stop.prevent="formData.dateNotification = null"
                          class="cursor-pointer"
                        />
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>

              <div class="col-xs-12 col-sm-3" id="complaintFrom">
                <q-select
                  :class="inputEdit(isReadonly)"
                  for="selectReceivecomplaints"
                  ref="complaintFromRef"
                  dense
                  :readonly="isReadonly || checkRoutePermisson"
                  outlined
                  v-model="formData.complaintFrom"
                  :options="channelOptions"
                  label="รับเรื่องร้องเรียน"
                  option-value="id"
                  option-label="name"
                  hide-bottom-space
                  emit-value
                  clearable
                  map-options
                  @update:model-value="changeFormData()"
                />
              </div>

              <div class="col-xs-12 col-sm-12" id="appellant">
                <q-input
                  :class="inputEdit(isReadonly)"
                  for="inputPetitioner"
                  ref="appellantRef"
                  dense
                  outlined
                  v-model="formData.appellant"
                  :readonly="isReadonly || checkRoutePermisson"
                  label="ผู้ร้องเรียน"
                  hide-bottom-space
                  type="textarea"
                  rows="5"
                  @update:model-value="changeFormData()"
                />
              </div>
              <div class="col-xs-12 col-sm-12">
                <q-input
                  :class="inputEdit(isReadonly)"
                  :readonly="isReadonly || checkRoutePermisson"
                  for="result"
                  ref="resultRef"
                  dense
                  outlined
                  hide-bottom-space
                  v-model="formData.result"
                  label="ผลการตรวจสอบเรื่องร้องเรียน"
                  type="textarea"
                  rows="5"
                  @update:model-value="changeFormData()"
                />
              </div>
            </div>
          </div>
          <div class="row"><q-separator vertical /></div>
        </div>

        <!-- อัพโหลดไฟล์ -->
        <div class="col-sm-12 col-md-3">
          <div flat class="q-pa-md">
            <div class="col-12 row q-col-gutter-md">
              <div class="row col-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"
                  >
                    {{
                      !isReadonly
                        ? "อัปโหลดไฟล์เอกสารหลักฐาน"
                        : "ไฟล์เอกสารหลักฐาน"
                    }}
                  </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
                        for="inputFiles"
                        class="col-12"
                        outlined
                        dense
                        v-model="formData.documentFile"
                        @added="fileUploadDoc"
                        label="ไฟล์เอกสารหลักฐาน"
                        hide-bottom-space
                        accept=".pdf,.xlsx,.docx,.png,.jpg"
                        clearable
                      >
                        <template v-slot:prepend>
                          <q-icon name="attach_file" color="primary" />
                        </template>
                        <template v-slot:after>
                          <q-btn
                            size="14px"
                            v-if="formData.documentFile"
                            flat
                            round
                            dense
                            color="add"
                            icon="mdi-upload"
                            @click="upLoadFileDoc()"
                            ><q-tooltip>อัปโหลดไฟล์</q-tooltip></q-btn
                          >
                        </template>
                      </q-file>

                      <!-- <div class="col-1 self-center" v-if="formData.documentFile"></div> -->
                    </div>

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

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

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

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

<style scoped>
.q-banner {
  min-height: 25px;
}
</style>
@/modules/11_discipline/store/store
