<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 config from "@/app.config";
import http from "@/plugins/http";

import type {
  FormData,
  ArrayPerson,
  ArrayFileList,
} from "@/modules/11_discipline/interface/request/complaint";
import { useCounterMixin } from "@/stores/mixin";
import { useComplainstDataStore } from "@/modules/11_discipline/store/ComplaintsStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store";

const complainstStore = useComplainstDataStore();
const mainStore = useDisciplineMainStore();
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogConfirm,
  showLoader,
  hideLoader,
  success,
  messageError,
  dialogMessageNotify,
} = 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: "positionNo",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: true,
    field: "positionNo",
    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",
  "positionNo",
  "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();
    });
}
/** ฟังชั่น แก้ไข */
async function onSubmit(data: any) {
  showLoader();
  http
    .put(config.API.complaintbyId(id.value), data)
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
  // router.push(`/discipline/complaints`);
}

/** ยืนยัน มีมูลส่งไปสืบสวน */
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();
    });
}

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();
    });
}

/**
 * ดึงข้อมูล จาก 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(() => {
  // fetchData();
  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>

    <Form :on-submit="onSubmit" :data="data" :get-data="getData" />
    <PopupSendToNext
      :modal="modalPopup"
      :close="closePopup"
      @return-person="sendPersonToNext"
      :rows="mainStore.rowsAdd"
      :columns="columns"
      :visibleColumns="visibleColumns"
    />
  </div>
</template>
