<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form :model="formData" label-placement="left" label-width="100px" ref="formRef">
        <n-form-item
          label="消息内容"
          path="message"
          :rule="{ required: true, message: '请输入消息内容', trigger: 'blur' }"
        >
          <n-input v-model:value="formData.message" type="textarea" rows="4" />
        </n-form-item>
      </n-form>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import { sendMsg } from '@/api/system/user';
  import { useUserStore } from '@/store/modules/user';
  import { onMounted, reactive, ref } from 'vue';
  import { useModal } from '@/components/Modal';
  import { useMessage } from 'naive-ui';

  /**
   * 定义参数
   */
  const message = useMessage();
  const userStore = useUserStore();
  const userInfo: object = userStore.getUserInfo || {};
  const emit = defineEmits(['update:visible']);
  const formRef = ref();

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    receiveId: {
      type: String,
      default: '',
    },
  });

  /**
   * 定义表单参数
   */
  const formData = reactive({
    message: '',
  });

  /**
   * 定义模态
   */
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: '发送消息',
    subBtuText: '确定',
    width: 600,
  });
  /**
   * 关闭窗体
   */
  const handleClose = () => {
    emit('update:visible', false);
  };

  /**
   * 执行提交表单数据
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        await sendMsg({
          formId: userInfo.id,
          receiveId: props.receiveId,
          message: formData.message,
        });
        setSubLoading(false);
        message.success('发送成功');
        emit('update:visible', false);
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };
  defineExpose({
    openModal,
  });
</script>
