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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useCommandDetail } from "@/modules/18_command/store/DetailStore";

import type { FormDataDetail } from "@/modules/18_command/interface/request/Main";

import DialogPerview from "@/modules/18_command/components/Step/Dialog1_Perview.vue";

const $q = useQuasar();
const route = useRoute();
const store = useCommandDetail();
const {
  showLoader,
  hideLoader,
  messageError,
  date2Thai,
  success,
  dialogConfirm,
} = useCounterMixin();

/**
 * props
 */
const isChangeData = defineModel<boolean>("isChangeData", { required: true });
const props = defineProps({
  onCheckChangeData: { type: Function, required: true },
  fetchDataCommandList: { type: Function, required: true },
  formCommandList: { type: Object, required: true },
});

const commandId = ref<string>(route.params.id.toString()); //ID คำสั่ง
// ฟอร์มข้อมูล
let formData = reactive<FormDataDetail>({
  issue: null, //คำสั่งเรื่อง
  commandNo: "", //คำสั่งเลขที่
  commandYear: null, //พ.ศ.
  detailHeader: "", //เนื้อหาคำสั่งขึ้นต้น
  detailBody: "", //เนื้อหาคำสั่งหลัก
  detailFooter: "", //เนื้อหาคำสั่งลงท้าย
  commandAffectDate: null, //วันที่ลงนาม
  commandExcecuteDate: null, //วันที่คำสั่งมีผล
  isBangkok: null, //คำสั่งสำนักปลัดกรุงเทพมหานคร
});
const modalPreview = ref<boolean>(false); //แสดงตัวอย่าง
const isIdofficer = ref<boolean>(false); //เช็ค สกจ.

/** ฟังก์ชันเช็ค สกจ.*/
async function fetchCheckIdofficer() {
  await http
    .get(config.API.checkIdofficer)
    .then((res) => {
      isIdofficer.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * ฟังก์ชันบันทึกข้อมูลรายละเอียดคำสั่ง
 * และกำหนด isChangeData เป็น false
 */
async function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .put(config.API.commandAction(commandId.value, "tab1"), formData)
      .then(async () => {
        await props.fetchDataCommandList();
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
        isChangeData.value = false;
      });
  });
}

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 */
onMounted(async () => {
  await fetchCheckIdofficer();
  formData.commandNo = props.formCommandList.commandNo;
  formData.commandYear = props.formCommandList.commandYear;
  formData.detailHeader = props.formCommandList.detailHeader;
  formData.detailBody = props.formCommandList.detailBody;
  formData.detailFooter = props.formCommandList.detailFooter;
  formData.issue = props.formCommandList.issue;
  formData.commandAffectDate = props.formCommandList.commandAffectDate;
  formData.commandExcecuteDate = props.formCommandList.commandExcecuteDate;
  formData.isBangkok = !isIdofficer.value
    ? null
    : props.formCommandList.isBangkok;
});
</script>

<template>
  <q-form greedy @submit.prevent @validation-success="onSubmit">
    <q-card-section>
      <div class="row q-col-gutter-sm">
        <div class="col-12">
          <q-input
            :class="store.classInput(!store.readonly)"
            :readonly="store.readonly"
            outlined
            dense
            v-model="formData.issue"
            hide-bottom-space
            :label="`${'คำสั่งเรื่อง'}`"
            @update:model-value="onCheckChangeData()"
          />
        </div>

        <div class="col-4 row">
          <div class="col-6">
            <q-input
              :class="store.classInput(!store.readonly)"
              :readonly="store.readonly"
              outlined
              dense
              v-model="formData.commandNo"
              hide-bottom-space
              :label="`${'คำสั่งเลขที่'}`"
              @update:model-value="onCheckChangeData()"
            />
          </div>
          <label class="col-1 flex justify-center items-center text-bold">
            /
          </label>
          <div class="col-5">
            <datepicker
              menu-class-name="modalfix"
              v-model="formData.commandYear"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
              :class="store.classInput(!store.readonly)"
              :readonly="store.readonly"
              @update:model-value="onCheckChangeData()"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  dense
                  outlined
                  hide-bottom-space
                  :class="store.classInput(!store.readonly)"
                  :readonly="store.readonly"
                  :model-value="
                    formData.commandYear == null
                      ? null
                      : formData.commandYear + 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>

        <div class="col-4">
          <datepicker
            clearable
            menu-class-name="modalfix"
            v-model="formData.commandAffectDate"
            :locale="'th'"
            autoApply
            :enableTimePicker="false"
            :class="store.classInput(!store.readonly)"
            :readonly="store.readonly"
            @update:model-value="onCheckChangeData()"
          >
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input
                clearable
                dense
                outlined
                hide-bottom-space
                :class="store.classInput(!store.readonly)"
                :readonly="store.readonly"
                :model-value="
                  formData.commandAffectDate == null
                    ? null
                    : date2Thai(formData.commandAffectDate)
                "
                :label="`${'วันที่ลงนาม'}`"
                @clear="() => (formData.commandAffectDate = null)"
              >
                <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-4">
          <datepicker
            clearable
            menu-class-name="modalfix"
            v-model="formData.commandExcecuteDate"
            :locale="'th'"
            autoApply
            :enableTimePicker="false"
            :class="store.classInput(!store.readonly)"
            :readonly="store.readonly"
            @update:model-value="onCheckChangeData()"
          >
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input
                clearable
                dense
                outlined
                hide-bottom-space
                :class="store.classInput(!store.readonly)"
                :readonly="store.readonly"
                :model-value="
                  formData.commandExcecuteDate == null
                    ? null
                    : date2Thai(formData.commandExcecuteDate)
                "
                :label="`${'วันที่คำสั่งมีผล'}`"
                @clear="() => (formData.commandExcecuteDate = null)"
              >
                <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-12">
          <q-input
            :class="store.classInput(!store.readonly)"
            :readonly="store.readonly"
            outlined
            dense
            v-model="formData.detailHeader"
            hide-bottom-space
            :label="`${'เนื้อหาคำสั่งขึ้นต้น (optional)'}`"
            @update:model-value="onCheckChangeData()"
            type="textarea"
          />
        </div>

        <!-- เนื้อหาคำสั่งส่วนกลาง -->
        <div class="col-12">
          <q-input
            :class="store.classInput(!store.readonly)"
            :readonly="store.readonly"
            outlined
            dense
            v-model="formData.detailBody"
            hide-bottom-space
            :label="`${'เนื้อหาคำสั่งหลัก'}`"
            @update:model-value="onCheckChangeData()"
            type="textarea"
            :rules="[(val: string) => !!val || `${'กรุณากรอกเนื้อหาคำสั่งหลัก'}`]"
            lazy-rules
          />
        </div>

        <!-- เนื้อหาคำสั่งส่วนท้าย -->
        <div class="col-12">
          <q-input
            :class="store.classInput(!store.readonly)"
            :readonly="store.readonly"
            outlined
            dense
            v-model="formData.detailFooter"
            hide-bottom-space
            :label="`${'เนื้อหาคำสั่งลงท้าย (optional)'}`"
            @update:model-value="onCheckChangeData()"
            type="textarea"
          />
        </div>

        <div class="col-12 q-gutter-sm" v-if="isIdofficer">
          <q-radio
            :disable="store.readonly"
            keep-color
            color="primary"
            dense
            v-model="formData.isBangkok"
            label="คำสั่งสำนักปลัดกรุงเทพมหานคร"
            val="OFFICE"
          />

          <q-radio
            :disable="store.readonly"
            keep-color
            color="primary"
            dense
            v-model="formData.isBangkok"
            label="คำสั่งกรุงเทพมหานคร"
            val="BANGKOK"
          />
        </div>
      </div>
    </q-card-section>

    <q-separator />

    <q-card-actions align="right" v-if="!store.readonly">
      <q-btn label="บันทึก" color="public" type="submit" />
    </q-card-actions>
  </q-form>

  <DialogPerview
    v-model:modal="modalPreview"
    v-model:data-template-detail="formData"
  />
</template>
