<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { DiscussItem, DiscussCommentItem, User } from '../types'
import { ElMessage, ElInput } from 'element-plus'
import { getCommitList, replyToPost } from '../api'

interface Props {
  data: DiscussItem
}
const props = defineProps<Props>()

const params = reactive({ page: 1, limit: 3, floor_id: props.data.id })
let list = $ref<DiscussCommentItem[]>([])
let hasMore = $ref(true)
let loading = $ref(false)
function fetchList() {
  if (loading) return
  loading = true
  getCommitList(params)
    .then(res => {
      list = params.page === 1 ? res.data.data : list.concat(res.data.data)
      hasMore = res.data.data.length >= params.limit
      params.page++
    })
    .finally(() => {
      loading = false
    })
}
function refresh() {
  params.page = 1
  fetchList()
}

// 加载更多
function loadMore() {
  if (params.limit === 3) {
    params.page = 1
  }
  params.limit = 20
  fetchList()
}

const currentList = $computed(() => {
  if (list.length) return list
  return props.data.child_replies
})

onMounted(() => {
  hasMore = props.data.child_replies.length >= 3
})

const inputRef = $ref<InstanceType<typeof ElInput> | null>(null)
let activeComment = $ref<DiscussCommentItem>()
function handleReply(data: DiscussCommentItem) {
  if (data.id === activeComment?.id && formVisible) {
    formVisible = false
    return
  }
  activeComment = data
  formVisible = true
  form.content = `回复@${getUsername(data.sso_user)}：`
  nextTick(() => {
    inputRef?.focus()
  })
}

let formVisible = $ref(false)
const formRef = $ref<FormInstance>()
const form = reactive({
  content: '',
  files: []
})
const rules = ref<FormRules>({
  content: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
})
// 发布回复
function handleSubmit() {
  formRef?.validate().then(() => {
    replyToPost({
      id: props.data.discussion_id,
      reply_type: 2,
      floor_id: activeComment.floor_id,
      reply_id: activeComment.id,
      content: form.content.replace(`回复@${getUsername(activeComment.sso_user)}：`, '')
    }).then(() => {
      formVisible = false
      refresh()
      ElMessage({ message: '回复成功', type: 'success' })
    })
  })
}
function getUsername(data: User) {
  return data.realname || data.username || data.nickname
}

defineExpose({ refresh })
</script>

<template>
  <div class="discuss-comment-list" v-if="currentList.length">
    <div class="discuss-comment-item" v-for="item in currentList" :key="item.id">
      <img
        :src="item.sso_user.avatar || 'https://webapp-pub.ezijing.com/website/base/images/default.jpg'"
        class="discuss-comment-item__avatar" />
      <div class="discuss-comment-item__main">
        <div class="discuss-comment-item-hd">
          {{ getUsername(item.sso_user) }}
          <span v-if="item.reply_sso_user?.id">
            回复 <em>{{ getUsername(item.reply_sso_user) }}</em
            >：
          </span>
        </div>
        <div class="discuss-comment-item-bd">{{ item.content }}</div>
        <div class="discuss-comment-item-ft">
          <p>来自于{{ item.created_time }}</p>
          <div class="discuss-item__comment" @click="handleReply(item)"><p>回复</p></div>
        </div>
      </div>
    </div>
    <p class="more" v-if="hasMore"><span @click="loadMore">查看更多</span></p>
    <div class="discuss-item-form" v-if="formVisible">
      <el-form ref="formRef" :model="form" :rules="rules" hide-required-asterisk>
        <el-form-item prop="content">
          <el-input
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 6 }"
            :maxlength="100"
            v-model="form.content"
            ref="inputRef" />
        </el-form-item>
        <el-row justify="end">
          <el-button round type="primary" @click="handleSubmit">发表回复</el-button>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss">
.discuss-comment-list {
  margin-top: 20px;
  padding: 20px;
  background-color: #f4f5f8;
  border-radius: 6px;
  .discuss-item-form {
    margin-left: 40px;
  }
}
.discuss-comment-item {
  display: flex;
  margin-bottom: 24px;
}
.discuss-comment-item__main {
  flex: 1;
  margin-left: 10px;
}
.discuss-comment-item-hd {
  font-size: 16px;
  color: #666666;
  em {
    color: #3571e0;
  }
}
.discuss-comment-item-bd {
  margin-top: 12px;
  font-size: 16px;
  color: #666666;
}
.discuss-comment-item-ft {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
  font-size: 12px;
  color: #b4b4b4;
}
.discuss-comment-item__avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  overflow: hidden;
  object-fit: cover;
}
.more {
  padding: 10px;
  line-height: 30px;
  color: #3571e0;
  text-align: center;
  span {
    cursor: pointer;
  }
}
</style>
