<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 { sendFormSchema } from './application.data';
  import { sendMessage } from '/@/api/platform/common/controller/pushApplication';
  import { BasicModal, ModalProps, useModalInner } from '/@/components/Modal';
  import { ref } from 'vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const messageSecret = ref<Nullable<string>>('');
  const userStore = useUserStore();
  const userInfoStore = userStore.getUserInfo;
  const emit = defineEmits(['success', 'register']);
  const [registerForm, { resetFields, setFieldsValue, validate, clearValidate, updateSchema }] = useForm({
    labelWidth: 80,
    schemas: sendFormSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 }
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: WindowInnerData = { _tag: '' }) => {
    // 处理清除脏数据
    await resetFields();
    await clearValidate();
    messageSecret.value = data.record?.messageSecret;
    const props: Partial<ModalProps> = { confirmLoading: false };
    props.title = '企业发送消息';
    // 尾部:设置处理后的最终配置数据
    setModalProps(props);
  });

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