<script setup lang="ts">
import { ref, reactive, defineProps, watch } from "vue";
import { useAppealComplainStore } from "@/modules/07_appealComplain/store";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import type { MyObjectAppealRef } from "@/modules/07_appealComplain/interface/request/appeal";
import type {
  EditDataList,
  HistoryStatusType,
  FileObType,
} from "@/modules/07_appealComplain/interface/response/mainType";
const $q = useQuasar();

const isReadOnly = ref<boolean>(false);
const printForm = ref<string>("");
const mixin = useCounterMixin();
const { dialogConfirm, modalWarning } = mixin;
const dataStore = useAppealComplainStore();

const historyStatusOb = reactive<HistoryStatusType>({
  status: "",
  createdAt: "",
});

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

const formData = reactive<any>({
  title: "",
  type: "",
  description: "",
  year: new Date().getFullYear().toString(),
  caseType: "",
  caseNumber: "",
  fullname: "",
  profileId: "",
  citizenId: "",
  disciplineComplaint_Appeal_Docs: [fileOb],
  historyStatus: [historyStatusOb],
});

const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  formProfile: {
    type: Object,
    default: null,
  },
  onSubmit: {
    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)) {
    if (formData.files.length === 0) {
      modalWarning($q, "ข้อความแจ้งเตือน", "กรุณาอัปโหลดไฟล์");
    } else {
      onSubmit(formData);
    }
  } else {
    console.log("ไม่ผ่าน ");
    console.log(hasError);
  }
}

watch(props.formProfile, () => {
  if (props.formProfile !== null) {
    formData.fullname = props.formProfile.fullname;
    formData.profileId = props.formProfile.profileId;
    formData.citizenId = props.formProfile.citizenId;
  }
});

watch(props.data, () => {
  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;
  // dataStore.getRow([
  //   {
  //     profileId: props.data.profileId,
  //     fullname: props.data.fullname,
  //     citizenId: props.data.citizenId,
  //   },
  // ]);
});
function filePrint() {
  console.log("print");
}

function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

function downLoadFile(path: string) {
  window.open(path, "_blank");
}
function onSubmit(data: any) {
  dialogConfirm(
    $q,
    async () => {
      props.onSubmit(data);
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}
</script>
<template>
  <div class="row">
    <div class="col-sm-12 col-md-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.historyStatus[0].status === 'NEW'"
                  v-model="printForm"
                  color="blue"
                  label="พิมพ์แบบฟอร์มคำร้อง"
                  @click="filePrint"
                />
              </div>
              <div
                class="q-gutter-sm"
                v-if="formData.historyStatus[0].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" />
                  คำอุทธรณ์/ร้องทุกข์นี้จะยังไม่สมบูรณ์
                  จนกว่าผู้อุทธรณ์/ร้องทุกข์ จะ “Print แบบฟอร์มคำร้อง” จากระบบ
                  พร้อม เอกสารหลักฐานทั้งหมดเป็น Hard Copy <br />
                  แล้วส่งไปรษณีย์ให้ กพค. หรือ
                  นำเอกสารทั้งหมดไปส่งด้วยตนเองที่ชั้น 14 อาคารศรีจุลทรัพย์
                </q-banner>
              </div>
              <div class="row q-gutter-x-sm">
                <div class="col-3">
                  <q-select
                    :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) => !!val || `${'กรุณาเลือกประเภท'}`]"
                    lazy-rules
                    hide-bottom-space
                  />
                </div>
                <div class="col-3">
                  <div class="col-3">
                    <q-input
                      :class="inputEdit(isReadOnly)"
                      :readonly="isReadOnly"
                      ref="titleRef"
                      :rules="[
                        (val) => !!val || 'กรุณากรอกเรื่องอุทธรณ์/ร้องทุกข์',
                      ]"
                      v-model="formData.title"
                      dense
                      outlined
                      label="เรื่องอุทธรณ์/ร้องทุกข์"
                    />
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-12">
                  <q-input
                    :class="inputEdit(isReadOnly)"
                    :readonly="isReadOnly"
                    ref="descriptionRef"
                    :rules="[
                      (val) => !!val || 'กรุณากรอกรายละเอียดเรื่องร้องทุกข์',
                    ]"
                    v-model="formData.description"
                    dense
                    outlined
                    label="รายละเอียดเรื่องร้องทุกข์"
                    type="textarea"
                    rows="5"
                  />
                </div>
              </div>
              <div class="row q-gutter-x-sm">
                <div class="col-3">
                  <datepicker
                    menu-class-name="modalfix"
                    v-model="formData.year"
                    class="col-2"
                    :locale="'th'"
                    autoApply
                    year-picker
                    :enableTimePicker="false"
                    :readonly="isReadOnly"
                  >
                    <template #year="{ year }">{{ year + 543 }}</template>
                    <template #year-overlay-value="{ value }">{{
                      parseInt(value + 543)
                    }}</template>
                    <template #trigger>
                      <q-input
                        :class="inputEdit(isReadOnly)"
                        :readonly="isReadOnly"
                        dense
                        lazy-rules
                        outlined
                        :model-value="Number(formData.year) + 543"
                        :label="`${'ปีงบประมาณ'}`"
                      >
                        <template v-slot:prepend>
                          <q-icon
                            name="event"
                            class="cursor-pointer"
                            style="color: var(--q-primary)"
                          >
                          </q-icon>
                        </template>
                      </q-input>
                    </template>
                  </datepicker>
                </div>

                <div class="col-3">
                  <q-input
                    :class="inputEdit(isReadOnly)"
                    :readonly="isReadOnly"
                    ref="caseTypeRef"
                    v-model="formData.caseType"
                    dense
                    outlined
                    :rules="[(val) => !!val || 'กรุณากรอกประเภทคดี']"
                    lazy-rules
                    label="ประเภทคดี"
                    hide-bottom-space
                  />
                </div>
                <div class="col-3">
                  <q-input
                    :class="inputEdit(isReadOnly)"
                    :readonly="isReadOnly"
                    ref="caseNumberRef"
                    v-model="formData.caseNumber"
                    dense
                    outlined
                    :rules="[(val) => !!val || 'กรุณากรอกเลขที่คดี']"
                    lazy-rules
                    label="เลขที่คดี"
                    hide-bottom-space
                  />
                </div>
              </div>
              <div class="row" v-if="!isReadOnly">
                <!-- multiple
                    use-chips -->
                <div class="col-12">
                  <q-file
                    ref="fileRef"
                    v-model="formData.files"
                    label="อัปโหลดเอกสารหลักฐาน"
                    flat
                    dense
                    outlined
                    hide-bottom-space
                    bg-color="white"
                  />
                </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="primary"
                          @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>
          <div v-if="!isReadOnly">
            <q-separator />
            <div class="row col-12 q-pa-sm">
              <q-space />
              <q-btn
                id="onSubmit"
                type="submit"
                label="บันทึก"
                color="secondary"
                ><q-tooltip>บันทึก</q-tooltip></q-btn
              >
            </div>
          </div>
        </q-card>
      </form>
    </div>
  </div>
</template>
