<template>
  <BasicModal
    v-bind="$attrs"
    width="720px"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { concernSendFormSchema } from './concern.data';
  import { concernFanMessageSend } from '/@/api/platform/common/controller/pushConcernFan';
  import { BasicModal, ModalProps, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { listPushConcernFanType } from '/@/api/platform/common/controller/pushConcernFanType';

  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const [registerForm, { resetFields, setFieldsValue, validate, clearValidate, updateSchema }] = useForm({
    labelWidth: 80,
    schemas: concernSendFormSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 }
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: BoxPayload = { _tag: '' }) => {
    // 处理清除脏数据
    await resetFields();
    await clearValidate();
    const props: Partial<ModalProps> = { confirmLoading: false };
    await updateSchema([
      {
        field: 'alias',
        defaultValue: data.record?.concernUserId
      },
      {
        field: 'pushTypeId',
        componentProps: {
          api: listPushConcernFanType,
          params: {
            size: 999,
            concernFanId: data.record?.id
          },
        }
      }
    ]);
    props.title = '推送关注消息';
    // 尾部:设置处理后的最终配置数据
    setModalProps(props);
  });

  async function handleSubmit() {
    try {
      // 提取验证数据
      const formData = await validate();
      // 处理提交之前逻辑
      setModalProps({ confirmLoading: true });
      await concernFanMessageSend(formData);
      // 处理提交完成之后逻辑
      closeModal();
      createMessage.success('推送成功!');
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
