<template>
  <div class="detail-page">
    <el-row :gutter="30" style="margin-top: 20px;">
      <!-- 左侧菜品信息 -->
      <el-col :sm="24" :md="12">
        <el-card v-if="product" class="product-card">
          <div class="product-image-container">
            <img :src="product.imageUrl" class="product-image" />
          </div>
          <h1 class="product-name">{{ product.dishName }}</h1>
          <div class="product-price">
            <span class="price-label">价格：</span>
            <span class="price-value">{{ product.price }}</span>
          </div>
              <!-- 菜品标签 -->
<div class="product-tags" style="margin: 8px 0;">
  <span class="tag-label">标签：</span>
  <el-tag 
    v-for="tag in tagList" 
    :key="tag" 
    type="success" 
    style="margin-right: 6px;"
  >
    {{ tag }}
  </el-tag>
</div>
<!-- 显示库存 -->
<div class="product-stock" style="margin: 8px 0;">
  <span class="stock-label">库存：</span>
  <el-tag type="info">
    {{ product.stock }} 件
  </el-tag>
</div>
    <!-- 菜品状态 -->
 <div class="product-status" style="margin: 8px 0;">
  <span class="status-label">状态：</span>
  <el-tag :type="product.status === '在售' ? 'success' : 'danger'">
    {{ product.status }}
  </el-tag>
</div>

          <div class="product-desc">
            <h3>菜品描述</h3>
            <p>{{ product.description }}</p>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="openAddDialog">
            <el-icon><ShoppingCart /></el-icon> 添加到购物车
            </el-button>
            <!-- 添加到购物车弹窗 -->
<el-dialog v-model="dialogVisible" title="添加到购物车" width="30%">
  <div style="margin-bottom: 16px;">
    <span>菜品：{{ product?.dishName }}</span>
  </div>
  <!-- 显示库存 -->
  <div class="product-stock" style="margin: 8px 0;">
  <span class="stock-label">库存：</span>
  <el-tag type="info">
    {{ product.stock }} 件
  </el-tag>
</div>
  <div>
    <span>数量：</span>
    <el-input-number v-model="addQuantity" :min="1" />
  </div>
  <template #footer>
    <el-button @click="dialogVisible = false">取消</el-button>
    <el-button type="primary" @click="confirmAddToCart">确认添加</el-button>
  </template>
</el-dialog>
            <el-button @click="goBack">
              <el-icon><ArrowLeft /></el-icon> 返回
            </el-button>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧评论区 -->
      <el-col :sm="24" :md="12">
        <el-card class="comment-card">
          <div class="comment-header">
            <h2>用户评论</h2>
            <div class="rating-stats">
<el-rate :model-value="averageRating" disabled />
<span class="rating-count">{{ commentCount }} 条评论</span>

            </div>
          </div>
          
          <el-divider />
          
          <!-- 评论表单 -->
          <div class="comment-form">
            <h3>发表评论</h3>
          
            <el-form :model="commentForm" label-width="80px">
              <el-form-item label="评分">
                <el-rate v-model="commentForm.rating" />
              </el-form-item>
              <el-form-item label="评论内容">
                <el-input
                  v-model="commentForm.content"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入您的评论..."
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitComment">提交评论</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <el-divider />
          
          <!-- 评论列表（支持主评论 + 子评论 + 回复输入框） -->
<div class="comment-list">
  <div v-for="comment in groupedComments" :key="comment.commentId" class="comment-item">
    <!-- 主评论 -->
    <div class="comment-user">
      <span class="user-name">{{ comment.username || '加载中...' }}</span>
      <el-rate v-model="comment.commentRating" disabled size="small" />
      <span class="comment-time">{{ comment.createdAt }}</span>
    </div>
    <div class="comment-content">{{ comment.commentText }}</div>

    <!-- 回复按钮 -->
    <el-button
      size="small"
      type="text"
      @click="toggleReply(comment.commentId)"
    >回复</el-button>

    <!-- 回复输入框（不含评分） -->
    <div
      v-if="activeReplyId === comment.commentId"
      class="reply-box"
      style="margin: 10px 0 10px 30px;"
    >
      <el-input
        v-model="replyContent"
        type="textarea"
        rows="2"
        placeholder="请输入回复内容"
      />
      <el-button type="primary" size="small" @click="submitReply(comment)">提交</el-button>
      <el-button size="small" @click="cancelReply">取消</el-button>
    </div>

    <!-- 子评论列表 -->
    <div
      v-for="reply in comment.replies"
      :key="reply.commentId"
      class="reply-item"
      style="margin-left: 30px; margin-top: 8px;"
    >
      <div class="comment-user">
        <span class="user-name">{{ reply.username || '加载中...' }}</span>
        
        <span class="comment-time">{{ reply.createdAt }}</span>
      </div>
      <div class="comment-content">{{ reply.commentText }}</div>
    </div>
  </div>
</div>

        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';
interface Dish {
  dishId: number;
  dishName: string;
  category: string;
  price: number;
  stock: number;
  status: string;
  description: string;
  imageUrl: string;
  sales: number;
  tag:string;
}

interface Comment {
  commentId: number;
  parentCommentId: number;// 父评论ID，用于回复功能
  commentText: string;
  commentDishId: number;
  commentAccountId: string;
  commentRating: number;
  createdAt: string;
}

const route = useRoute();
const router = useRouter();
const productId = ref<number | null>(null);
const comments = ref<Comment[]>([]); 
const product = ref<Dish | null>(null);
const commentForm = ref({ rating: 0, content: '' });
const activeReplyId = ref<number | null>(null);
const replyContent = ref('');

import { useCartStore } from '@/userStores/cart'
const cartStore = useCartStore()

import { useUserStore } from '@/userStores/user'
const userStore = useUserStore()

const dialogVisible = ref(false)
const addQuantity = ref(1)

const openAddDialog = () => {
  if (product.value?.status === '停售') {
    ElMessage.warning('该菜品已停售，无法添加到购物车')
    return
  }
  addQuantity.value = 1 // 默认数量为1
  dialogVisible.value = true
}
// 获取用户名
async function fetchUsername(comment: any) {
  try {
    const response = await axios.get(`/api/user/customers/${userStore.getUserId}`)//ok
    comment.username = response.data.accountName
  } catch (error) {
    console.error('获取用户名失败:', error)
    comment.username = '未知用户'
  }
}

// 页面加载时获取菜品ID并获取相关数据
onMounted(async () => {
 const id = parseInt(route.params.id as string, 10);
  console.log('准备加载菜品 id:', id);
  productId.value = id;
  loadProductDetail(id);
 await loadComments(id);
  comments.value.forEach(fetchUsername);
});

// 获取菜品详情（API请求）
const loadProductDetail = async (dishId: number) => {
  try {
    const response = await axios.get(`/api/user/dishes/${dishId}`);//ok
    console.log('获取到的菜品信息：', response.data);
    product.value = response.data;  // 假设 API 返回的数据结构与前端匹配
  } catch (error) {
    console.error('获取菜品信息失败:', error);
  }
};
// 假设 product 是一个响应式对象（由 props 或 API 加载）
const tagList = computed(() => {
  return product.value?.tag
    ? product.value.tag.split(/[,，]/).map(t => t.trim()).filter(t => t.length > 0)
    : [];
});
// 获取评论数据（API请求）
const loadComments = async (dishId: number) => {
  try {
    const response = await axios.get(`/api/user/comments/dish/${dishId}`);
    comments.value = response.data.map((c: any) => ({
      ...c,
      commentRating: Number(c.commentRating),
      parentCommentId: c.parentCommentId != null ? Number(c.parentCommentId) : 0,
    }));
  } catch (error) {
    console.error('获取评论失败:', error);
  }
};

// 计算属性 - 评论数量
const commentCount = computed(() => comments.value.length);

// 计算属性 - 平均评分
const averageRating = computed(() => {
  if (commentCount.value === 0) return 0;
  const total = comments.value.reduce((sum, c) => sum + Number(c.commentRating || 0), 0);
  return total / commentCount.value;
});

const confirmAddToCart = () => {
  if (product.value) {
    if (addQuantity.value > product.value.stock) {
      ElMessage.error('购买数量不能超过库存数量')
      return
    }

    cartStore.addToCart({
      id: product.value.dishId,
      name: product.value.dishName,
      price: product.value.price,
      quantity: addQuantity.value,
      imageUrl: product.value.imageUrl,
    })

    ElMessage.success(`已添加 ${addQuantity.value} 份到购物车`)
    dialogVisible.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.push({ name: 'type' });
};

//提交评论
const submitComment = async () => {
  if (!productId.value) return;
  try {
    await axios.post('/api/user/comments/add', {//ok
      commentDishId: productId.value,
      commentText: commentForm.value.content,
      commentRating: commentForm.value.rating,
      commentAccountId: userStore.getUserId, // 模拟账号
    });
    ElMessage.success('评论提交成功');
    commentForm.value = { rating: 0, content: '' };
    loadComments(productId.value);
    location.reload();
  } catch (error) {
    ElMessage.error('评论提交失败');
    console.error(error);
  }
};

// 计算属性：将评论分组为主评论和对应的回复列表
const groupedComments = computed(() => {
  const mainComments = comments.value.filter(c => c.parentCommentId === 0); // 主评论
  const replies = comments.value.filter(c => c.parentCommentId !== 0);      // 回复

  return mainComments.map(main => ({
    ...main,
    replies: replies.filter(reply => reply.parentCommentId === main.commentId),
  }));
});

const toggleReply = (commentId: number) => {
  activeReplyId.value = activeReplyId.value === commentId ? null : commentId
  replyContent.value = ''
}

const cancelReply = () => {
  activeReplyId.value = null
  replyContent.value = ''
}
// 提交子评论（回复）
const submitReply = async (parent: Comment) => {
  if (!replyContent.value.trim() || !productId.value) return;

  try {
    // 向后端发送 POST 请求，提交一条“回复”类型的评论
    await axios.post('/api/user/comments/add', {
      commentDishId: productId.value,           // 所属菜品 ID
      commentText: replyContent.value,          // 回复内容
      commentAccountId: userStore.getUserId,    // 当前用户 ID
      parentCommentId: parent.commentId,        // 指定这是一条回复，指向主评论 ID
    });

    ElMessage.success('回复提交成功');

    // 重置输入框
    replyContent.value = '';
    activeReplyId.value = null;

    // 重新加载评论列表
    loadComments(productId.value);
    location.reload();
  } catch (error) {
    ElMessage.error('回复提交失败');
    console.error(error);
  }
};
</script>

<style scoped>
.detail-page {
  padding: 20px;
}

.product-card {
  height: 100%;
  background-color: #fff8e1; /* 浅黄色背景 */
  padding: 20px;
  border-radius: 8px;
}
::v-deep(.product-card .el-button--primary) {
  background-color: #fccc0a;
  border-color: #fccc0a;
  color: #000;
}
::v-deep(.el-button--primary) {
  background-color: #fccc0a;
  border-color: #fccc0a;
  color: #000;
}
.product-image-container {
  width: 100%;
  height: 300px;
  overflow: hidden;
  border-radius: 4px;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-image:hover {
  transform: scale(1.05);
}

.product-name {
  font-size: 24px;
  margin: 15px 0;
  color: #303133;
}

.product-price {
  font-size: 28px;
  font-weight: bold;
  color: #f56c6c;
  margin: 15px 0;
}

.price-label {
  font-size: 18px;
  color: #606266;
  margin-right: 10px;
}

.product-desc {
  margin: 20px 0;
  line-height: 1.8;
}

.product-desc h3 {
  font-size: 18px;
  margin-bottom: 10px;
  color: #303133;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.comment-card {
  height: 100%;
}

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

.comment-header h2 {
  font-size: 20px;
  color: #303133;
}

.rating-stats {
  display: flex;
  align-items: center;
}

.rating-count {
  margin-left: 10px;
  color: #606266;
}

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

.comment-list {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 10px;
}

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

.comment-user {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-name {
  font-weight: bold;
  color: #303133;
}

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

.comment-content {
  color: #606266;
  line-height: 1.6;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .product-image-container {
    height: 200px;
  }
  
  .product-name {
    font-size: 20px;
  }
  
  .product-price {
    font-size: 24px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>