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

import type { FormBasicinfo } from "@/modules/15_development/interface/request/Main";

import DialogSelectAgency from "@/modules/15_development/components/DialogSelectAgency.vue";

import { useCounterMixin } from "@/stores/mixin";
import { useDevelopmentDataStore } from "@/modules/15_development/store/developmentStore";
import http from "@/plugins/http";
import config from "@/app.config";

const $q = useQuasar();
const store = useDevelopmentDataStore();
const mixin = useCounterMixin();

const {
  dialogRemove,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  date2Thai,
} = mixin;
const route = useRoute();
const projectId = ref<string>(route.params.id.toLocaleString());

const formData = reactive<FormBasicinfo>({
  year: new Date().getFullYear(),
  org: "",
  projectName: "",
  reason: "",
  objective: "",
});

const rows = ref<FormBasicinfo[]>([]);

const modalDialogSelect = ref<boolean>(false);
function selectAgency() {
  modalDialogSelect.value = true;
}
function updateAgency(name: string) {
  formData.org = name;
}

async function fetchData(id: string) {
  showLoader();
  await http
    .get(config.API.developmentBasicInfoById(id))
    .then(async (res) => {
      const data = res.data.result;
      formData.year = data.year;
      formData.reason = data.reason;
      formData.projectName = data.projectName;
      formData.objective = data.objective;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function editData(id: string) {
  await http
    .put(config.API.developmentBasicInfoById(id), {
      year: formData.year,
      reason: formData.reason,
      projectName: formData.projectName,
      objective: formData.objective,
    })
    .then(() => {
      fetchData(id);
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    editData(projectId.value);
    hideLoader();
  });
}

onMounted(async () => {
  fetchData(projectId.value);
});
</script>

<template>
  <q-form greedy @submit.prevent @validation-success="onSubmit">
    <div class="row col-12 q-col-gutter-md q-pa-md">
      <div class="col-xs-6 col-sm-2 col-md-2">
        <datepicker
          menu-class-name="modalfix"
          v-model="formData.year"
          :locale="'th'"
          autoApply
          year-picker
          :enableTimePicker="false"
        >
          <template #year="{ year }">{{ year + 543 }}</template>
          <template #year-overlay-value="{ value }">{{
            parseInt(value + 543)
          }}</template>
          <template #trigger>
            <q-input
              dense
              lazy-rules
              outlined
              class="inputgreen"
              :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-xs-10 col-sm-10 col-md-10">
        <q-input
          dense
          outlined
          class="inputgreen"
          v-model="formData.org"
          inputgreen
          label="ชื่อหน่วยงานที่รับผิดชอบ"
          hide-bottom-space
          lazy-rules
          @click="selectAgency"
        />
        <!-- :rules="[
          (val:string) =>
            !!val || `${'กรุณาเลือกหน่วยงานที่รับผิดชอบ'}`,
        ]" -->
      </div>
      <div class="col-xs-12 col-sm-12 col-md-12">
        <q-input
          outlined
          class="inputgreen"
          dense
          v-model="formData.projectName"
          label="ชื่อโครงการ/กิจกรรม/หลักสูตร"
          rows="6"
          type="textarea"
          hide-bottom-space
          :rules="[
            (val:string) =>
              !!val || `${'กรุณากรอกชื่อโครงการ/กิจกรรม/หลักสูตร'}`,
          ]"
        />
      </div>
      <div class="col-xs-12 col-sm-12 col-md-12">
        <q-input
          outlined
          class="inputgreen"
          dense
          v-model="formData.reason"
          label="หลักการและเหตุผล"
          rows="6"
          hide-bottom-space
          type="textarea"
        />
      </div>
      <div class="col-xs-12 col-sm-12 col-md-12">
        <q-input
          outlined
          class="inputgreen"
          dense
          v-model="formData.objective"
          label="วัตถุประสงค์"
          rows="6"
          hide-bottom-space
          type="textarea"
        />
      </div>
    </div>

    <q-separator />
    <div class="text-right q-pa-sm">
      <q-btn
        dense
        unelevated
        label="บันทึก"
        id="onSubmit"
        type="submit"
        color="public"
        class="q-px-md"
      >
        <q-tooltip>บันทึกข้อมูล</q-tooltip>
      </q-btn>
    </div>
  </q-form>

  <DialogSelectAgency
    v-model:modal="modalDialogSelect"
    @update:updateAgency="updateAgency"
  />
</template>

<style scoped></style>
