<template>
  <el-dialog
    v-model="visible"
    title="发表评论"
    width="500px"
    :before-close="handleClose"
    top="30vh"
  >
    <div class="flex gap-3">
      <!-- 用户头像 -->
      <el-avatar :size="40" :src="userInfo.avatar" />
      <!-- 删除按钮 -->
      <CommentBox
        class="flex-1"
        :textAreaHeight="100"
        v-model:inputText="commentStr"
        v-model:inputImg="commentImgStr"
      >
        <template #submit>
          <el-button
            :disabled="isDisabled"
            :loading="loading"
            type="primary"
            @click="handleSubmit"
            class="px-6 py-2 bg-blue-500 hover:bg-blue-600 rounded-lg text-white text-sm font-medium shadow-sm hover:shadow-md transition-all duration-200"
            >发表</el-button
          >
        </template>
      </CommentBox>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { addComment } from '@/api'
import CommentBox from '../CommentBox/index.vue'
import { push } from 'notivue'

const emit = defineEmits<{
  (e: 'commentSuccess'): void
}>()

// 弹窗显示状态
const visible = ref(false)
// 评论内容
const commentStr = ref('')
const commentImgStr = ref('')
const loading = ref(false)
const isDisabled = computed(() => !commentStr.value.trim() || loading.value)

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

let articleId = 0

// 暴露 open 方法
const open = (id: number) => {
  articleId = id
  visible.value = true
  commentStr.value = ''
  commentImgStr.value = ''
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  commentStr.value = ''
  commentImgStr.value = ''
}

// 提交评论
const handleSubmit = async () => {
  loading.value = true

  try {
    await addComment({
      articleId: articleId,
      content: commentStr.value,
      imgUrl: commentImgStr.value,
    })
    console.log('评论内容:', commentStr.value)
    push.success('评论发表成功')
    handleClose()
    emit('commentSuccess')
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 暴露方法给父组件
defineExpose({
  open,
})
</script>
