<script setup lang="ts">
import { ref, watch } from "vue";
import { QForm, useQuasar } from "quasar";

import { useCounterMixin } from "@/stores/mixin";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const mixin = useCounterMixin();
const { dialogConfirm } = mixin;

const props = defineProps({
  modal: Boolean,
  id: String,
  closePopup: Function,
  duty: {
    type: String,
    default: "",
  },
  command: {
    type: String,
    default: "",
  },
  resolution: {
    type: String,
    default: "",
  },
  save: {
    type: Function,
    default: () => console.log("not function"),
  },
});

const duty = ref<string>("");
const resolution = ref<string>("");
const myForm = ref<QForm | null>(null);

/**
 * ฟังก์ชั่น Save
 */
async function submit() {
  if (myForm.value !== null) {
    myForm.value.validate().then((success) => {
      if (success) {
        dialogConfirm($q, async () => {
          await props.save(props.id, duty.value, resolution.value);
          duty.value = "";
          resolution.value = "";
        });
      }
    });
  }
}

watch(props, () => {
  duty.value = props?.duty === "-" ? "" : props.duty;
  resolution.value = props?.command === "-" ? "" : props.command;
});
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="width: 30vw">
      <q-form ref="myForm">
        <DialogHeader tittle="แก้ไขข้อมูลกรรมการ" :close="props.closePopup" />
        <q-separator />
        <q-card-section>
          <q-input
            v-model="duty"
            outlined
            dense
            class="col-12 q-mb-sm"
            label="หน้าที่"
            :rules="[(val:string) => !!val || `กรุณากรอกหน้าที่`]"
            hide-bottom-space
          />
          <q-input
            v-model="resolution"
            outlined
            dense
            class="col-12 q-mb-sm"
            label="มติ/คำสั่ง"
            :rules="[(val:string) => !!val || `กรุณากรอก มติ/คำสั่ง`]"
            hide-bottom-space
          />
        </q-card-section>

        <q-separator />

        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn label="บันทึก" @click="submit()" color="public" />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
