<template>
  <div class="rating-topic-comment-record-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="24">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-select
              v-model="queryForm.userId"
              v-loadmore="loadMoreUsers"
              clearable
              filterable
              placeholder="请选择用户"
              style="width: 200px"
              @change="handleFilterChange"
            >
              <el-option v-for="item in userList" :key="item.id" :label="item.nickname || item.id" :value="item.id">
                <div style="display: flex; align-items: center">
                  <el-image
                    v-if="item.avatar"
                    :src="getThumbUrl(item.avatar)"
                    style="width: 24px; height: 24px; border-radius: 50%; margin-right: 10px"
                  />
                  <span>{{ item.nickname || '未知用户' }}</span>
                  <el-tag v-if="item.isRobot" size="mini" style="margin-left: 8px" type="info">机器人</el-tag>
                  <el-tag v-else size="mini" style="margin-left: 8px" type="success">真人</el-tag>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select
              v-model="queryForm.topicId"
              v-loadmore="loadMoreTopics"
              clearable
              filterable
              placeholder="请选择评价主题"
              style="width: 200px"
              @change="handleTopicChange"
            >
              <el-option v-for="item in topicList" :key="item.id" :label="item.title" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select
              v-model="queryForm.itemId"
              v-loadmore="loadMoreItems"
              clearable
              :disabled="!queryForm.topicId"
              filterable
              placeholder="请先选择主题，再选择评价项"
              style="width: 220px"
              @change="handleFilterChange"
            >
              <el-option v-for="item in itemList" :key="item.id" :label="item.name" :value="item.id">
                <div style="display: flex; align-items: center">
                  <el-image
                    v-if="item.avatarUrl"
                    :src="getThumbUrl(item.avatarUrl)"
                    style="width: 24px; height: 24px; border-radius: 50%; margin-right: 10px"
                  />
                  <span>{{ item.name }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button :type="queryForm.trueUser ? 'warning' : 'default'" @click="toggleTrueUser">
              {{ queryForm.trueUser ? '已去掉机器人' : '去掉机器人' }}
            </el-button>
          </el-form-item>

          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-edit" type="success" @click="handleCommentNow">立即评论</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-left-panel>
    </vab-query-form>

    <el-table v-loading="listLoading" :data="list" :element-loading-text="elementLoadingText">
      <el-table-column align="left" label="评论内容" min-width="250">
        <template #default="{ row }">
          <div class="comment-content-cell">
            <div class="content-text">{{ row.content }}</div>
            <div class="comment-meta">
              <span class="meta-item">
                <i class="el-icon-thumb" />
                {{ row.likeCount || 0 }}
              </span>
              <span class="meta-item">
                <i class="el-icon-chat-dot-square" />
                {{ row.replyCount || 0 }}
              </span>
              <el-tag v-if="row.status === 2" size="mini" style="margin-left: 8px" type="success">已展示</el-tag>
              <el-tag v-else size="mini" style="margin-left: 8px" type="info">隐藏/待审</el-tag>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="left" label="评价目标" min-width="200">
        <template #default="{ row }">
          <div class="target-info-cell">
            <div class="topic-title">
              [{{ row.rating ? (row.rating.topic ? row.rating.topic.title : '未知主题') : row.topicName || '未知主题' }}]
            </div>
            <div class="item-info">
              <el-image
                v-if="row.rating && row.rating.item && row.rating.item.avatarUrl"
                class="item-avatar"
                :src="getThumbUrl(row.rating.item.avatarUrl)"
              />
              <el-image v-else-if="row.itemAvatarUrl" class="item-avatar" :src="getThumbUrl(row.itemAvatarUrl)" />
              <span class="item-name">{{ row.rating && row.rating.item ? row.rating.item.name : row.itemName || '未知评价项' }}</span>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="left" label="用户信息" min-width="200">
        <template #default="{ row }">
          <div v-if="row.user" class="user-info-cell">
            <el-image
              v-if="row.user.avatar"
              class="user-avatar"
              :preview-src-list="[row.user.avatar]"
              :src="getThumbUrl(row.user.avatar)"
            />
            <div v-else class="user-avatar-placeholder"><i class="el-icon-user" /></div>
            <div class="user-details">
              <div class="user-nickname">
                {{ row.user.nickname || '未知用户' }}
                <el-tag v-if="row.user.isRobot" size="mini" style="margin-left: 4px" type="info">机器人</el-tag>
                <el-tag v-else size="mini" style="margin-left: 4px" type="success">真人</el-tag>
              </div>
              <div class="user-id">{{ row.user.id }}</div>
            </div>
          </div>
          <div v-else class="user-details">
            <div class="user-id">{{ row.userId }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="评论时间" prop="createdAt" width="160">
        <template #default="{ row }">
          {{ formatTime(row.createdAt) }}
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <record-comment-edit ref="commentEdit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { userCommentList } from '@/api/rating/topicOperate'
  import { getList as getUserList } from '@/api/system/user'
  import { getList as getTopicList } from '@/api/rating/topic'
  import { getList as getItemList } from '@/api/rating/topicItem'
  import { formatTime } from '@/utils'
  import { getThumbUrl } from '@/utils/blessing'
  import RecordCommentEdit from './components/RecordCommentEdit'

  export default {
    name: 'RatingTopicCommentIndex',
    components: { RecordCommentEdit },
    directives: {
      loadmore: {
        bind(el, binding) {
          setTimeout(() => {
            const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
            if (SELECTWRAP_DOM) {
              SELECTWRAP_DOM.addEventListener('scroll', function () {
                const condition = this.scrollHeight - this.scrollTop <= this.clientHeight + 2
                if (condition) {
                  binding.value()
                }
              })
            }
          }, 0)
        },
      },
    },
    data() {
      return {
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        elementLoadingText: '正在加载...',
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          userId: '',
          topicId: '',
          itemId: '',
          trueUser: false,
        },

        // 用户下拉列表状态
        userList: [],
        userQuery: { pageNo: 1, pageSize: 20, trueUser: false },
        userTotal: 0,
        fetchingUsers: false,

        // Topic 下拉列表状态
        topicList: [],
        topicQuery: { pageNo: 1, pageSize: 20 },
        topicTotal: 0,
        fetchingTopics: false,

        // Item 下拉列表状态
        itemList: [],
        itemQuery: { pageNo: 1, pageSize: 20, topicId: '' },
        itemTotal: 0,
        fetchingItems: false,
      }
    },
    created() {
      this.fetchUserList()
      this.fetchTopicList()
      this.fetchData()
    },
    methods: {
      formatTime,
      getThumbUrl,

      // -- 用户列表加载 --
      async fetchUserList() {
        if (this.fetchingUsers) return
        this.fetchingUsers = true
        try {
          const params = { pageNo: this.userQuery.pageNo, pageSize: this.userQuery.pageSize, appId: '6a0d7dbe4c5de50f2ba66475' }
          if (this.userQuery.trueUser) params.trueUser = true

          const { data } = await getUserList(params)
          this.userList = this.userList.concat(data.list || [])
          this.userTotal = data.totalCount || 0
        } catch (error) {
          console.error(error)
        } finally {
          this.fetchingUsers = false
        }
      },
      loadMoreUsers() {
        if (this.userList.length >= this.userTotal || this.fetchingUsers) return
        this.userQuery.pageNo += 1
        this.fetchUserList()
      },

      // -- Topic 列表加载 --
      async fetchTopicList() {
        if (this.fetchingTopics) return
        this.fetchingTopics = true
        try {
          const { data } = await getTopicList(this.topicQuery)
          this.topicList = this.topicList.concat(data.list || [])
          this.topicTotal = data.totalCount || 0
        } catch (error) {
          console.error(error)
        } finally {
          this.fetchingTopics = false
        }
      },
      loadMoreTopics() {
        if (this.topicList.length >= this.topicTotal || this.fetchingTopics) return
        this.topicQuery.pageNo += 1
        this.fetchTopicList()
      },

      // -- Item 列表加载 --
      async fetchItemList() {
        if (this.fetchingItems || !this.itemQuery.topicId) return
        this.fetchingItems = true
        try {
          const { data } = await getItemList(this.itemQuery)
          this.itemList = this.itemList.concat(data.list || [])
          this.itemTotal = data.totalCount || 0
        } catch (error) {
          console.error(error)
        } finally {
          this.fetchingItems = false
        }
      },
      loadMoreItems() {
        if (this.itemList.length >= this.itemTotal || this.fetchingItems) return
        this.itemQuery.pageNo += 1
        this.fetchItemList()
      },

      // -- 交互与筛选 --
      toggleTrueUser() {
        this.queryForm.trueUser = !this.queryForm.trueUser

        // 同步更新 userQuery
        this.userQuery.trueUser = this.queryForm.trueUser
        // 重新拉取用户下拉列表
        this.userQuery.pageNo = 1
        this.userList = []
        this.userTotal = 0
        this.fetchUserList()

        // 重新拉取表格数据
        this.queryData()
      },
      handleTopicChange(val) {
        // 重置 item 选择
        this.queryForm.itemId = ''
        this.itemList = []
        this.itemQuery.pageNo = 1
        this.itemTotal = 0

        if (val) {
          this.itemQuery.topicId = val
          this.fetchItemList()
        } else {
          this.itemQuery.topicId = ''
        }

        this.queryData()
      },
      handleFilterChange() {
        this.queryData()
      },

      // -- 列表数据加载 --
      handleCommentNow() {
        this.$refs['commentEdit'].showEdit()
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        try {
          const params = { pageNo: this.queryForm.pageNo, pageSize: this.queryForm.pageSize }
          if (this.queryForm.userId) params.userId = this.queryForm.userId
          if (this.queryForm.topicId) params.topicId = this.queryForm.topicId
          if (this.queryForm.itemId) params.itemId = this.queryForm.itemId
          if (this.queryForm.trueUser) params.trueUser = true

          const { data } = await userCommentList(params)
          this.list = data.list || []
          this.total = data.totalCount || 0
        } catch (error) {
          console.error(error)
        } finally {
          this.listLoading = false
        }
      },
    },
  }
</script>

<style scoped>
  .rating-topic-comment-record-container {
    padding: 20px;
  }

  /* 评论内容列样式 */
  .comment-content-cell {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  .content-text {
    font-size: 14px;
    color: #303133;
    line-height: 1.5;
    word-break: break-all;
  }
  .comment-meta {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #909399;
  }
  .meta-item {
    display: flex;
    align-items: center;
    margin-right: 12px;
  }
  .meta-item i {
    margin-right: 4px;
  }

  /* 用户信息列样式 */
  .user-info-cell {
    display: flex;
    align-items: center;
  }
  .user-avatar,
  .user-avatar-placeholder {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
    flex-shrink: 0;
  }
  .user-avatar-placeholder {
    background-color: #f0f2f5;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    font-size: 20px;
  }
  .user-details {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .user-nickname {
    font-weight: bold;
    color: #303133;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .user-id {
    font-size: 12px;
    color: #909399;
  }

  /* 评价目标列样式 */
  .target-info-cell {
    display: flex;
    flex-direction: column;
  }
  .topic-title {
    color: #409eff;
    font-weight: bold;
    margin-bottom: 6px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .item-info {
    display: flex;
    align-items: center;
  }
  .item-avatar {
    width: 24px;
    height: 24px;
    border-radius: 4px;
    margin-right: 8px;
    flex-shrink: 0;
  }
  .item-name {
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>
