<script setup lang="ts">
import type { TagModel }                              from '@/model/system.model';
import { tagEditMethod, tagMethod, tagsSearchMethod } from '@/request/api/system.api';
import { useRequest }                                 from 'alova/client';
import { type VxeFormListeners, type VxeFormProps }   from 'vxe-pc-ui';


type FormModel = Partial<TagModel>

const defaultModel = {};

const props = defineProps<{ data: FormModel }>();
const emits = defineEmits<{
  submit: [ data?: TagModel ],
}>();

const { loading, send: load } = useRequest(tagMethod, { immediate: false, initialData: props.data ?? defaultModel })
  .onSuccess(({ data }) => {
    formProps.data = { ...data };
  });
const { loading: submitting, send: submit } = useRequest(tagEditMethod, { immediate: false }).onSuccess(({ data }) => {
    emits('submit');
});

const { data: tags, loading: tagsLoading } = useRequest(tagsSearchMethod, { initialData: { total: 0, data: [] } });
const formProps = reactive<VxeFormProps<FormModel>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: { ...props.data },
  items: [
    { field: 'name', title: '标签名称', span: 24, itemRender: { name: 'VxeInput' } },
    {
      field: 'parentId', title: '上级标签', span: 24, itemRender: {
        name: 'VxeSelect',
        props: {
          loading: tagsLoading,
          options: computed(() => tags.value.data),
          optionProps: { value: 'id', label: 'name' },
          clearable: true, filterable: true,
        },
      },
    },
    { align: 'center', span: 24, slots: { default: 'active' } },
  ],
  rules: {
    name: [
      { required: true, message: '请输入标签名称' },
    ],
  },
});
const formEmits: VxeFormListeners<FormModel> = {
  submit({ data }) { submit(data); },
  reset() { formProps.data = { ...props.data }; },
};

onBeforeMount(() => {
  if ( props.data?.tagId ) load(props.data);
});
</script>
<template>

  <vxe-form v-bind="formProps" v-on="formEmits" :loading>
    <template #active>
      <vxe-button type="submit" status="primary" content="提交" :loading="submitting"></vxe-button>
      <vxe-button type="reset" content="重置" :disabled="submitting"></vxe-button>
    </template>
  </vxe-form>
</template>
<style scoped lang="scss"></style>
