<script setup lang="ts">
import { ref, onMounted, reactive, watch } from "vue";
import { useQuasar, QForm } from "quasar";
import { useRouter, useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import Dialogbody from "@/modules/11_discipline/components/3_InvestigateDisciplinary/Dialogbody.vue";
import Table from "@/modules/11_discipline/components/3_InvestigateDisciplinary/DirectorTable.vue";
import { useInvestigateDisStore } from "@/modules/11_discipline/store/InvestigateDisStore";
import type {
  FormData,
  disciplinaryRef,
} from "@/modules/11_discipline/interface/request/disciplinary";
const investigateDis = useInvestigateDisStore();
const { fecthDirector } = investigateDis;
const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
});
onMounted(async () => {
  await fecthDirector([
    {
      nameDirector: "นาง เกสินี เจียรสุมัย",
      position: "ครู",
      duty: "ประธาน",
      email: "e@email.com",
      telephone: "0800808080",
      role: "4",
    },
    {
      nameDirector: "นาย สรวิชญ์ พลสิทธิ์",
      position: "ทดลองงาน",
      duty: "เลขานุการ",
      email: "g@gmail.com",
      telephone: "0614565145",
      role: "6",
    },
  ]);
  await hideLoader();
});

const popup = () => {
  modal.value = true;
  filterKeyword2.value = "";
};

const mixin = useCounterMixin();
const { date2Thai, hideLoader, dialogConfirm } = mixin;
const router = useRouter();
const route = useRoute();
const rows = ref([]);
const modal = ref<boolean>(false);
const $q = useQuasar();
const id = ref<string>(route.params.id as string);
const type = ref<string>("");
const myForm = ref<QForm | null>(null); //form data input
const edit = ref<boolean>(false);
const dateInvestigate = ref<Date>(new Date());
const dateAllegation = ref<Date>(new Date());
const dateEvident = ref<Date>(new Date());
const filterKeyword2 = ref<string>("");
const complaintRef = ref<Object | null>(null);
const dateInvestigateRef = ref<Object | null>(null);
const dateAllegationRef = ref<Object | null>(null);
const dateEvidentRef = ref<Object | null>(null);
const casefaultRef = ref<Object | null>(null);
const refLawRef = ref<Object | null>(null);
const typefaultRef = ref<Object | null>(null);
const faultLevelRef = ref<Object | null>(null);
const detailComplaintRef = ref<Object | null>(null);
const whereInvestigateRef = ref<Object | null>(null);
const witnessesRef = ref<Object | null>(null);
const InvestResultsRef = ref<Object | null>(null);
const filesEvidenceRef = ref<Object | null>(null);
const filesRecordAccuserRef = ref<Object | null>(null);
const filesWitnessesRef = ref<Object | null>(null);
const filesEtcRef = ref<Object | null>(null);
const trueDetailRef = ref<Object | null>(null);
const evidenceRef = ref<Object | null>(null);
const recordAccuserRef = ref<Object | null>(null);
const complaintsOptions = ref<any>([]);

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

const formData = reactive<FormData>({
  complaint: "",
  dateInvestigate: null,
  dateAllegation: null,
  dateEvident: null,
  casefault: "",
  typefault: "",
  faultLevel: "",
  refLaw: "",
  detailComplaint: "",
  whereInvestigate: "",
  trueDetail: "",
  evidence: "",
  recordAccuser: "",
  witnesses: "",
  InvestResults: "",
  filesEvidence: null,
  filesRecordAccuser: null,
  filesWitnesses: null,
  filesEtc: null,
});

const objectdisciplinary: disciplinaryRef = {
  complaint: complaintRef,
  dateInvestigate: dateInvestigateRef,
  dateAllegation: dateAllegationRef,
  dateEvident: dateEvidentRef,
  casefault: casefaultRef,
  typefault: typefaultRef,
  faultLevel: faultLevelRef,
  refLaw: refLawRef,
  detailComplaint: detailComplaintRef,
  whereInvestigate: whereInvestigateRef,
  trueDetail: trueDetailRef,
  evidence: evidenceRef,
  recordAccuser: recordAccuserRef,
  witnesses: witnessesRef,
  InvestResults: InvestResultsRef,
  filesEvidence: filesEvidenceRef,
  filesRecordAccuser: filesRecordAccuserRef,
  filesWitnesses: filesWitnessesRef,
  filesEtc: filesEtcRef,
};

function validateForm() {
  const hasError = [];
  for (const key in objectdisciplinary) {
    if (Object.prototype.hasOwnProperty.call(objectdisciplinary, key)) {
      const property = objectdisciplinary[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    onSubmit();
  } else {
    console.log("ไม่ผ่าน ");
    console.log(hasError);
  }
}

const routeName = router.currentRoute.value.name;

const clickClose = () => {
  modal.value = false;
};

// เรียกข้อมูลของรอบการเสนอขอ

const filter = ref<string>(""); //search data table

const fileUploadDoc = async (files: any) => {
  files.forEach((file: any) => {
    fileDocDataUpload.value.push(file);
  });
};

// คลิกบันทึก
function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      console.log(formData);
      props.onSubmit();
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

const deleteData = async (id: string) => {
  console.log("delete");
};

const clickBack = () => {
  router.push(`/discipline/disciplinary`);
};
watch(props.data, async () => {
  formData.complaint = props.data.complaint;
  formData.dateInvestigate = props.data.dateInvestigate;
  formData.dateAllegation = props.data.dateAllegation;
  formData.dateEvident = props.data.dateEvident;
  formData.casefault = props.data.casefault;
  formData.typefault = props.data.typefault;
  formData.faultLevel = props.data.faultLevel;
  formData.refLaw = props.data.refLaw;
  formData.detailComplaint = props.data.detailComplaint;
  formData.whereInvestigate = props.data.whereInvestigate;
  formData.trueDetail = props.data.trueDetail;
  formData.evidence = props.data.evidence;
  formData.recordAccuser = props.data.recordAccuser;
  formData.witnesses = props.data.witnesses;
  formData.InvestResults = props.data.InvestResults;
  formData.filesEvidence = props.data.filesEvidence;
  formData.filesRecordAccuser = props.data.filesRecordAccuser;
  formData.filesWitnesses = props.data.filesWitnesses;
  formData.filesEtc = props.data.filesEtc;
});
</script>
<template>
  <div class="col-xs-12 col-sm-12 col-md-11">
    <form @submit.prevent="validateForm">
      <div class="col-12">
        <q-card bordered>
          <div class="col-12 row q-pa-md">
            <div class="col-12 row q-col-gutter-md">
              <div class="col-12">
                <q-select
                  for="#fault"
                  outlined
                  dense
                  ref="complaintRef"
                  v-model="formData.complaint"
                  :rules="[(val) => !!val || `${'กรุณาเลือกเรื่องร้องเรียน'}`]"
                  :options="complaintsOptions"
                  label="เรื่องร้องเรียน"
                  emit-value
                  map-options
                  option-label="name"
                  option-value="id"
                  use-input
                  ><template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        ไม่มีข้อมูล
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>

              <datepicker
                menu-class-name="modalfix"
                v-model="dateInvestigate"
                ref="dateInvestigateRef"
                for="#dateInvestigate"
                :locale="'th'"
                autoApply
                class="col-xs-12 col-sm-4"
                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
                    outlined
                    dense
                    class="full-width datepicker"
                    hide-bottom-space
                    :model-value="
                      dateInvestigate != null
                        ? date2Thai(dateInvestigate)
                        : null
                    "
                    :label="`${'วันที่สอบสวน'}`"
                    :rules="[(val) => !!val || `${'กรุณาเลือกวันที่สอบสวน'}`]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>

              <datepicker
                menu-class-name="modalfix"
                ref="dateAllegationRef"
                for="#dateAllegation"
                v-model="dateAllegation"
                class="col-xs-12 col-sm-4"
                :locale="'th'"
                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
                    outlined
                    dense
                    class="col-xs-12 col-sm-4"
                    hide-bottom-space
                    :model-value="
                      dateAllegation != null ? date2Thai(dateAllegation) : null
                    "
                    :label="`${'วันที่รับทราบข้อกล่าวหา'}`"
                    :rules="[
                      (val) =>
                        !!val || `${'กรุณาเลือกวันที่รับทราบข้อกล่าวหา'}`,
                    ]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>

              <datepicker
                menu-class-name="modalfix"
                ref="dateEvidentRef"
                for="#dateEvident"
                v-model="dateEvident"
                :locale="'th'"
                autoApply
                class="col-xs-12 col-sm-4"
                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
                    outlined
                    dense
                    class="full-width datepicker"
                    hide-bottom-space
                    :model-value="
                      dateEvident != null ? date2Thai(dateEvident) : null
                    "
                    :label="`${'วันที่สรุปพยานหลักฐาน'}`"
                    :rules="[
                      (val) => !!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 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
                      size="12px"
                      flat
                      round
                      dense
                      color="add"
                      class="q-ml-sm"
                      @click="popup()"
                      icon="mdi-plus"
                    >
                      <q-tooltip>เพิ่มกรรมการ</q-tooltip>
                    </q-btn>
                  </div>
                  <div class="col-12"><q-separator /></div>
                  <div class="col-xs-12 q-pa-sm row">
                    <Table
                      class="col-12"
                      style="max-height: 80vh"
                      :rows="rows"
                      :columns="investigateDis.columnsDirector"
                      :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
                            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-td>
                            <q-btn
                              dense
                              size="12px"
                              flat
                              round
                              color="red"
                              @click="deleteData(props.row.id)"
                              icon="mdi-delete"
                            >
                              <q-tooltip>ลบข้อมูล</q-tooltip>
                            </q-btn>
                          </q-td>
                        </q-tr>
                      </template>
                    </Table>
                  </div>
                </q-card>
              </div>
              <q-input
                class="col-xs-12 col-sm-6"
                dense
                outlined
                ref="casefaultRef"
                v-model="formData.casefault"
                for="#casefault"
                label="กรณีมีความผิด"
                hide-bottom-space
                :rules="[(val) => !!val || `${'กรุณากรอกกรณีมีความผิด'}`]"
                lazy-rules
              />
              <q-input
                class="col-xs-12 col-sm-6"
                dense
                hide-bottom-space
                outlined
                for="#whereInvestigate"
                ref="whereInvestigateRef"
                v-model="formData.whereInvestigate"
                label="สอบสวนที่"
                :rules="[(val) => !!val || `${'กรุณากรอกสอบสวนที่'}`]"
                lazy-rules
              />
              <q-select
                dense
                class="col-xs-12 col-sm-3"
                outlined
                for="#typefault"
                ref="typefaultRef"
                v-model="formData.typefault"
                option-label="name"
                option-value="id"
                emit-value
                map-options
                hide-bottom-space
                :options="investigateDis.optionsTypefault"
                label="ลักษณะความผิด"
              />
              <q-select
                dense
                class="col-xs-12 col-sm-3"
                outlined
                for="#faultLevel"
                ref="faultLevelRef"
                v-model="formData.faultLevel"
                option-label="name"
                option-value="id"
                emit-value
                map-options
                hide-bottom-space
                :options="investigateDis.optionsfaultLevel"
                label="ระดับโทษความผิด"
              />
              <q-input
                class="col-xs-12 col-sm-6"
                dense
                for="#refLaw"
                hide-bottom-space
                outlined
                ref="refLawRef"
                v-model="formData.refLaw"
                label="อ้างอิงมาตราตามกฎหมาย"
                :rules="[
                  (val) => !!val || `${'กรุณากรอกอ้างอิงมาตราตามกฎหมาย'}`,
                ]"
                lazy-rules
              />
              <q-input
                class="col-12"
                dense
                outlined
                hide-bottom-space
                for="#detailComplaint"
                ref="detailComplaintRef"
                v-model="formData.detailComplaint"
                label="รายละเอียดเรื่องร้องเรียน"
                type="textarea"
                :rules="[(val:string) => !!val || `${'กรุณากรอกรายละเอียดเรื่องร้องเรียน'}`]"
              />
              <q-input
                class="col-12"
                dense
                outlined
                hide-bottom-space
                for="#trueDetail"
                ref="trueDetailRef"
                v-model="formData.trueDetail"
                label="รายละเอียดสืบสวนข้อเท็จจริง"
                type="textarea"
                :rules="[(val:string) => !!val || `${'กรุณากรอกรายละเอียดสืบสวนข้อเท็จจริง'}`]"
              />
              <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"
                  >
                    หลักฐานสนับสนุนข้อกล่าวหา
                  </div>
                  <div class="col-12"><q-separator /></div>
                  <div class="col-xs-12 q-pa-sm row">
                    <q-input
                      class="col-12"
                      dense
                      outlined
                      for="#evidence"
                      ref="evidenceRef"
                      hide-bottom-space
                      v-model="formData.evidence"
                      label="สรุปพยานหลักฐานสนับสนุนข้อกล่าวหา"
                      type="textarea"
                      :rules="[(val:string) => !!val || `${'กรุณากรอกสรุปพยานหลักฐานสนับสนุนข้อกล่าวหา'}`]"
                    />
                    <q-file
                      class="col-12 q-mt-sm"
                      outlined
                      dense
                      ref="filesEvidenceRef"
                      for="#filesEvidence"
                      v-model="formData.filesEvidence"
                      @added="fileUploadDoc"
                      label="ไฟล์เอกสารหลักฐานสรุปพยานหลักฐานสนับสนุนข้อกล่าวหา"
                      hide-bottom-space
                      lazy-rules
                      accept=".pdf,.xlsx,.doc"
                    >
                      <template v-slot:prepend>
                        <q-icon name="attach_file" />
                      </template>
                    </q-file>
                  </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"
                  >
                    บันทึกถ้อยคำของผู้กล่าวหา
                  </div>
                  <div class="col-12"><q-separator /></div>
                  <div class="col-xs-12 q-pa-sm row">
                    <q-input
                      class="col-12"
                      dense
                      outlined
                      ref="recordAccuserRef"
                      for="#recordAccuser"
                      v-model="formData.recordAccuser"
                      label="บันทึกถ้อยคำของผู้กล่าวหา"
                      hide-bottom-space
                      type="textarea"
                      :rules="[(val:string) => !!val || `${'กรุณากรอกบันทึกถ้อยคำของผู้กล่าวหา'}`]"
                    />
                    <q-file
                      class="col-12 q-mt-sm"
                      outlined
                      dense
                      ref="filesRecordAccuserRef"
                      for="#filesRecordAccuser"
                      v-model="formData.filesRecordAccuser"
                      @added="fileUploadDoc"
                      label="ไฟล์เอกสารบันทึกถ้อยคำของผู้กล่าวหา"
                      hide-bottom-space
                      lazy-rules
                      accept=".pdf,.xlsx,.doc"
                    >
                      <template v-slot:prepend>
                        <q-icon name="attach_file" />
                      </template>
                    </q-file>
                  </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"
                  >
                    พยานและการบันทึกถ้อยคำ
                  </div>
                  <div class="col-12"><q-separator /></div>
                  <div class="col-xs-12 q-pa-sm row">
                    <q-input
                      class="col-12"
                      dense
                      outlined
                      for="#witnesses"
                      ref="witnessesRef"
                      v-model="formData.witnesses"
                      label="พยานและการบันทึกถ้อยคำ"
                      hide-bottom-space
                      type="textarea"
                      :rules="[(val:string) => !!val || `${'กรุณากรอกพยานและการบันทึกถ้อยคำ'}`]"
                    />
                    <q-file
                      class="col-12 q-mt-sm"
                      outlined
                      dense
                      ref="filesWitnessesRef"
                      for="#filesWitnesses"
                      v-model="formData.filesWitnesses"
                      @added="fileUploadDoc"
                      label="ไฟล์เอกสารพยานและการบันทึกถ้อยคำ"
                      hide-bottom-space
                      lazy-rules
                      accept=".pdf,.xlsx,.doc"
                    >
                      <template v-slot:prepend>
                        <q-icon name="attach_file" />
                      </template>
                    </q-file>
                  </div>
                </q-card>
              </div>
              <q-input
                class="col-12"
                dense
                outlined
                for="#InvestResults"
                ref="InvestResultsRef"
                v-model="formData.InvestResults"
                label="ผลการสอบสวน"
                hide-bottom-space
                type="textarea"
                :rules="[(val:string) => !!val || `${'กรุณากรอกผลการสอบสวน'}`]"
              />
              <q-file
                class="col-12"
                outlined
                dense
                ref="filesEtcRef"
                for="#filesEtc"
                v-model="formData.filesEtc"
                @added="fileUploadDoc"
                label="ไฟล์เอกสารหลักฐานอื่น ๆ"
                hide-bottom-space
                lazy-rules
                accept=".pdf,.xlsx,.doc"
              >
                <template v-slot:prepend>
                  <q-icon name="attach_file" />
                </template>
              </q-file>
            </div>
          </div>
          <q-separator />
          <div class="row col-12 q-pa-sm">
            <q-space />
            <q-btn
              for="ButtonOnSubmit"
              id="formSubmit"
              color="secondary"
              label="บันทึก"
              type="submit"
              ><q-tooltip>บับทึกข้อมูล</q-tooltip></q-btn
            >
          </div>
        </q-card>
      </div>
    </form>
  </div>
  <Dialogbody
    v-model:Modal="modal"
    :clickClose="clickClose"
    :rows2="investigateDis.rows2"
    v-model:filterKeyword2="filterKeyword2"
    v-model:type="type"
  />
  <!-- :fecthlistappointment="fecthlistappointment" -->
</template>
