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

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

import type { DataListRow } from "@/modules/11_discipline/interface/request/Result";
import type {
  FormData as FormDataComplaint,
  ArrayPerson,
  ArrayFileList,
} from "@/modules/11_discipline/interface/request/complaint";
import type { FormData as FormInvestigateFact } from "@/modules/11_discipline/interface/request/InvestigateFact";

import DialogSendToCommand from "@/modules/11_discipline/components/4_Result/DialogSendToCommand.vue";
import FormComplaints from "@/modules/11_discipline/components/1_Complaint/Form.vue"; //เรื่องร้องเรียน
import FormInvestigatefacts from "@/modules/11_discipline/components/2_InvestigateFacts/Form.vue"; //สืบสวนข้อเท็จจริง
import FormDisciplinary from "@/modules/11_discipline/components/3_InvestigateDisciplinary/Form.vue"; // สอบสวนความผิดทางวินัย
import FormResult from "@/modules/11_discipline/components/4_Result/Form.vue"; // สอบสวนความผิดทางวินัย

const $q = useQuasar();
const mainStore = useDisciplineMainStore();
const mixin = useCounterMixin();
const store = useDisciplineResultStore();
const { showLoader, hideLoader, messageError } = mixin;
const router = useRouter();
const route = useRoute();

const id = ref<string>(route.params.id as string);
const titlePopup = ref<string>("");
const idInvestigate = ref<string>("");
const idComplaint = ref<string>("");
const status = ref<string>("");
const modal = ref<boolean>(false);
const dataResult = ref<DataListRow[]>([]);
const filterKeyword = ref<string>("");
const dataDisciplinary = ref<object>([]);
const checkRoutePermisson = ref<boolean>(
  route.name == "disciplineResultDetail"
);

const dataInvestigatefacts = reactive<FormInvestigateFact>({
  id: "",
  idComplaint: "",
  investigationDetail: "",
  complaint: "",
  complaintdetail: "",
  investigationDescription: "",
  fault: "",
  investigationDetailOther: "",
  evidenceFiles: null,
  fileComplaint: null,
  investigationExtendStatus: false,
  investigationDateStart: null,
  investigationDateEnd: null,
  investigationDaysExtend: null,
  investigationStatusResult: "",
  investigationCauseText: "",
  complaintStatus: "",
  result: "",
  directors: [],
  disciplineInvestigateDocs: [],
  disciplineInvestigateRelevantDocs: [],
  status: "",
  documentFile: null,
  respondentType: "",
  organizationId: "",
  organization: "",
  persons: [],
  investigationExtendHistory: [],
  isDisciplinary: false,
  isAncestorDNA: false,
});

const personObjComplaint = reactive<ArrayPerson>({
  id: "",
  personId: "",
  idcard: "",
  name: "",
  prefix: "",
  firstName: "",
  lastName: "",
  posNo: "",
  position: "",
  positionLevel: "",
  salary: null,
  organization: "",
});
const fileListObjComplaint = reactive<ArrayFileList>({
  id: "",
  pathName: "",
  fileName: "",
});
const dataComplaints = reactive<FormDataComplaint>({
  id: "",
  respondentType: "",
  organizationId: "",
  organization: "",
  consideredAgency: "",
  consideredAgencyId: "",
  title: "",
  description: "",
  dateReceived: null,
  dateConsideration: null,
  offenseDetails: "",
  levelConsideration: "",
  dateNotification: null,
  complaintFrom: "",
  appellant: "",
  documentFile: null,
  status: "",
  persons: [personObjComplaint],
  result: "",
  disciplineComplaintDocs: [fileListObjComplaint],
});

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

/**
 * บันทึกข้อมูลที่เเก้ไข
 * @param id ระบุ บุคคล
 */
async function onSubmit() {
  router.push(`/discipline-result`);
}

/** ยืนยัน ส่งไปออกคำสั่ง */
function sentIssue(title: string) {
  modal.value = true;
  titlePopup.value = title;
}

/** function เรียกรายละเอียดผลการพิจารณาทางวินัย*/
async function fetchDetailResult() {
  showLoader();
  await http
    .get(config.API.listResultById(id.value))
    .then((res) => {
      dataResult.value = res.data.result;
      status.value = res.data.result.status;
      idComplaint.value = res.data.result.idComplaint;
      idInvestigate.value = res.data.result.idInvestigate;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function  เรียกรายละเอียดสอบสวนความผิดทางวินัย*/
async function fetchDetailDisciplinary() {
  showLoader();
  await http
    .get(
      config.API.disciplineDisciplinaryByGetId(
        id.value,
        mainStore.pathDiscip(route.name as string)
      )
    )
    .then((res) => {
      dataDisciplinary.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เรียกรายละเอียดสืบสวนข้อเท็จจริง*/
async function fetchDetailInvestigate() {
  showLoader();
  await http
    .get(
      config.API.investigateByGetId(
        idInvestigate.value,
        mainStore.pathInves(route.name as string)
      )
    )
    .then((res) => {
      const dataList = res.data.result;
      dataInvestigatefacts.id = dataList.id;
      dataInvestigatefacts.idComplaint = dataList.idComplaint;
      dataInvestigatefacts.respondentType = dataList.respondentType;
      dataInvestigatefacts.persons = dataList.persons;
      dataInvestigatefacts.investigationDetail = dataList.investigationDetail;
      dataInvestigatefacts.investigationDetailOther =
        dataList.investigationDetailOther;
      dataInvestigatefacts.investigationDateStart =
        dataList.investigationDateStart;
      dataInvestigatefacts.investigationDateEnd = dataList.investigationDateEnd;
      dataInvestigatefacts.investigationDescription =
        dataList.investigationDescription;
      dataInvestigatefacts.investigationCauseText =
        dataList.investigationCauseText;
      dataInvestigatefacts.status = dataList.status;
      dataInvestigatefacts.result = dataList.result;
      dataInvestigatefacts.directors = dataList.director;
      dataInvestigatefacts.disciplineInvestigateDocs =
        dataList.disciplineInvestigateDocs;
      dataInvestigatefacts.disciplineInvestigateRelevantDocs =
        dataList.disciplineInvestigateRelevantDocs;
      dataInvestigatefacts.investigationStatusResult =
        dataList.investigationStatusResult;
      dataInvestigatefacts.investigationExtendStatus =
        dataList.investigationExtendStatus;
      dataInvestigatefacts.investigationDaysExtend =
        dataList.investigationDaysExtend;
      dataInvestigatefacts.organizationId = dataList.organizationId;
      dataInvestigatefacts.organization = dataList.organization;
      dataInvestigatefacts.investigationExtendHistory =
        dataList.investigationExtendHistory;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เรียกรายละเอียดเรื่องร้องเรียน*/
async function fetchDetailComplaints() {
  showLoader();
  await http
    .get(
      config.API.complaintbyGetId(
        idComplaint.value,
        mainStore.pathComplaints(route.name as string)
      )
    )
    .then((res) => {
      const dataList = res.data.result;
      dataComplaints.id = dataList.id;
      dataComplaints.respondentType = dataList.respondentType;
      dataComplaints.organizationId = dataList.organizationId;
      dataComplaints.organization = dataList.organization;
      dataComplaints.consideredAgency = dataList.consideredAgency;
      dataComplaints.consideredAgencyId = dataList.consideredAgencyId;
      dataComplaints.title = dataList.title;
      dataComplaints.description = dataList.description;
      dataComplaints.dateReceived = dataList.dateReceived;
      dataComplaints.levelConsideration = dataList.levelConsideration;
      dataComplaints.dateConsideration = dataList.dateConsideration;
      dataComplaints.offenseDetails = dataList.offenseDetails;
      dataComplaints.dateNotification = dataList.dateNotification;
      dataComplaints.complaintFrom = dataList.complaintFrom;
      dataComplaints.appellant = dataList.appellant;
      dataComplaints.status = dataList.status;
      dataComplaints.persons = dataList.persons;
      dataComplaints.result = dataList.result;
      dataComplaints.disciplineComplaintDocs = dataList.disciplineComplaintDocs;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

watch(
  () => store.tabMenu,
  async () => {
    const fetchFunction =
      store.tabMenu === "disciplinary"
        ? fetchDetailDisciplinary
        : store.tabMenu === "investigatefacts"
        ? fetchDetailInvestigate
        : store.tabMenu === "complaints"
        ? fetchDetailComplaints
        : store.tabMenu === "result"
        ? fetchDetailResult
        : null;

    fetchFunction && (await fetchFunction());
  }
);

/** โหลดข้อมูลเมื่อเข้าหน้านี้ */
onMounted(async () => {
  store.tabMenu = "result";
  await fetchDetailResult();
});
</script>

<template>
  <div class="col-xs-12 col-sm-12 col-md-11">
    <div class="toptitle col-12 row items-center">
      <q-btn
        icon="mdi-arrow-left"
        unelevated
        round
        dense
        flat
        color="primary"
        class="q-mr-sm"
        @click="$router.push(`/discipline-result`)"
      />
      <div class="q-ma-none">
        {{
          checkRoutePermisson
            ? "รายละเอียดผลการพิจารณาทางวินัย"
            : "แก้ไขผลการพิจารณาทางวินัย"
        }}
      </div>
      <q-space />
      <div class="q-gutter-x-sm" v-if="!checkRoutePermisson">
        <q-btn
          v-if="status === 'DONE'"
          label="ส่งไปออกคำสั่ง"
          color="public"
          @click="sentIssue('ส่งไปออกคำสั่ง')"
        />
      </div>
    </div>
    <q-card bordered flat class="col-12">
      <q-tabs
        v-model="store.tabMenu"
        dense
        align="left"
        inline-label
        class="rounded-borders"
        indicator-color="primary"
        active-bg-color="teal-1"
        active-class="text-primary"
      >
        <q-tab name="complaints" label="เรื่องร้องเรียน (สำเนา)" />
        <q-tab name="investigatefacts" label="สืบสวนข้อเท็จจริง (สำเนา)" />
        <q-tab name="disciplinary" label="สอบสวนความผิดทางวินัย (สำเนา)" />
        <q-tab name="result" label="ผลการพิจารณาทางวินัย" />
      </q-tabs>
      <q-separator />
      <q-tab-panels v-model="store.tabMenu" animated>
        <q-tab-panel name="complaints">
          <FormComplaints :on-submit="onSubmit" :data="dataComplaints" />
        </q-tab-panel>
        <q-tab-panel name="investigatefacts">
          <FormInvestigatefacts
            :on-submit="onSubmit"
            :data="dataInvestigatefacts"
          />
        </q-tab-panel>
        <q-tab-panel name="disciplinary">
          <FormDisciplinary :on-submit="onSubmit" :data="dataDisciplinary" />
        </q-tab-panel>
        <q-tab-panel name="result">
          <FormResult
            :on-submit="onSubmit"
            :data="dataResult"
            :fetchData="fetchDetailResult"
          />
        </q-tab-panel>
      </q-tab-panels>
    </q-card>
  </div>

  <DialogSendToCommand
    :title="titlePopup"
    v-model:modal="modal"
    :closeModal="closeModal"
    :rows2="[]"
    :columns="mainStore.columnsDirector"
    :visibleColumns="mainStore.visibleColumnsDirector"
    :data="dataResult"
    v-model:filterKeyword2="filterKeyword"
    :getData="fetchDetailResult"
  />
</template>

<style scoped>
.q-tab-panel {
  padding: 0;
  background-color: #f0f3f3;
}
</style>
