<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import FormComplaints from "@/modules/11_discipline/components/1_Complaint/Form.vue"; //เรื่องร้องเรียน
import FormInvestigatefacts from "@/modules/11_discipline/components/2_InvestigateFacts/Form.vue"; //สืบสวนข้อเท็จจริง
import { useRouter, useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useInvestigateFactStore } from "@/modules/11_discipline/store/InvestigateFactStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/main";
import { useQuasar } from "quasar";
import PopupSendToNext from "@/modules/11_discipline/components/PopupSendToNext.vue";
import type { FormData } from "@/modules/11_discipline/interface/request/investigateFact";
import type {
  FormData as FormDataComplaint,
  ArrayPerson,
  ArrayFileList,
} from "@/modules/11_discipline/interface/request/complaint";

import config from "@/app.config";
import http from "@/plugins/http";
import type { ArrayPersonAdd } from "../../interface/response/investigate";

const mainStore = useDisciplineMainStore();

const $q = useQuasar();
const mixin = useCounterMixin();
const store = useInvestigateFactStore();
const { dialogConfirm, showLoader, success, hideLoader, messageError } = mixin;
const route = useRoute();
const router = useRouter();
const id = ref<string>(route.params.id as string);
const modalPopup = ref<boolean>(false);

/** ข้อมูล v-model ของฟอร์มสืบสวน */
const data = reactive<FormData>({
  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: [],
  isDisciplinary: false,
  isAncestorDNA: false,
});

/** ข้อมูล v-model ของฟอร์มเรื่องร้องเรียน */
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],
});

async function getDataComplaint() {
  showLoader();
  await http
    .get(config.API.complaintbyId(data.idComplaint))
    .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((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function getData() {
  showLoader();
  http
    .get(config.API.investigateById(id.value))
    .then((res) => {
      const dataList = res.data.result;
      data.id = dataList.id;
      data.idComplaint = dataList.idComplaint;
      data.respondentType = dataList.respondentType;
      data.organizationId = dataList.organizationId;
      data.persons = dataList.persons;
      data.investigationDetail = dataList.investigationDetail;
      data.investigationDetailOther = dataList.investigationDetailOther;
      data.investigationDateStart = dataList.investigationDateStart;
      data.investigationDateEnd = dataList.investigationDateEnd;
      data.investigationDescription = dataList.investigationDescription;
      data.investigationCauseText = dataList.investigationCauseText;
      data.status = dataList.status;
      data.result = dataList.result;
      data.directors = dataList.director;
      data.disciplineInvestigateDocs = dataList.disciplineInvestigateDocs;
      data.disciplineInvestigateRelevantDocs =
        dataList.disciplineInvestigateRelevantDocs;
      data.investigationStatusResult = dataList.investigationStatusResult;
      data.investigationExtendStatus = dataList.investigationExtendStatus;
      data.investigationDaysExtend = dataList.investigationDaysExtend;
      data.isDisciplinary = dataList.isDisciplinary;
      data.isAncestorDNA = dataList.isAncestorDNA;
      data.investigationExtendHistory =
        dataList.investigationExtendHistory ?? [];
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * บันทึกข้อมูลที่เเก้ไข
 * @param id ระบุ บุคคล
 */
async function onSubmit(data: any) {
  // put
  showLoader();
  http
    .put(config.API.investigateById(id.value), {
      id: data.id,
      idComplaint: data.idComplaint,
      complaint: data.complaint,
      complaintdetail: data.complaintdetail,
      investigationDescription: data.investigationDescription,
      fault: data.fault,
      investigationDetailOther: data.investigationDetailOther,
      evidenceFiles: data.evidenceFiles,
      fileComplaint: data.fileComplaint,
      investigationExtendStatus: data.investigationExtendStatus,
      investigationDateStart: data.investigationDateStart,
      investigationDateEnd: data.investigationDateEnd,
      investigationDetail: data.investigationDetail,
      investigationDaysExtend: data.investigationDaysExtend,
      investigationStatusResult: data.investigationStatusResult,
      investigationCauseText: data.investigationCauseText,
      complaintStatus: data.complaintStatus,
      result: data.result,
      directors: data.directors,
      disciplineInvestigateDocs: data.disciplineInvestigateDocs,
      disciplineInvestigateRelevantDocs: data.disciplineInvestigateRelevantDocs,
      status: data.status,
      documentFile: data.documentFile,
      respondentType: data.respondentType,
      organizationId: data.organizationId,
      persons: data.persons.map((item: any) => ({
        personId: item.personId,
        idcard: item.idcard,
        prefix: item.prefix,
        firstName: item.firstName,
        lastName: item.lastName,
        name: item.name,
        posNo: item.posNo === "-" ? null : item.posNo,
        position: item.position,
        positionLevel: item.positionLevel,
        salary: item.salary === "-" ? null : item.salary,
        organization: item.organization,
        phone: item.phone === "-" ? null : item.phone,
        email: item.email,
      })),
      investigationExtendHistory: data.investigationExtendHistory,
      isDisciplinary: data.isDisciplinary,
    })
    .then((res) => {
      getData();
      success($q, "บันทึกข้อมูลสำเร็จ");
      // router.push(`/discipline/complaints`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
  // router.push(`/discipline/investigatefacts`);
}

/** ยืนยัน ส่งไปสอบสวน */
function sentInvestigate() {
  if (mainStore.rowsAdd.length > 0) {
    modalPopup.value = true;
  } else {
    dialogConfirm(
      $q,
      () => sentConfirmNoPerson(),
      "ยืนยันส่งไปสอบสวน",
      "ต้องการยืนยันส่งไปสอบสวนใช่หรือไม่?"
    );
  }
}

function sentConfirmNoPerson() {
  showLoader();
  http
    .put(config.API.investigateApprove(id.value), {
      persons: [],
    })
    .then((res) => {})
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
      getData();
      router.push(`/discipline/investigatefacts`);
    });
}

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

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

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

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

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

function emitPerson(data: FormData[]) {
  const dataMapId = data.map((item: FormData) => item.id);
  showLoader();
  http
    .put(config.API.investigateApprove(id.value), {
      persons: dataMapId,
    })

    .then((res) => {
      router.push(`/discipline/investigatefacts`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** โหลดข้อมูลเมื่อเข้าหน้านี้ */
onMounted(() => {
  getData();
});

watch(
  () => store.tabMenu,
  () => {
    if (store.tabMenu == "complaints") {
      getDataComplaint();
    } else {
      getData();
    }
  }
);
</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/investigatefacts`)"
      />
      <div class="q-ma-none">แก้ไขรายการสืบสวนข้อเท็จจริง</div>
      <q-space />

      <div class="q-gutter-x-sm">
        <q-btn
          v-if="data.status === 'NEW'"
          label="ส่งไปสอบสวน"
          color="public"
          @click="sentInvestigate"
        />
        <q-btn
          v-if="data.status === 'NEW'"
          label="ยุติเรื่อง"
          color="red-7"
          @click="endInvestigate"
        />
        <q-btn
          v-if="data.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-class="text-primary"
      >
        <q-tab name="complaints" label="เรื่องร้องเรียน (สำเนา)" />
        <q-tab name="investigatefacts" label="สืบสวนข้อเท็จจริง" />
      </q-tabs>
      <q-separator />
      <q-tab-panels v-model="store.tabMenu" animated>
        <q-tab-panel name="complaints">
          <FormComplaints :data="dataComplaints" />
        </q-tab-panel>
        <q-tab-panel name="investigatefacts">
          <FormInvestigatefacts
            :on-submit="onSubmit"
            :data="data"
            :get-data="getData"
          />
        </q-tab-panel>
      </q-tab-panels>
    </q-card>

    <PopupSendToNext
      :modal="modalPopup"
      :close="closePopup"
      title="ส่งไปสอบสวน"
      :rows="mainStore.rowsAdd.filter((item: ArrayPersonAdd)=> item.isSend == 'NEW')"
      :columns="mainStore.columnsDirector"
      :visibleColumns="mainStore.visibleColumnsDirector"
      @return-person="emitPerson"
    />
  </div>
</template>
<style scoped>
.q-tab-panel {
  padding: 0;
  background-color: #f0f3f3;
}
</style>
