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

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

import type { QTableProps } from "quasar";
import type {
  FormData,
  ArrayPerson,
  ArrayFileList,
} from "@/modules/11_discipline/interface/request/Complaint";

import Form from "@/modules/11_discipline/components/1_Complaint/Form.vue";
import PopupSendToNext from "@/modules/11_discipline/components/PopupSendToNext.vue";

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 checkRoutePermisson = ref<boolean>(
  route.name == "disciplineComplaintsDetail"
);

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.complaintbyGetId(id.value, mainStore.pathComplaints(route.name as string))
    )
    .then((res) => {
      const dataList = res.data.result;
      data.id = dataList.id;
      data.respondentType = dataList.respondentType;
      data.organizationId = dataList.organizationId;
      data.organization = dataList.organization;
      data.consideredAgency = dataList.consideredAgency;
      data.consideredAgencyId = dataList.consideredAgencyId;
      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;
      data.activeId = dataList.activeId;

      mainStore.fetchDataRowsSend(dataList.persons);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * บันทึกข้อมูลเมื่อแก้ไข
 * @param data ข้อมูลจากฟอร์ม
 */
async function onSubmit(data: any) {
  showLoader();

  http
    .put(config.API.complaintbyId(id.value), data)
    .then((res) => {
      getData();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}

/** ยืนยัน มีมูลส่งไปสืบสวน */
function sentInvestigate() {
  if (mainStore.rowsSend.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">
        {{
          checkRoutePermisson
            ? "รายละเอียดเรื่องร้องเรียน"
            : "แก้ไขเรื่องร้องเรียน"
        }}
      </div>
      <q-space />
      <div class="q-gutter-x-sm" v-if="!checkRoutePermisson">
        <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.rowsSend"
      :columns="columns"
      :visible-columns="visibleColumns"
    />
  </div>
</template>
