<script setup lang="ts">
import { onMounted, reactive, ref, watch } 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 } = 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>({
  commandNo: "",
  commandYear: null,
  detailHeader: "",
  detailBody: "",
  detailFooter: "",
  issue: null,
  commandAffectDate: null, //วันที่ลงนาม
  commandExcecuteDate: null, //วันที่คำสั่งมีผล
  isBangkok: false,
});
const modalPreview = ref<boolean>(false); //แสดงตัวอย่าง

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

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 */
onMounted(() => {
  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;
});

/**
 * ฟังก์ชันที่ต้องการนำฟังก์ชันออกไปใช้ใน Components แม่
 */
defineExpose({
  onSubmit,
});
</script>

<template>
  <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"
        />
        <!-- <q-card bordered flat>
          <div class="bg-grey-2 row q-py-sm q-px-md text-bold">
            เนื้อหาคำสั่งส่วนต้น
          </div>
          <q-separator />
          <q-card-section>
            <q-field
              class="q_field_p_none"
              ref="fieldRef"
              v-model="formData.detailHeader"
              borderless
              hide-bottom-space
            >
              <template #control>
                <q-editor
                  @update:model-value="onCheckChangeData()"
                  :readonly="store.readonly"
                  class="full-width"
                  v-model="formData.detailHeader"
                  min-height="5rem"
                  :toolbar="[
                    ['left', 'center', 'right', 'justify'],
                    [
                      'bold',
                      'italic',
                      'strike',
                      'underline',
                      'subscript',
                      'superscript',
                    ],
                    ['unordered', 'ordered'],
                  ]"
                />
              </template>
            </q-field>
          </q-card-section>
        </q-card> -->
      </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 || `${'กรุณากรอกเนื้อหาคำสั่งหลัก'}`]"
        />
        <!-- <q-card bordered flat>
          <div class="bg-grey-2 row q-py-sm q-px-md text-bold">
            เนื้อหาคำสั่งส่วนกลาง
          </div>
          <q-separator />
          <q-card-section>
            <q-field
              class="q_field_p_none"
              ref="fieldRef"
              v-model="formData.detailBody"
              borderless
              hide-bottom-space
            >
              <template #control>
                <q-editor
                  @update:model-value="onCheckChangeData()"
                  :readonly="store.readonly"
                  class="full-width"
                  v-model="formData.detailBody"
                  min-height="5rem"
                  :toolbar="[
                    ['left', 'center', 'right', 'justify'],
                    [
                      'bold',
                      'italic',
                      'strike',
                      'underline',
                      'subscript',
                      'superscript',
                    ],
                    ['unordered', 'ordered'],
                  ]"
                />
              </template>
            </q-field>
          </q-card-section>
        </q-card> -->
      </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"
        />
        <!-- <q-card bordered flat>
          <div class="bg-grey-2 row q-py-sm q-px-md text-bold">
            เนื้อหาคำสั่งส่วนท้าย
          </div>
          <q-separator />
          <q-card-section>
            <q-field
              class="q_field_p_none"
              ref="fieldRef"
              v-model="formData.detailFooter"
              borderless
              hide-bottom-space
            >
              <template #control>
                <q-editor
                  @update:model-value="onCheckChangeData()"
                  :readonly="store.readonly"
                  class="full-width"
                  v-model="formData.detailFooter"
                  min-height="5rem"
                  :toolbar="[
                    ['left', 'center', 'right', 'justify'],
                    [
                      'bold',
                      'italic',
                      'strike',
                      'underline',
                      'subscript',
                      'superscript',
                    ],
                    ['unordered', 'ordered'],
                  ]"
                />
              </template>
            </q-field>
          </q-card-section>
        </q-card> -->
      </div>

      <div class="col-12">
        <q-checkbox
          keep-color
          color="primary"
          dense
          v-model="formData.isBangkok"
          label="นี่คือคำสั่งกรุงเทพมหานคร"
        />
      </div>
    </div>
  </q-card-section>

  <q-separator />

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

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