<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import http from "@/plugins/http";
import config from "@/app.config";
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"; // สอบสวนความผิดทางวินัย
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 { useRouter, useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useDisciplineResultStore } from "@/modules/11_discipline/store/ResultStore";
import { useQuasar } from "quasar";
import DialogSendToCommand from "@/modules/11_discipline/components/4_Result/DialogSendToCommand.vue";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/main";

const mainStore = useDisciplineMainStore();
const $q = useQuasar();
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>('')

/**
 * บันทึกข้อมูลที่เเก้ไข
 * @param id ระบุ บุคคล
 */
const onSubmit = async (id: string) => {
  console.log("edit");
  router.push(`/discipline-result`);
};

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


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

const idInvestigate = ref<string>("");
const idComplaint = ref<string>("");
const status = ref<string>("");

const dataResult = ref<DataListRow[]>([]);
/** 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();
    });
}

const dataDisciplinary = ref<object>([]);
/** function  เรียกรายละเอียดสอบสวนความผิดทางวินัย*/
async function fetchDetailDisciplinary() {
  showLoader();
  await http
    .get(config.API.disciplineDisciplinaryById(id.value))
    .then((res) => {
      dataDisciplinary.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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: "",
  persons: [],
  investigationExtendHistory:[]
});
/** function เรียกรายละเอียดสืบสวนข้อเท็จจริง*/
async function fetchDetailInvestigate() {
  showLoader();
  await http
    .get(config.API.investigateById(idInvestigate.value))
    .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;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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: "",
  consideredAgency: "",
  title: "",
  description: "",
  dateReceived: null,
  dateConsideration: null,
  offenseDetails: "",
  levelConsideration: "",
  dateNotification: null,
  complaintFrom: "",
  appellant: "",
  documentFile: null,
  status: "",
  persons: [personObjComplaint],
  result: "",
  disciplineComplaintDocs: [fileListObjComplaint],
});
/** function เรียกรายละเอียดเรื่องร้องเรียน*/
async function fetchDetailComplaints() {
  showLoader();
  await http
    .get(config.API.complaintbyId(idComplaint.value))
    .then((res) => {
      const dataList = res.data.result;
      dataComplaints.id = dataList.id;
      dataComplaints.respondentType = dataList.respondentType;
      dataComplaints.organizationId = dataList.organizationId;
      dataComplaints.consideredAgency = dataList.consideredAgency;
      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();
    });
}

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

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());
  }
);
</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">แก้ไขผลการพิจารณาทางวินัย</div>
      <q-space />
      <div class="q-gutter-x-sm">
        <q-btn
          v-if="status === 'DONE'"
          label="ส่งไปออกคำสั่งลงโทษทางวินัย"
          color="public"
          @click="sentIssue('ส่งไปออกคำสั่งลงโทษทางวินัย')"
        />
        <q-btn
          v-if="status === 'DONE'"
          label="ส่งไปออกคำสั่งงดโทษ/เพิ่มโทษ"
          color="blue-6"
          @click="sentIssue('ส่งไปออกคำสั่งงดโทษ/เพิ่มโทษ')"
        />
      </div>
    </div>
    <q-card 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>
    <!-- <Form :on-submit="onSubmit" :data="data" /> -->
  </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>
