<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 { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useInvestigateFactStore } from "@/modules/11_discipline/store/InvestigateFactStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store";
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 type { QTableProps } from "quasar";

import config from "@/app.config";
import http from "@/plugins/http";

const mainStore = useDisciplineMainStore();

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

/** ข้อมูล 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: [],
});

/** ข้อมูล 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.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;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * บันทึกข้อมูลที่เเก้ไข
 * @param id ระบุ บุคคล
 */
async function onSubmit(data: any) {
  // put
  console.log("edit", data);
  showLoader();
  http
    .put(config.API.investigateById(id.value), data)
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      // router.push(`/discipline/complaints`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      getData();
    });
  // router.push(`/discipline/investigatefacts`);
}

const modalPopup = ref<boolean>(false);
/** ยืนยัน ส่งไปสอบสวน */
function sentInvestigate() {
  modalPopup.value = true;
  // dialogConfirm(
  //   $q,
  //   () => confirmSentInvestigate(),
  //   "ยืนยันส่งไปสอบสวน",
  //   "ต้องการยืนยันส่งไปสอบสวนใช่หรือไม่?"
  // );
}

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

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

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

/** ฟังชั่น ส่งไปสอบสวน*/
function confirmSentInvestigate() {
  console.log("sent");
}

/** ฟังชั่น ยุติเรื่อง*/
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();
    });
}

function emitPerson(data: FormData[]) {
  const dataMapId = data.map((item: FormData) => item.id);
  console.log(dataMapId);
  showLoader();
  http
    .put(config.API.investigateApprove(id.value), {
      persons: dataMapId,
    })
    .then((res) => {
      // router.push(`/discipline/investigatefacts`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
      getData();
    });
}

/** โหลดข้อมูลเมื่อเข้าหน้านี้ */
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 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"
      :columns="mainStore.columnsDirector"
      :visibleColumns="mainStore.visibleColumnsDirector"
      @return-person="emitPerson"
    />
  </div>
</template>
<style scoped>
.q-tab-panel {
  padding: 0;
  background-color: #f0f3f3;
}
</style>
