<script setup lang="ts">
import { onMounted, reactive, ref } 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: "profileType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: false,
    field: "profileType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return `${mainStore.convertType(row.profileType)}`;
    },
  },
  {
    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: "posLevelName",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "salary",
    align: "left",
    label: "เงินเดือน",
    sortable: true,
    field: "salary",
    format(val, row) {
      return val.toLocaleString();
    },
    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",
  "profileType",
  "idcard",
  "name",
  "posNo",
  "position",
  "posLevelName",
  "salary",
  "organization",
]);

/** ดึงข้อมูล */
async function getData() {
  showLoader();
  await http
    .get(
      config.API.complaintbyGetId(
        id.value,
        mainStore.pathComplaints(route.name as string)
      )
    )
    .then(async (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;
      await 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(async () => {
      await getData();
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ยืนยัน มีมูลส่งไปสืบสวน */
function sentInvestigate() {
  if (mainStore.rowsSend.length > 0) {
    modalPopup.value = true;
  } else {
    dialogConfirm(
      $q,
      () => {
        showLoader();
        http
          .put(config.API.complaintApprove(id.value), {
            persons: [],
          })
          .then(() => {
            router.push(`/discipline/complaints`);
          })
          .catch((e) => {
            messageError($q, e);
          })
          .finally(() => {
            hideLoader();
          });
      },
      "ยืนยันส่งไปสืบสวน",
      "ต้องการยืนยันยืนยันส่งไปสืบสวนใช่หรือไม่?"
    );
  }
}

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

/** ยืนยัน ยุติเรื่อง */
function endInvestigate() {
  dialogConfirm(
    $q,
    () => {
      showLoader();
      http
        .get(config.API.complaintReject(id.value))
        .then(async () => {
          await getData();
          success($q, "ยุติเรื่องสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          hideLoader();
        });
    },
    "ยืนยันยุติเรื่อง",
    "ต้องการยืนยันยุติเรื่องใช่หรือไม่?"
  );
}

/** ยืนยัน ยกเลิกการยุติเรื่อง */
function cancelInvestigate() {
  dialogConfirm(
    $q,
    () => {
      showLoader();
      http
        .get(config.API.complaintResume(id.value))
        .then(async () => {
          await getData();
          success($q, "ยกเลิกยุติเรื่องสำเร็จ");
        })
        .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(() => {
      router.push(`/discipline/complaints`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** เรียกใช้งาน ฟังชั่น ตอนเริ่มโหลดหน้า */
onMounted(async () => {
  await 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>
