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

import http from "@/plugins/http";
import config from "@/app.config";
import { useLeaveStore } from "@/modules/05_leave/store";
import { useCounterMixin } from "@/stores/mixin";

import FormPart2 from "@/modules/05_leave/components/FormLeave/Form.vue";
import SickForm from "@/modules/05_leave/components/FormLeave/01_SickForm.vue";
import FormBirth from "@/modules/05_leave/components/FormLeave/03_Birth.vue";
import HelpWifeBirthForm from "@/modules/05_leave/components/FormLeave/04_HelpWifeBirthForm.vue";
import VacationForm from "@/modules/05_leave/components/FormLeave/05_VacationForm.vue";
import OrdinationForm from "@/modules/05_leave/components/FormLeave/06_OrdinationForm.vue";
import HajjForm from "@/modules/05_leave/components/FormLeave/07_HajjForm.vue";
import MilitaryForm from "@/modules/05_leave/components/FormLeave/08_MilitaryForm.vue";
import StudyForm from "@/modules/05_leave/components/FormLeave/09_StudyForm.vue";
import TrainForm from "@/modules/05_leave/components/FormLeave/10_TrainForm.vue";
import WorkInternationalForm from "@/modules/05_leave/components/FormLeave/11_WorkInternationalForm.vue";
import FollowSpouseForm from "@/modules/05_leave/components/FormLeave/12_FollowSpouseForm.vue";
import RehabilitationForm from "@/modules/05_leave/components/FormLeave/13_RehabilitationForm.vue";

const $q = useQuasar();
const router = useRouter();
const myform = ref<QForm | null>(null);
const dataStore = useLeaveStore();
const mixin = useCounterMixin();
const { fetchLeaveType } = dataStore;
const {
  dialogConfirm,
  success,
  messageError,
  showLoader,
  hideLoader,
  convertDateToAPI,
  dialogMessageNotify,
} = mixin;

const model = ref<string>("");
const modelSpecific = ref<string>("");
const option = ref<any[]>(dataStore.options);
/**
 * ดึงค่าประเภทการลาจาก Api
 */
async function fectOptionType() {
  await http
    .get(config.API.leaveType())
    .then(async (res) => {
      const data = res.data.result;
      await fetchLeaveType(data);
    })
    .catch((err) => {
      messageError($q, err);
    });
}

function onSubmit(postData: FormData, isLeave: boolean = true) {
  if (isLeave) {
    if (dataStore.commanderPosition !== "" && dataStore.dear !== "") {
      dialogConfirm($q, async () => {
        showLoader();
        if (model.value === "LV-006" || model.value === "LV-008") {
          postData.append("leaveSubTypeName", modelSpecific.value);
        }
        if (postData.get("leaveEndDate") === postData.get("leaveStartDate")) {
          postData.set("leaveRangeEnd", postData.get("leaveRange") as string);
        }
        postData.append("commanderPosition", dataStore.commanderPosition);
        postData.append("dear", dataStore.dear);
        await http
          .post(config.API.leaveUser(), postData)

          .then((res) => {
            router.push(`/leave/edit/${res.data.result.id}`);
            success($q, "บันทึกสำเร็จ");
          })
          .catch((e: any) => {
            messageError($q, e);
          })
          .finally(() => {
            hideLoader();
          });
      });
    } else {
      dialogMessageNotify($q, "กรุณาเพิ่มรายชื่อ ผู้บังคับบัญชา");
    }
  } else {
    messageError($q, "", "ไม่มีสิทธิ์ลา");
  }
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFn(val: string, update: Function) {
  update(() => {
    option.value = dataStore.options.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

onMounted(async () => {
  dataStore.typeLeave = "";

  if (dataStore.options.length == 0) {
    await fectOptionType();
  }
});
</script>

<template>
  <div class="row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-11">
      <div class="toptitle text-white col-12 row items-center">
        <q-btn
          to="/leave"
          icon="mdi-arrow-left"
          unelevated
          round
          dense
          flat
          color="primary"
          class="q-mr-sm"
        />
        <div>สร้างใบลา</div>
      </div>

      <q-form ref="myform">
        <q-card bordered>
          <div class="row q-col-gutter-md q-pa-md">
            <div class="col-xs-12 col-sm-12">
              <div style="display: flex; align-items: center">
                <q-icon
                  name="mdi-numeric-1-circle"
                  size="20px"
                  color="primary"
                />
                <div class="q-pl-sm text-weight-bold text-dark">
                  เลือกประเภทการลา
                </div>
              </div>
              <div class="q-py-sm q-px-lg">
                <div class="row">
                  <q-select
                    dense
                    class="col-12 col-sm-9 col-md-6 inputgreen"
                    outlined
                    v-model="model"
                    :options="option"
                    option-value="code"
                    option-label="name"
                    emit-value
                    map-options
                    prefix="ประเภทใบลา :"
                    @update:model-value="
                      dataStore.typeConvert(model, null),
                        (modelSpecific = ''),
                        dataStore.fetchProfile()
                    "
                    use-input
                    @filter="filterOptionFn"
                  >
                    <template v-slot:no-option>
                      <q-item>
                        <q-item-section class="text-grey">
                          ไม่มีข้อมูล
                        </q-item-section>
                      </q-item>
                    </template></q-select
                  >
                </div>

                <div class="row q-mt-sm">
                  <div
                    class="col-12 col-sm-6 col-md-4"
                    v-if="model === 'LV-006' || model === 'LV-008'"
                  >
                    <q-select
                      dense
                      outlined
                      v-model="modelSpecific"
                      :options="
                        model === 'LV-006'
                          ? dataStore.optionsOrdination
                          : dataStore.optionsSpecific
                      "
                      option-value="id"
                      option-label="name"
                      emit-value
                      map-options
                      prefix="ประเภทการลา :"
                    />
                  </div>
                </div>
              </div>

              <div>
                <div style="display: flex; align-items: center">
                  <q-icon
                    name="mdi-numeric-2-circle"
                    size="20px"
                    color="primary"
                  />
                  <div class="q-pl-sm text-weight-bold text-dark">
                    ข้อมูลการลา
                  </div>
                </div>
                <q-card
                  bordered
                  class="q-pa-md bg-grey-1"
                  v-if="dataStore.isLoadingProfile"
                >
                  <div class="row q-col-gutter-sm">
                    <div class="col-12">
                      <div class="row q-col-gutter-sm">
                        <div class="col-md-4 col-xs-12">
                          <q-skeleton height="40px" />
                        </div>
                        <div class="col-md-4 col-xs-12">
                          <q-skeleton height="40px" />
                        </div>
                      </div>
                    </div>
                    <div class="col-md-6 col-xs-12">
                      <q-skeleton height="40px" />
                    </div>
                    <div class="col-md-6 col-xs-12">
                      <q-skeleton height="40px" />
                    </div>
                    <div class="col-md-4 col-xs-12">
                      <q-skeleton height="40px" />
                    </div>
                    <div class="col-md-4 col-xs-12">
                      <q-skeleton height="40px" />
                    </div>
                    <div class="col-md-4 col-xs-12">
                      <q-skeleton height="40px" />
                    </div>
                    <div class="col-md-4 col-xs-12">
                      <q-skeleton height="40px" />
                    </div>
                  </div>
                </q-card>

                <FormPart2 v-else :model="model" />
              </div>
            </div>

            <div class="col-12" v-if="dataStore.isLoadingProfile">
              <div style="display: flex; align-items: center">
                <q-icon
                  name="mdi-numeric-3-circle"
                  size="20px"
                  color="primary"
                />
                <div class="q-pl-sm text-weight-bold text-dark">กรอกข้อมูล</div>
              </div>
              <q-card bordered class="q-pa-md bg-grey-1">
                <div class="row q-col-gutter-sm">
                  <div class="col-12">
                    <q-skeleton height="40px" />
                  </div>
                  <div class="col-12">
                    <div class="row q-col-gutter-sm">
                      <div class="col-md-3 col-xs-6">
                        <q-skeleton height="40px" />
                      </div>
                      <div class="col-md-3 col-xs-6">
                        <q-skeleton height="40px" />
                      </div>
                    </div>
                  </div>
                  <div class="col-12">
                    <div class="row q-col-gutter-sm">
                      <div class="col-md-3 col-xs-12">
                        <q-skeleton height="40px" />
                      </div>
                    </div>
                  </div>
                  <div class="col-12">
                    <q-skeleton height="40px" />
                  </div>
                  <div class="col-12">
                    <q-skeleton height="120px" />
                  </div>
                  <div class="col-12">
                    <q-skeleton height="40px" />
                  </div>
                </div>
              </q-card>
            </div>

            <div class="col-12" v-else>
              <SickForm
                v-if="model === 'LV-001' || model === 'LV-002'"
                v-model:type="model"
                :on-submit="onSubmit"
              />
              <FormBirth v-if="model === 'LV-003'" :on-submit="onSubmit" />
              <HelpWifeBirthForm
                v-if="model === 'LV-004'"
                :on-submit="onSubmit"
              />
              <VacationForm v-if="model === 'LV-005'" :on-submit="onSubmit" />
              <OrdinationForm
                v-if="model === 'LV-006' && modelSpecific == 'ลาอุปสมบท'"
                :on-submit="onSubmit"
              />
              <HajjForm
                v-if="
                  model === 'LV-006' && modelSpecific == 'ลาประกอบพิธีฮัจญ์'
                "
                :on-submit="onSubmit"
              />
              <MilitaryForm
                v-if="model === 'LV-007'"
                style="width: 100%"
                :on-submit="onSubmit"
              />
              <StudyForm
                v-if="model === 'LV-008' && modelSpecific === 'ศึกษาต่อ'"
                style="width: 100%"
                :on-submit="onSubmit"
              />
              <TrainForm
                v-if="
                  (model === 'LV-008' && modelSpecific == 'ฝึกอบรม') ||
                  (model === 'LV-008' && modelSpecific == 'ปฎิบัติการวิจัย') ||
                  (model === 'LV-008' && modelSpecific == 'ดูงาน')
                "
                :on-submit="onSubmit"
              />
              <WorkInternationalForm
                v-if="model === 'LV-009'"
                :on-submit="onSubmit"
              />
              <FollowSpouseForm
                v-if="model === 'LV-010'"
                :on-submit="onSubmit"
              />
              <RehabilitationForm
                v-if="model === 'LV-011'"
                :on-submit="onSubmit"
              />
            </div>
          </div>
        </q-card>
      </q-form>
    </div>
  </div>
</template>
