<template>
  <div class="store-reviews">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>门店评价管理</span>
            <el-tag type="success" effect="dark" class="branch-tag">{{
              branch.branch_name
            }}</el-tag>
          </div>
          <el-button type="primary" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="菜品名称">
            <el-input
              v-model="searchForm.dishName"
              placeholder="请输入菜品名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="评分">
            <el-select
              v-model="searchForm.rating"
              placeholder="请选择评分"
              clearable
              style="width: 150px"
            >
              <el-option label="1星" value="1" />
              <el-option label="2星" value="2" />
              <el-option label="3星" value="3" />
              <el-option label="4星" value="4" />
              <el-option label="5星" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="评论类型">
            <el-select
              v-model="searchForm.commentType"
              placeholder="评论类型"
              clearable
              style="width: 150px"
            >
              <el-option label="主评论" value="main" />
              <el-option label="回复评论" value="reply" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading" border stripe>
        <el-table-column type="expand">
          <template #default="scope">
            <div v-if="scope.row.replies && scope.row.replies.length > 0" class="reply-list">
              <el-table :data="scope.row.replies" border style="width: 100%" size="small">
                <el-table-column prop="commentId" label="ID" width="80" align="center" />
                <el-table-column prop="dishName" label="菜品名称" width="120" align="center" />
                <el-table-column prop="accountName" label="用户" width="120" align="center" />
                <el-table-column prop="commentText" label="评论内容" min-width="200">
                  <template #default="rScope">
                    <div class="comment-content">
                      {{ rScope.row.commentText }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="评论时间" width="180" align="center">
                  <template #default="rScope">
                    {{ formatDateTime(rScope.row.createdAt) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center" fixed="right">
                  <template #default="rScope">
                    <el-button size="small" @click="handleDelete(rScope.row)" type="danger" link>
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="no-replies">暂无回复</div>
          </template>
        </el-table-column>
        <el-table-column prop="commentId" label="ID" width="80" align="center" />
        <el-table-column prop="dishName" label="菜品名称" width="120" align="center" />
        <el-table-column prop="accountName" label="用户" width="120" align="center" />
        <el-table-column prop="commentText" label="评论内容" min-width="200">
          <template #default="scope">
            <div class="comment-content">
              {{ scope.row.commentText }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="commentRating" label="评分" width="120" align="center">
          <template #default="scope">
            <el-rate
              v-model="scope.row.commentRating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="评论时间" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)" type="info" link>
              查看
            </el-button>
            <el-button size="small" @click="handleReply(scope.row)" type="primary" link>
              回复
            </el-button>
            <el-button size="small" @click="handleDelete(scope.row)" type="danger" link>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 评论详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="评论详情" width="600px">
      <div v-if="currentComment" class="comment-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="评论ID">{{ currentComment.commentId }}</el-descriptions-item>
          <el-descriptions-item label="评论类型">
            {{ currentComment.updatedId && currentComment.updatedId > 0 ? '回复评论' : '主评论' }}
          </el-descriptions-item>
          <el-descriptions-item label="菜品名称">{{
            currentComment.dishName
          }}</el-descriptions-item>
          <el-descriptions-item label="用户账号">{{
            currentComment.accountName
          }}</el-descriptions-item>
          <el-descriptions-item label="评分">
            <el-rate
              v-model="currentComment.commentRating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </el-descriptions-item>
          <el-descriptions-item label="评论时间">{{
            formatDateTime(currentComment.createdAt)
          }}</el-descriptions-item>
          <el-descriptions-item label="评论内容" :span="2">
            {{ currentComment.commentText }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 显示相关回复 -->
        <div
          v-if="currentComment.replies && currentComment.replies.length > 0"
          class="replies-section"
        >
          <h4>相关回复</h4>
          <el-table :data="currentComment.replies" border style="width: 100%" size="small">
            <el-table-column prop="commentId" label="ID" width="80" align="center" />
            <el-table-column prop="accountName" label="用户" width="120" align="center" />
            <el-table-column prop="commentText" label="评论内容" min-width="200">
              <template #default="scope">
                <div class="comment-content">
                  {{ scope.row.commentText }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="回复时间" width="180" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 回复评论对话框 -->
    <el-dialog v-model="replyDialogVisible" title="回复评论" width="500px">
      <div v-if="currentComment" class="original-comment">
        <h4>原评论</h4>
        <p>{{ currentComment.commentText }}</p>
        <p class="comment-info">
          {{ currentComment.accountName }} - {{ formatDateTime(currentComment.createdAt) }}
        </p>
      </div>

      <el-form
        :model="replyForm"
        :rules="replyRules"
        ref="replyFormRef"
        label-width="80px"
        class="reply-form"
      >
        <el-form-item label="回复内容" prop="commentText">
          <el-input
            v-model="replyForm.commentText"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveReply">提交回复</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import axios from 'axios'

// 接口类型定义
interface Comment {
  commentId: number
  commentText: string
  commentDishId: number
  commentAccountId: string
  commentRating: number
  isDeleted: number
  deletedAt: string | null
  createdAt: string
  updatedId: number | null
  // 附加信息
  dishName: string
  accountName: string
  replies?: Comment[]
}

interface SearchForm {
  dishName: string
  rating: string
  commentType: string
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Comment[]>([])
const detailDialogVisible = ref(false)
const replyDialogVisible = ref(false)
const currentComment = ref<Comment | null>(null)
const replyFormRef = ref<FormInstance>()
const loadingReplies = ref<Record<number, boolean>>({})

// 搜索表单
const searchForm = reactive<SearchForm>({
  dishName: '',
  rating: '',
  commentType: '',
})

// 分页数据
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 回复表单
const replyForm = reactive({
  commentText: '',
  commentDishId: 0,
  parentCommentId: 0,
})

const branch = reactive({
  branch_id: 1,
  branch_name: '中山路总店',
  branch_address: '广东省深圳市福田区中山路123号',
  branch_phone: '0755-88888888',
  branch_start: '08:00',
  branch_end: '22:00',
  branch_status: '营业中',
  branch_boss: 'ACC001',
  is_deleted: 0,
  deleted_at: null,
  created_at: '2025-06-15 13:29:22',
  updated_at: '2025-06-15 15:21:51',
})

// 回复表单验证规则
const replyRules = {
  commentText: [{ required: true, message: '请输入回复内容', trigger: 'blur' }],
}

// API 基础URL
const API_BASE_URL = 'http://localhost:8080/api'

// 获取评论列表
const fetchComments = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      dishName: searchForm.dishName,
      rating: searchForm.rating,
      commentType: searchForm.commentType,
    }

    // 使用新的API端点，根据店铺ID获取评论列表
    const response = await axios.get(
      `${API_BASE_URL}/comments/branch/${branch.branch_id}/with-replies`,
      { params },
    )
    tableData.value = response.data.data.records || []
    pagination.total = response.data.data.total
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchComments()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    dishName: '',
    rating: '',
    commentType: '',
  })
  pagination.currentPage = 1
  fetchComments()
}

// 刷新数据
const handleRefresh = () => {
  fetchComments()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchComments()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchComments()
}

// 查看详情
const handleView = async (comment: Comment) => {
  try {
    // 根据店铺ID和菜品ID获取评论详情
    const response = await axios.get(
      `${API_BASE_URL}/comments/branch/${branch.branch_id}/dish/${comment.commentDishId}`,
    )

    // 从返回的评论列表中找到当前评论
    const comments = response.data.data || []
    const currentCommentDetail = comments.find((c: Comment) => c.commentId === comment.commentId)

    if (currentCommentDetail) {
      currentComment.value = currentCommentDetail

      // 获取所有回复评论
      const replies = comments.filter((c: Comment) => c.updatedId === comment.commentId)
      if (replies && replies.length > 0) {
        // 确保回复按时间排序
        if (currentComment.value) {
          currentComment.value.replies = replies.sort(
            (a: Comment, b: Comment) =>
              new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
          )
        }
      }

      detailDialogVisible.value = true
    } else {
      ElMessage.warning('未找到评论详情')
    }
  } catch (error) {
    console.error('获取评论详情失败:', error)
    ElMessage.error('获取评论详情失败')
  }
}

// 回复评论
const handleReply = (comment: Comment) => {
  currentComment.value = comment
  replyForm.commentDishId = comment.commentDishId
  replyForm.parentCommentId = comment.commentId
  replyForm.commentText = ''
  replyDialogVisible.value = true
}

// 保存回复
const handleSaveReply = async () => {
  if (!replyFormRef.value) return

  try {
    // 使用 Promise 形式的 validate 以正确处理异步验证
    const valid = await replyFormRef.value.validate()

    if (valid) {
      // 提交回复，使用新的API端点，包含店铺ID
      const response = await axios.post(
        `${API_BASE_URL}/comments/branch/${branch.branch_id}/reply`,
        {
          commentText: replyForm.commentText,
          commentDishId: replyForm.commentDishId,
          updatedId: replyForm.parentCommentId,
          commentRating: 5, // 使用默认评分5，而不是null，避免后端验证失败
        },
      )

      ElMessage.success('回复成功')
      replyDialogVisible.value = false

      // 回复成功后重新获取评论列表
      fetchComments()
    }
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error(typeof error === 'string' ? error : '回复失败')
  }
}

// 删除评论
const handleDelete = async (comment: Comment) => {
  try {
    await ElMessageBox.confirm('确定要删除此评论吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 使用新的API端点，包含店铺ID
    await axios.delete(`${API_BASE_URL}/comments/branch/${branch.branch_id}/${comment.commentId}`)
    ElMessage.success('删除成功')
    fetchComments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  // 默认只获取主评论
  searchForm.commentType = 'main'
  fetchComments()
})
</script>

<style scoped>
.store-reviews {
  padding: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.branch-tag {
  margin-left: 10px;
}

.search-bar {
  margin-bottom: 5px;
}

.search-form {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.comment-content {
  word-break: break-word;
  line-height: 1.5;
}

.reply-tag {
  background-color: #409eff;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 6px;
}

.comment-detail {
  margin-bottom: 20px;
}

.replies-section {
  margin-top: 20px;
}

.original-comment {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.original-comment h4 {
  margin-top: 0;
  margin-bottom: 8px;
}

.comment-info {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.reply-form {
  margin-top: 15px;
}

.reply-list {
  padding: 10px 20px;
}

.no-replies {
  padding: 20px;
  text-align: center;
  color: #999;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.reply-user {
  font-weight: bold;
}
</style>
