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

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

import type {
  PersonsArray,
  Persons,
} from "@/modules/11_discipline/interface/request/Disciplinary";
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 PopupSendToNext from "@/modules/11_discipline/components/PopupSendToNext.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"; // สอบสวนความผิดทางวินัย

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

const isSaveInfo = ref<boolean>(false);
const checkRoutePermisson = ref<boolean>(
  route.name == "disciplineDisciplinaryDetail"
);
const modalPopup = ref<boolean>(false);
const id = ref<string>(route.params.id as string);
const data = ref<object>();
const status = ref<string>("");

const idInvestigate = ref<string>("");
const idComplaint = ref<string>("");
const respondentRows = ref<Persons[]>([]);
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],
});

/** ข้อมูล v-model ของฟอร์มสืบสวน */
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,
});

/** function fetchData สอบสวนความผิดทางวินัย*/
async function fetchDetailDisciplinary() {
  showLoader();
  await http
    .get(config.API.disciplineDisciplinaryByGetId(id.value,mainStore.pathDiscip(route.name as string)))
    .then((res) => {
      data.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 fetchData สืบสวนข้อเท็จจริง*/
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;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function fetchData เรื่องร้องเรียน*/
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();
    });
}

/**
 * function บันทักข้อมูล
 * @param data ข้อมูล ใน form
 */
async function onSubmitDisciplinary(data: any) {
  console.log("🚀 ~ onSubmitDisciplinary ~ data:", data)
  showLoader();
  await http
    .put(config.API.disciplineDisciplinaryById(id.value), data)
    .then(async () => {
      await fetchDetailDisciplinary();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

/** ยืนยัน ส่งไปออกคำสั่ง */
async function sentIssue() {
  respondentRows.value = await store.rowSent.filter(
    (x) => x.isSuspend === "NEW" && x.isSend === "NEW"
  );
  modalPopup.value = true;
}

function sentIssueGate() {
  dialogConfirm(
    $q,
    () => confirmSentIssueGate(),
    "ยืนยันส่งไปสรุปผลการพิจารณา",
    "ต้องการยืนยันส่งไปสรุปผลการพิจารณาใช่หรือไม่?"
  );
}

function confirmSentIssueGate() {
  showLoader();
  http
    .get(config.API.disciplinaryApprove(id.value))
    .then((res) => {
      // fetchDetailDisciplinary();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      router.push(`/discipline/disciplinary`);
    });
}

/** ยืนยัน ยุติเรื่อง */
function endInvestigate() {
  dialogConfirm(
    $q,
    () => confirmEndInvestigate(),
    "ยืนยันยุติเรื่อง",
    "ต้องการยืนยันยุติเรื่องใช่หรือไม่?"
  );
}

/** ยืนยัน ยกเลิกการยุติเรื่อง */
function cancelInvestigate() {
  dialogConfirm(
    $q,
    () => confirmCancelInvestigate(),
    "ยืนยันยกเลิกการยุติเรื่อง",
    "ต้องการยืนยันยกเลิกการยุติเรื่องใช่หรือไม่?"
  );
}

/** ฟังชั่น ยุติเรื่อง*/
function confirmEndInvestigate() {
  showLoader();
  http
    .get(config.API.disciplinaryReject(id.value))
    .then((res) => {
      success($q, "ยุติเรื่องสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      fetchDetailDisciplinary();
    });
}

/** ฟังชั่น ยกเลิกการยุติเรื่อง*/
function confirmCancelInvestigate() {
  showLoader();
  http
    .get(config.API.disciplinaryResume(id.value))
    .then((res) => {})
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      success($q, "ยกเลิกยุติเรื่องสำเร็จ");
      fetchDetailDisciplinary();
    });
}

function closePopup() {
  modalPopup.value = false;
}

function emitPerson(data: PersonsArray[]) {
  const dataMapId = data.map((item: PersonsArray) => item.id);
  showLoader();
  http
    .put(config.API.disciplinarySuspend(id.value), {
      persons: dataMapId,
    })
    .then(async(res) => {
      modalPopup.value = false
      success($q, "ส่งไปพักราชการสำเร็จ");
      // router.push(`/discipline/investigatefacts`);
      await fetchDetailDisciplinary();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

    if (fetchFunction) {
      await fetchFunction();
    }
  }
);

/** โหลดข้อมูลเมื่อเข้าหน้านี้ */
onMounted(async () => {
  store.tabMenu = "disciplinary";
  await fetchDetailDisciplinary();
});
</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/disciplinary`)"
      />
      <div class="q-ma-none">
        {{
          checkRoutePermisson
            ? "รายละเอียดการสอบสวนความผิดทางวินัย"
            : "แก้ไขการสอบสวนความผิดทางวินัย"
        }}
      </div>
      <q-space />
      <div class="q-gutter-x-sm" v-if="!checkRoutePermisson">
        <q-btn
          v-if="status === 'NEW'"
          label="ส่งไปสรุปผลการพิจารณา"
          color="public"
          @click="sentIssueGate"
          :disable="isSaveInfo"
        />
        <q-btn
          v-if="status === 'NEW'"
          label="ส่งไปพักราชการ"
          color="primary"
          @click="sentIssue"
        />
        <q-btn
          v-if="status === 'NEW'"
          label="ยุติเรื่อง"
          color="red-7"
          @click="endInvestigate"
        />
        <q-btn
          v-if="status === 'STOP'"
          label="ยกเลิกการยุติเรื่อง"
          color="red-7"
          @click="cancelInvestigate"
        />
      </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-color="primary"
        active-class="bg-teal-1"
      >
        <q-tab name="complaints" label="เรื่องร้องเรียน (สำเนา)" />
        <q-tab name="investigatefacts" label="สืบสวนข้อเท็จจริง (สำเนา)" />
        <q-tab name="disciplinary" 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="data"
            @submit:disciplinary="onSubmitDisciplinary"
            :fetchData="fetchDetailDisciplinary"
            v-model:isSaveInfo="isSaveInfo"
          />
        </q-tab-panel>
      </q-tab-panels>
    </q-card>
  </div>

  <PopupSendToNext
    :modal="modalPopup"
    :close="closePopup"
    title="ส่งไปพักราชการ"
    :rows="respondentRows"
    :columns="mainStore.columnsRespondent"
    :visibleColumns="mainStore.visibleColumnsRespondent"
    :checked-val="false"
    @return-person="emitPerson"
  />
</template>

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