<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import Form from "@/modules/11_discipline/components/1_Complaint/Form.vue";
import PopupSendToNext from "@/modules/11_discipline/components/PopupSendToNext.vue";
import { useRouter, useRoute } from "vue-router";
import { useQuasar } from "quasar";
import type { QTableProps } from "quasar";
import type {
  FormData,
  ArrayPerson,
  ArrayFileList,
} from "@/modules/11_discipline/interface/request/complaint";

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

import { useCounterMixin } from "@/stores/mixin";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/main";

const mainStore = useDisciplineMainStore();
const $q = useQuasar();
const mixin = useCounterMixin();

const { dialogConfirm, showLoader, hideLoader, success, messageError } = mixin;
const router = useRouter();
const route = useRoute();
const id = ref<string>(route.params.id as string);

const modalPopup = ref<boolean>(false);

/** ข้อมูล v-model ของฟอร์ม */
const personOj = reactive<ArrayPerson>({
  id: "",
  personId: "",
  idcard: "",
  name: "",
  prefix: "",
  firstName: "",
  lastName: "",
  posNo: "",
  position: "",
  positionLevel: "",
  salary: null,
  organization: "",
});

const fileListOj = reactive<ArrayFileList>({
  id: "",
  pathName: "",
  fileName: "",
});

const data = reactive<FormData>({
  id: "",
  respondentType: "",
  organizationId: "",
  consideredAgency: "",
  title: "",
  description: "",
  dateReceived: null,
  dateConsideration: null,
  offenseDetails: "",
  levelConsideration: "",
  dateNotification: null,
  complaintFrom: "",
  appellant: "",
  documentFile: null,
  status: "",
  persons: [personOj],
  result: "",
  disciplineComplaintDocs: [fileListOj],
});

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "idcard",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "idcard",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ - นามสกุล",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posNo",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionLevel",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "salary",
    align: "left",
    label: "เงินเดือน",
    sortable: true,
    field: "salary",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** หัวข้อที่เเสดงในตาราง */
const visibleColumns = ref<string[]>([
  "no",
  "idcard",
  "name",
  "posNo",
  "position",
  "positionLevel",
  "salary",
  "organization",
]);

/** ดึงข้อมูล */
async function getData() {
  showLoader();
  await http
    .get(config.API.complaintbyId(id.value))
    .then((res) => {
      const dataList = res.data.result;
      data.id = dataList.id;
      data.respondentType = dataList.respondentType;
      data.organizationId = dataList.organizationId;
      data.consideredAgency = dataList.consideredAgency;
      data.title = dataList.title;
      data.description = dataList.description;
      data.dateReceived = dataList.dateReceived;
      data.levelConsideration = dataList.levelConsideration;
      data.dateConsideration = dataList.dateConsideration;
      data.offenseDetails = dataList.offenseDetails;
      data.dateNotification = dataList.dateNotification;
      data.complaintFrom = dataList.complaintFrom;
      data.appellant = dataList.appellant;
      data.status = dataList.status;
      data.persons = dataList.persons;
      data.result = dataList.result;
      data.disciplineComplaintDocs = dataList.disciplineComplaintDocs;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * บันทึกข้อมูลเมื่อแก้ไข
 * @param data ข้อมูลจากฟอร์ม
 */
async function onSubmit(data: any) {
  showLoader();
  http
    .put(config.API.complaintbyId(id.value), {
      id: data.id,
      respondentType: data.respondentType,
      organizationId: data.organizationId,
      consideredAgency: data.consideredAgency,
      title: data.title,
      description: data.description,
      dateReceived: data.dateReceived,
      dateConsideration: data.dateConsideration,
      offenseDetails: data.offenseDetails,
      levelConsideration: data.levelConsideration,
      dateNotification: data.dateNotification,
      complaintFrom: data.complaintFrom,
      appellant: data.appellant,
      documentFile: data.documentFile,
      status: data.status,
      result: data.result,
      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,
      })),
      disciplineComplaintDocs: data.disciplineComplaintDocs.map(
        (file: any) => ({
          id: file.id,
          fileName: file.fileName,
          pathName: file.pathName,
        })
      ),
    })
    .then((res) => {
      getData();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}

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

/** ส่งไปสืบสวน */
function sentConfirmNoPerson() {
  showLoader();
  http
    .put(config.API.complaintApprove(id.value), {
      persons: [],
    })
    .then((res) => {
      router.push(`/discipline/complaints`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ปิด dialog */
function closePopup() {
  modalPopup.value = false;
}

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

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

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

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

/**
 * ดึงข้อมูล จาก component เเล้ว update
 * @param data person data
 */
function sendPersonToNext(data: ArrayPerson[]) {
  const dataMapId = data.map((item: ArrayPerson) => item.id);

  showLoader();
  http
    .put(config.API.complaintApprove(id.value), {
      persons: dataMapId,
    })
    .then((res) => {
      router.push(`/discipline/complaints`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** เรียกใช้งาน ฟังชั่น ตอนเริ่มโหลดหน้า */
onMounted(() => {
  getData();
});
</script>

<template>
  <div class="col-xs-12 col-sm-12 col-md-11">
    <div class="toptitle col-12 row items-end">
      <q-btn
        icon="mdi-arrow-left"
        unelevated
        round
        dense
        flat
        color="primary"
        class="q-mr-sm"
        @click="$router.push(`/discipline/complaints`)"
      />
      <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><Form :on-submit="onSubmit" :data="data" :get-data="getData" /></q-card>
    <PopupSendToNext
      :modal="modalPopup"
      :close="closePopup"
      @return-person="sendPersonToNext"
      :rows="mainStore.rowsAdd"
      :columns="columns"
      :visibleColumns="visibleColumns"
    />
  </div>
</template>
