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

// 基础配置
const baseAPI = 'http://localhost:8080'

// 接口类型定义
interface Branch {
  branchId: number
  branchName: string
  branchAddress: string
  branchStatus: string
  branchBoss: string
}

interface Comment {
  commentId: number
  commentText: string
  commentDishId: number
  commentAccountId: number
  commentRating: number
  parentCommentId: number | null
  isDeleted?: number
  deletedAt?: string
  createdAt: string
  updatedAt?: string
  replies?: Comment[]
  dishName?: string
  accountName?: string
}

interface Dish {
  dishId: number
  dishName: string
}

interface PageData {
  records: Comment[]
  total: number
  current: number
  size: number
  pages: number
}

// 响应式数据
const loading = ref(false)
const replyLoading = ref(false)
const currentBranch = ref<Branch | null>(null)
const commentList = ref<Comment[]>([])
const dishList = ref<Dish[]>([])

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 搜索参数
const searchForm = reactive({
  dishName: '',
  rating: ''
})

// 回复表单
const replyForm = reactive({
  commentParentId: 0,
  content: ''
})

const replyFormRef = ref<FormInstance>()
const replyDialogVisible = ref(false)
const currentComment = ref<Comment | null>(null)

// 评分选项
const ratingOptions = [
  { label: '全部评分', value: '' },
  { label: '1星', value: '1' },
  { label: '2星', value: '2' },
  { label: '3星', value: '3' },
  { label: '4星', value: '4' },
  { label: '5星', value: '5' }
]

// 回复表单验证规则
const replyRules = {
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' },
    { min: 1, max: 500, message: '回复内容长度在1到500个字符', trigger: 'blur' }
  ]
}

// 获取本地存储的accountId
const getAccountId = (): number | null => {
  const userInfo = StorageManager.getUserInfo()
  return userInfo ? userInfo.accountId : null
}

// 根据负责人查询分店信息
const fetchBranchInfo = async (): Promise<void> => {
  const accountId = getAccountId()
  if (!accountId) {
    ElMessage.error('未找到账户信息，请重新登录')
    return
  }

  try {
    loading.value = true
    const response = await axios.get(`${baseAPI}/branch/branch/by-boss/${accountId}`)
    
    if (response.data.code === 200 && response.data.data.length > 0) {
      currentBranch.value = response.data.data[0]
      await fetchDishList()
      await fetchCommentList()
    } else {
      ElMessage.warning('未找到您管理的分店信息')
    }
  } catch (error) {
    console.error('获取分店信息失败:', error)
    ElMessage.error('获取分店信息失败')
  } finally {
    loading.value = false
  }
}

// 获取分店菜品列表
const fetchDishList = async (): Promise<void> => {
  if (!currentBranch.value) return

  try {
    const response = await axios.get(`${baseAPI}/branch/dishes/branch/${currentBranch.value.branchId}/all`)
    
    if (response.data.code === 200) {
      dishList.value = response.data.data
    }
  } catch (error) {
    console.error('获取菜品列表失败:', error)
  }
}

// 获取评论列表
const fetchCommentList = async (): Promise<void> => {
  if (!currentBranch.value) return

  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.size,
      dishName: searchForm.dishName || undefined,
      rating: searchForm.rating || undefined
    }

    const response = await axios.get(`${baseAPI}/branch/comments/branch/${currentBranch.value.branchId}/with-replies`, { params })
    
    if (response.data.code === 200) {
      const pageData: PageData = response.data.data
      commentList.value = pageData.records
      pagination.total = pageData.total
      pagination.current = pageData.current
    } else {
      ElMessage.error(response.data.msg || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索评论
const handleSearch = (): void => {
  pagination.current = 1
  fetchCommentList()
}

// 重置搜索
const handleReset = (): void => {
  searchForm.dishName = ''
  searchForm.rating = ''
  pagination.current = 1
  fetchCommentList()
}

// 分页改变
const handlePageChange = (page: number): void => {
  pagination.current = page
  fetchCommentList()
}

const handleSizeChange = (size: number): void => {
  pagination.size = size
  pagination.current = 1
  fetchCommentList()
}

// 打开回复对话框
const openReplyDialog = (comment: Comment): void => {
  currentComment.value = comment
  replyForm.commentParentId = comment.commentId
  replyForm.content = ''
  replyDialogVisible.value = true
  
  // 清除之前的验证状态
  if (replyFormRef.value) {
    replyFormRef.value.clearValidate()
  }
}

// 关闭回复对话框
const closeReplyDialog = (): void => {
  replyDialogVisible.value = false
  replyForm.content = ''
  replyForm.commentParentId = 0
  currentComment.value = null
  
  if (replyFormRef.value) {
    replyFormRef.value.clearValidate()
  }
}

// 提交回复 - 修复版本
const submitReply = async (): Promise<void> => {
  if (!replyFormRef.value) return

  try {
    await replyFormRef.value.validate()
    replyLoading.value = true

    const accountId = getAccountId()
    if (!accountId) {
      ElMessage.error('未找到账户信息，请重新登录')
      replyLoading.value = false
      return
    }

    if (!currentComment.value) {
      ElMessage.error('评论信息缺失')
      replyLoading.value = false
      return
    }

    // 按照API文档要求构造完整的Comment对象
    const postData = {
      commentText: replyForm.content,
      commentDishId: currentComment.value.commentDishId, // 使用原评论的菜品ID
      commentAccountId: accountId,
      commentRating: 0, // 回复评论没有评分
      parentCommentId: replyForm.commentParentId, // 父评论ID
      isDeleted: 0,
      deletedAt: "",
      createdAt: "",
      updatedAt: "",
      replies: [],
      dishName: "",
      accountName: ""
    }

    console.log('发送回复请求:', postData) // 调试日志

    const response = await axios.post(`${baseAPI}/branch/comments/reply`, postData)
    
    if (response.data.code === 200) {
      ElMessage.success('回复成功')
      closeReplyDialog()
      await fetchCommentList()
    } else {
      ElMessage.error(response.data.msg || '回复失败')
    }
  } catch (error) {
    console.error('回复失败:', error)
    if (axios.isAxiosError(error)) {
      const errorMsg = error.response?.data?.msg || error.message || '网络错误'
      ElMessage.error(`回复失败: ${errorMsg}`)
    } else {
      ElMessage.error('回复失败')
    }
  } finally {
    replyLoading.value = false
  }
}

// 删除评论
const deleteComment = async (commentId: number): Promise<void> => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await axios.delete(`${baseAPI}/branch/comments/${commentId}`)
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      await fetchCommentList()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取评分星级显示
const getStarRating = (rating: number): string => {
  return '★'.repeat(rating) + '☆'.repeat(5 - rating)
}

// 格式化时间
const formatTime = (timeStr: string): string => {
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 获取菜品名称
const getDishName = (dishId: number): string => {
  const dish = dishList.value.find(d => d.dishId === dishId)
  return dish ? dish.dishName : '未知菜品'
}

// 页面初始化
onMounted(() => {
  fetchBranchInfo()
})
</script>

<template>
  <div class="review-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>评价管理</h2>
      <div v-if="currentBranch" class="branch-info">
        <el-tag type="primary" size="large">
          {{ currentBranch.branchName }}
        </el-tag>
        <span class="branch-address">{{ currentBranch.branchAddress }}</span>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <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: 120px"
          >
            <el-option
              v-for="option in ratingOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 评论列表 -->
    <el-card class="comment-card" shadow="never">
      <div v-loading="loading">
        <div v-if="commentList.length === 0" class="empty-state">
          <el-empty description="暂无评论数据" />
        </div>
        
        <div v-else class="comment-list">
          <div v-for="comment in commentList" :key="comment.commentId" class="comment-item">
            <!-- 主评论 -->
            <div class="main-comment">
              <div class="comment-header">
                <div class="user-info">
                  <el-avatar :size="40" :src="comment.accountName || ''" />
                  <div class="user-details">
                    <div class="username">{{ comment.accountName || '匿名用户' }}</div>
                    <div class="comment-time">{{ formatTime(comment.createdAt) }}</div>
                  </div>
                </div>
                <div class="rating">
                  <span class="stars">{{ getStarRating(comment.commentRating || 0) }}</span>
                  <span class="rating-text">{{ comment.commentRating || 0 }}分</span>
                </div>
              </div>
              
              <div class="dish-info">
                <el-tag size="small" type="info">{{ getDishName(comment.commentDishId) }}</el-tag>
              </div>
              
              <div class="comment-content">
                {{ comment.commentText }}
              </div>
              
              <div class="comment-actions">
                <el-button size="small" type="primary" text @click="openReplyDialog(comment)">
                  回复
                </el-button>
                <el-button size="small" type="danger" text @click="deleteComment(comment.commentId)">
                  删除
                </el-button>
              </div>
            </div>

            <!-- 回复列表 -->
            <div v-if="comment.replies && comment.replies.length > 0" class="replies">
              <div v-for="reply in comment.replies" :key="reply.commentId" class="reply-item">
                <div class="reply-header">
                  <div class="reply-user">
                    <el-avatar :size="30" :src="reply.accountName || ''" />
                    <span class="reply-username">{{ reply.accountName || '商家' }}</span>
                    <el-tag size="small" type="success">回复</el-tag>
                  </div>
                  <div class="reply-time">{{ formatTime(reply.createdAt) }}</div>
                </div>
                <div class="reply-content">{{ reply.commentText }}</div>
                <div class="reply-actions">
                  <el-button size="small" type="danger" text @click="deleteComment(reply.commentId)">
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

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

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复评论"
      width="500px"
      :close-on-click-modal="false"
      @close="closeReplyDialog"
    >
      <div v-if="currentComment" class="reply-dialog-content">
        <div class="original-comment">
          <div class="original-comment-header">
            <span class="label">原评论:</span>
            <span class="dish-name">{{ getDishName(currentComment.commentDishId) }}</span>
            <span class="rating">{{ getStarRating(currentComment.commentRating || 0) }}</span>
          </div>
          <div class="original-comment-text">{{ currentComment.commentText }}</div>
        </div>

        <el-form ref="replyFormRef" :model="replyForm" :rules="replyRules">
          <el-form-item label="回复内容" prop="content">
            <el-input
              v-model="replyForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容..."
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeReplyDialog">取消</el-button>
          <el-button type="primary" @click="submitReply" :loading="replyLoading">
            发送回复
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.review-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.branch-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.branch-address {
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

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

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.comment-list {
  space-y: 16px;
}

.comment-item {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.comment-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.main-comment {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e4e7ed;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.username {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.rating {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stars {
  color: #f7ba2a;
  font-size: 16px;
}

.rating-text {
  color: #606266;
  font-size: 14px;
}

.dish-info {
  margin-bottom: 12px;
}

.comment-content {
  color: #303133;
  line-height: 1.6;
  margin-bottom: 12px;
  word-break: break-word;
}

.comment-actions {
  display: flex;
  gap: 8px;
}

.replies {
  margin-top: 16px;
  padding-left: 20px;
  border-left: 3px solid #e4e7ed;
}

.reply-item {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 8px;
}

.reply-item:last-child {
  margin-bottom: 0;
}

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

.reply-user {
  display: flex;
  align-items: center;
  gap: 8px;
}

.reply-username {
  font-weight: 500;
  color: #303133;
  font-size: 13px;
}

.reply-time {
  color: #909399;
  font-size: 12px;
}

.reply-content {
  color: #303133;
  line-height: 1.5;
  margin-bottom: 8px;
  font-size: 14px;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.reply-dialog-content {
  space-y: 16px;
}

.original-comment {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 20px;
}

.original-comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.label {
  font-weight: 600;
  color: #606266;
  font-size: 13px;
}

.dish-name {
  color: #409eff;
  font-size: 13px;
}

.original-comment-text {
  color: #303133;
  line-height: 1.5;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>