<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useQuasar } from "quasar";

import { useCounterMixin } from "@/stores/mixin";
import { useAppealComplainStore } from "@/modules/07_appealComplain/store";

import type { MyObjectAppealRef } from "@/modules/07_appealComplain/interface/request/appeal";
import type {
  HistoryStatusType,
  FileObType,
  FormDataType,
} from "@/modules/07_appealComplain/interface/response/mainType";

const $q = useQuasar();
const mixin = useCounterMixin();
const { dialogConfirm } = mixin;
const dataStore = useAppealComplainStore();

const isLoad = defineModel<boolean>("isLoad", { required: true });
const printForm = ref<string>("");
const isReadOnly = ref<boolean>(false);
const historyStatusOb = reactive<HistoryStatusType>({
  status: "",
  createdAt: "",
});

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

const formData = reactive<FormDataType>({
  id: "",
  title: "",
  type: "",
  description: "",
  year: new Date().getFullYear().toString(),
  caseType: "",
  caseNumber: "",
  fullname: "",
  profileId: "",
  citizenId: "",
  oc: "",
  position: "",
  status: "",
  disciplineComplaint_Appeal_Docs: [fileOb],
  historyStatus: [historyStatusOb],
  files: null,
  lastUpdatedAt: null,
});

const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  formProfile: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
  getReport: {
    type: Function,
    default: () => "",
  },
  getData: {
    type: Function,
    default: () => "",
  },
});

/** ตัวแปร validate */
const typeRef = ref<Object | null>(null);
const titleRef = ref<Object | null>(null);
const descriptionRef = ref<Object | null>(null);
const caseTypeRef = ref<Object | null>(null);
const caseNumberRef = ref<Object | null>(null);

const objectAppeal: MyObjectAppealRef = {
  type: typeRef,
  title: titleRef,
  description: descriptionRef,
  caseType: caseTypeRef,
  caseNumber: caseNumberRef,
};

/*** ฟังก์ชั่นสำหรับ validate ฟอร์ม */
function validateForm() {
  const hasError = [];
  for (const key in objectAppeal) {
    if (Object.prototype.hasOwnProperty.call(objectAppeal, key)) {
      const property = objectAppeal[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    onSubmit(formData);
  } else {
  }
}

/**
 * ฟังชั่น class input
 * @param val
 */
function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

/**
 * ดาวห์โหลด เอกสารเพิ่มเติม
 * @param path ลิงค์เอกสาร
 */
function downLoadFile(path: string) {
  window.open(path, "_blank");
}

/**
 * download แบบฟอร์ม file
 * @param fileName ชื่อไฟล์
 */
function filePrintDownload(fileName: string) {
  props.getReport(fileName);
}

/**
 * บันทึก form อุทธรณ์/ร้องทุกข์
 * @param data ข้อมูล
 */
function onSubmit(data: FormDataType) {
  dialogConfirm(
    $q,
    async () => {
      props.onSubmit(data);
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?",
  );
}

watch(
  () => props.formProfile,
  (newValue) => {
    if (newValue !== null) {
      formData.fullname = newValue.fullname;
      formData.profileId = newValue.profileId;
      formData.citizenId = newValue.citizenId;
      formData.oc = newValue.oc;
      formData.position = newValue.position;
    }
  },
  { deep: true },
);

watch(
  () => props.data,
  (newValue) => {
    if (newValue !== null) {
      isReadOnly.value = true;
      formData.id = props.data.id;
      formData.title = props.data.title;
      formData.description = props.data.description;
      formData.status = props.data.status;
      formData.type = props.data.type;
      formData.year = props.data.year;
      formData.caseType = props.data.caseType;
      formData.caseNumber = props.data.caseNumber;
      formData.fullname = props.data.fullname;
      formData.citizenId = props.data.citizenId;
      formData.profileId = props.data.profileId;
      formData.lastUpdatedAt = props.data.lastUpdatedAt;
      formData.disciplineComplaint_Appeal_Docs =
        props.data.disciplineComplaint_Appeal_Docs;
      formData.historyStatus = props.data.historyStatus;
    }
  },
  { deep: true },
);
</script>

<template>
  <div class="row">
    <div class="col-sm-12 col-md-12 col-xs-12">
      <form @submit.prevent="validateForm">
        <q-card bordered>
          <div class="q-pa-md">
            <div class="q-gutter-y-sm">
              <div class="row">
                <q-btn
                  v-if="formData.status === 'NEW'"
                  v-model="printForm"
                  color="blue"
                  label="พิมพ์แบบฟอร์มคำร้อง"
                  @click="filePrintDownload('แบบฟอร์มคำร้อง')"
                />
              </div>
              <div class="q-gutter-sm q-mb-sm" v-if="formData.status === 'NEW'">
                <q-banner
                  inline-actions
                  bordered
                  class="bg-red-1 text-red border-red q-pa-md"
                >
                  <q-icon name="mdi-information-outline" size="20px" />
                  คำอุทธรณ์/ร้องทุกข์นี้จะยังไม่สมบูรณ์
                  จนกว่าผู้อุทธรณ์/ร้องทุกข์จะ “พิมพ์แบบฟอร์มคำร้อง” จากระบบ
                  พร้อมเอกสารหลักฐานทั้งหมดนำส่งไปรษณีย์ให้ กพค.
                  หรือนำเอกสารทั้งหมดไปส่งด้วยตนเองที่ชั้น 14 อาคารศรีจุลทรัพย์
                </q-banner>
              </div>
              <div
                class="q-gutter-sm q-mb-sm"
                v-else-if="isReadOnly || formData.status === 'NEW'"
              >
                <q-banner
                  inline-actions
                  bordered
                  class="bg-blue-1 text-blue border-blue q-pa-md"
                >
                  <div class="row items-center q-gutter-x-sm">
                    <q-icon name="mdi-information-outline" size="20px" />
                    <div>
                      {{ dataStore.statusTothai(formData.status) }}
                    </div>
                  </div>
                </q-banner>
              </div>
              <div class="row q-col-gutter-sm">
                <div class="col-xs-12 col-md-3">
                  <q-select
                    v-if="!isLoad"
                    :class="inputEdit(isReadOnly)"
                    :readonly="isReadOnly"
                    ref="typeRef"
                    v-model="formData.type"
                    label="ประเภท"
                    dense
                    outlined
                    emit-value
                    map-options
                    option-label="name"
                    option-value="id"
                    :options="dataStore.typeOptions"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกประเภท'}`]"
                    lazy-rules
                    hide-bottom-space
                  />
                  <q-skeleton v-else type="QInput" height="40px" />
                </div>
                <div class="col-xs-12 col-md-3">
                  <q-input
                    v-if="!isLoad"
                    :class="inputEdit(isReadOnly)"
                    :readonly="isReadOnly"
                    ref="titleRef"
                    :rules="[
                      (val:string) => !!val || 'กรุณากรอกเรื่องอุทธรณ์/ร้องทุกข์',
                    ]"
                    v-model="formData.title"
                    dense
                    outlined
                    label="เรื่องอุทธรณ์/ร้องทุกข์"
                    hide-bottom-space
                  />
                  <q-skeleton v-else type="QInput" height="40px" />
                </div>
              </div>
              <div class="row">
                <div class="col-12">
                  <q-input
                    v-if="!isLoad"
                    :class="inputEdit(isReadOnly)"
                    :readonly="isReadOnly"
                    ref="descriptionRef"
                    :rules="[
                      (val:string) => !!val || 'กรุณากรอกรายละเอียดอุทธรณ์/ร้องทุกข์',
                    ]"
                    v-model="formData.description"
                    dense
                    outlined
                    label="รายละเอียดอุทธรณ์/ร้องทุกข์"
                    type="textarea"
                    rows="5"
                    hide-bottom-space
                  />
                  <q-skeleton v-else type="QInput" height="120px" />
                </div>
              </div>
              <div class="row" v-if="!isReadOnly">
                <div class="col-12">
                  <q-file
                    v-if="!isLoad"
                    ref="fileRef"
                    v-model="formData.files"
                    label="อัปโหลดเอกสารหลักฐาน"
                    flat
                    dense
                    outlined
                    hide-bottom-space
                    bg-color="white"
                  />
                  <q-skeleton v-else type="QInput" height="40px" />
                </div>
              </div>
              <q-card bordered class="col-12 row" v-if="isReadOnly">
                <div
                  class="bg-grey-1 q-pa-sm col-12 row items-center text-primary"
                >
                  <div class="q-pl-sm text-weight-bold text-dark">
                    เอกสารเพิ่มเติม
                  </div>
                </div>
                <q-card
                  flat
                  class="full-width"
                  v-if="formData.disciplineComplaint_Appeal_Docs.length !== 0"
                >
                  <q-list separator>
                    <q-item
                      v-for="file in formData.disciplineComplaint_Appeal_Docs"
                      :key="file.id"
                      class="q-my-xs"
                    >
                      <q-item-section>
                        <q-item-label class="full-width ellipsis">
                          {{ file.fileName }}
                        </q-item-label>
                      </q-item-section>
                      <q-item-section side>
                        <q-btn
                          unelevated
                          round
                          dense
                          flat
                          icon="mdi-download"
                          outline
                          color="blue"
                          @click="downLoadFile(file.pathName)"
                        >
                          <q-tooltip>ดาวห์โหลดเอกสาร</q-tooltip>
                        </q-btn>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-card>
                <div class="col-12 q-pa-sm" v-else>
                  <q-card class="q-pa-md" bordered> ไม่มีรายการเอกสาร </q-card>
                </div>
              </q-card>
            </div>
          </div>
          <q-separator v-if="!isReadOnly && !isLoad" />
          <q-card-actions
            align="right"
            class="bg-white text-teal"
            v-if="!isReadOnly && !isLoad"
          >
            <q-btn id="onSubmit" type="submit" label="บันทึก" color="secondary"
              ><q-tooltip>บันทึก</q-tooltip></q-btn
            >
          </q-card-actions>
        </q-card>
      </form>
    </div>
  </div>
</template>
