<template>
  <el-dialog
    v-model="visible"
    :title="form.chatType === BooleanFlag.YES ? '发送匿名私信' : '发送实名私信'"
    width="500px"
    :before-close="handleClose"
    top="30vh"
    class="send-message-dialog"
    destroy-on-close
  >
    <div class="flex gap-3">
      <el-avatar :size="40" :src="avatar" />
      <CommentBox
        class="flex-1"
        :textAreaHeight="100"
        placeholder="输入私信内容…"
        v-model:inputText="form.content"
        v-model:inputImg="form.images"
        :showMention="false"
      >
        <template #submit>
          <el-button
            :disabled="isDisabled"
            :loading="loading"
            type="primary"
            round
            @click="handleSubmit"
            class="px-5 !rounded-lg text-sm font-medium shadow-sm"
            >发送</el-button
          >
        </template>
      </CommentBox>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { sendMessage } from '@/api'
import CommentBox from '../CommentBox/index.vue'
import { push } from 'notivue'
import { BooleanFlag } from '@/constants'
import type { SendMessageDto } from '@/api'
import { useResetData } from '@/hooks'
const emit = defineEmits<{
  (e: 'sendSuccess'): void
}>()

const visible = ref(false)
const loading = ref(false)
const isDisabled = computed(() => {
  return !form.value.content || loading.value
})

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const [form] = useResetData<SendMessageDto>({
  content: '',
  chatType: BooleanFlag.NO,
  senderId: userInfo.value.userId,
  receiverId: '',
  images: '',
})

const avatar = computed(() => {
  return form.value.chatType === BooleanFlag.YES
    ? userInfo.value.hiddenAvatar
    : userInfo.value.avatar
})

const open = ({ receiverId, isReal }: { receiverId: string; isReal: BooleanFlag }) => {
  visible.value = true
  form.value.receiverId = receiverId
  form.value.chatType = isReal ? BooleanFlag.NO : BooleanFlag.YES
}

const handleClose = () => {
  visible.value = false
  form.value.content = ''
  form.value.images = ''
}

const handleSubmit = async () => {
  loading.value = true
  try {
    await sendMessage(form.value)
    push.success('发送成功')
    handleClose()
    emit('sendSuccess')
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

defineExpose({
  open,
})
</script>

<style scoped>
.send-message-dialog :deep(.el-dialog__header) {
  margin-right: 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #f3f4f6;
}
</style>
