<template>
  <DialogFrame ref="dialog" :header-title="'Edit ' + localTitle">
    <div class="row justify-center">
      <q-input
        autofocus
        class="q-ml-md col-6"
        :label="localTitle"
        filled
        v-model="value"
        @keyup.enter="save"
      ></q-input>
    </div>
    <div class="row justify-center">
      <q-btn class="q-ma-md" color="primary" no-caps @click="save">Save</q-btn>
    </div>
  </DialogFrame>
</template>

<script setup lang="ts">
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import { ref } from 'vue';
import { appApi } from 'src/boot/axios';
import type { Member } from 'src/vueLib/models/member';
import { useNotify } from 'src/vueLib/general/useNotify';

const dialog = ref();
const localMember = ref();
const localTitle = ref('');
const localField = ref('');
const value = ref('');

const emit = defineEmits(['update']);
const { NotifyResponse } = useNotify();

function open(label: string, field: string, member: Member) {
  localTitle.value = label;
  localField.value = field;
  localMember.value = member;

  value.value = localMember.value[field];
  dialog.value?.open();
}

function save() {
  const query = 'secure/members/edit?id=' + localMember.value.id;
  let payload = {};

  if (value.value === localMember.value[localField.value]) {
    dialog.value.close();
    return;
  }
  payload = {
    [localField.value]: value.value,
  };

  appApi
    .post(query, payload)
    .then(() => {
      emit('update', '');
      dialog.value.close();
    })
    .catch((err) => {
      NotifyResponse(err, 'error');
    });
}

defineExpose({ open });
</script>
