<template>
  <w-dialog
    ref="dialogRef"
    :title="$t('addNew')"
    width="600px"
    :can-maximize="false"
    :buttons="[
      {
        label: $t('submit'),
        click: upload,
      },
    ]"
  >
    <q-form ref="formRef" :autofocus="false" :greedy="true" class="p-2">
      <q-file
        ref="fileRef"
        v-model="modelValue.file"
        :label="$t('file.single.tip')"
        dense
        outlined
        clearable
        counter
        :rules="[(val) => !!val || '必填项未填写']"
        @update:model-value="
          (value) => {
            modelValue.name = value.name;
          }
        "
      >
        <template #prepend>
          <q-icon name="cloud_upload" />
        </template>
      </q-file>

      <q-input v-model="modelValue.name" :label="$t('name')" outlined dense required :rules="[(val) => !!val || '必填项未填写']"></q-input>
      <q-input v-model="modelValue.description" :label="$t('description')" outlined dense></q-input>
    </q-form>
  </w-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { axios, Environment } from 'platform-core';

const props = defineProps({
  opener: { type: Object, default: undefined },
  foreignKey: { type: String, default: '' },
  foreignValue: { type: String, default: '' },
});

const emit = defineEmits<{
  (e: 'afterAdd', evt: Event): void;
}>();

const dialogRef = ref();
const formRef = ref();
const fileRef = ref();
const modelValue = reactive({
  name: undefined,
  description: undefined,
  file: undefined,
});

const upload = async () => {
  const validated = await validateForm();
  if (validated) {
    axios
      .post(
        Environment.apiContextPath('/api/system/attachment/upload/' + props.foreignValue),
        {
          name: modelValue.name,
          description: modelValue.description,
          file: fileRef.value.nativeEl.files[0],
        },
        {
          loading: true,
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        },
      )
      .then(() => {
        close();
        emit('afterAdd');
      });
  }
};

const validateForm = async () => {
  let validate = false;
  await formRef.value.validate().then((success) => {
    if (success) {
      validate = true;
    }
  });
  return validate;
};

const open = () => {
  dialogRef.value.show();
  modelValue.name = undefined;
  modelValue.description = undefined;
  modelValue.file = undefined;
};

const close = () => {
  dialogRef.value.hide();
};

defineExpose({
  open,
  close,
});
</script>
