<script setup lang="ts">
import type { Rule } from 'ant-design-vue/es/form';
import type { FormExpose } from 'ant-design-vue/es/form/Form';
import { useToggle } from '@vueuse/core';

defineOptions({
  name: 'DrawerExpand',
});

const emit = defineEmits(['submit']);

const rules: Record<string, Rule[]> = {
  name: [{ required: true, message: '请输入属性名称', trigger: 'blur' }],
  value: [{ required: true, message: '请输入属性值', trigger: 'blur' }],
};

const [open, setOpen] = useToggle(false);
const formRef = ref<FormExpose>();
const form = ref<any>({});

async function onOpen(key: string, record?: any, index?: number) {
  setOpen(true);
  if (key === 'add') {
    form.value = {};
  }
  else if (key === 'edit' && record) {
    form.value = { ...record };
    form.value.index = index;
  }
}
const [loading, setLoading] = useToggle(false);

function onSubmit() {
  formRef.value?.validate().then(() => {
    setLoading(true);
    const params: any = { ...form.value };
    emit('submit', params);
    setLoading(false);
    setOpen(false);
  });
}

function close() {
  setOpen(false);
}

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

<template>
  <a-drawer
    v-model:open="open"
    title="属性配置"
    placement="right"
    :width="520"
    destroy-on-close
    :footer-style="{ textAlign: 'right' }"
    @close="close"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 4 }"
    >
      <a-form-item label="属性名称" name="name">
        <a-input v-model:value="form.name" :maxlength="100" />
      </a-form-item>
      <a-form-item label="属性值" name="value">
        <a-input v-model:value="form.value" :maxlength="1000" />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="close">
          取消
        </a-button>
        <a-button type="primary" :loading="loading" @click="onSubmit">
          提交
        </a-button>
      </a-space>
    </template>
  </a-drawer>
</template>
