<template>
  <div class="comments-page">
    <div class="page-header">
      <h2>评论管理</h2>
      <div class="header-stats">
        <span>未读: {{ stats.unreadCount }}</span>
        <span>待回复: {{ stats.unrepliedCount }}</span>
      </div>
    </div>
    
    <!-- 当前作品信息 -->
    <div v-if="currentWork" class="page-card current-work-card">
      <div class="work-preview">
        <img :src="currentWork.coverUrl" class="work-cover" />
        <div class="work-info">
          <div class="work-title">{{ currentWork.title || '无标题' }}</div>
          <div class="work-meta">
            <el-tag size="small">{{ getPlatformName(currentWork.platform) }}</el-tag>
            <span>{{ formatDate(currentWork.publishTime) }}</span>
            <span>{{ currentWork.commentCount }} 条评论</span>
          </div>
        </div>
        <el-button type="primary" link @click="clearWorkFilter">
          查看全部评论
        </el-button>
      </div>
    </div>
    
    <div class="page-card filter-bar">
      <el-select 
        v-model="filter.workId" 
        placeholder="选择作品" 
        clearable 
        filterable 
        style="width: 250px"
        @change="onWorkChange"
      >
        <el-option
          v-for="work in works"
          :key="work.id"
          :label="`${work.title || '无标题'} (${getPlatformName(work.platform)})`"
          :value="work.id"
        />
      </el-select>
      <el-select v-model="filter.accountId" placeholder="账号" clearable style="width: 180px">
        <el-option
          v-for="account in accounts"
          :key="account.id"
          :label="`${account.accountName} (${getPlatformName(account.platform)})`"
          :value="account.id"
        />
      </el-select>
      <el-select v-model="filter.isRead" placeholder="状态" clearable style="width: 120px">
        <el-option label="未读" :value="false" />
        <el-option label="已读" :value="true" />
      </el-select>
      <el-input v-model="filter.keyword" placeholder="搜索评论" clearable style="width: 200px" />
      <el-button type="primary" @click="loadComments">搜索</el-button>
      <el-button @click="markAllAsRead">全部标记已读</el-button>
    </div>
    
    <div class="page-card">
      <div class="comment-list" v-loading="loading">
        <div v-if="comments.length === 0" class="empty-state">
          <el-empty :description="currentWork ? '该作品暂无评论' : '暂无评论'" />
        </div>
        
        <div v-else v-for="comment in comments" :key="comment.id" class="comment-item">
          <el-avatar :size="40" :src="comment.authorAvatar || undefined">
            {{ comment.authorName?.[0] }}
          </el-avatar>
          
          <div class="comment-content">
            <div class="comment-header">
              <span class="author-name">{{ comment.authorName }}</span>
              <span class="comment-time">{{ formatDate(comment.commentTime) }}</span>
              <el-tag v-if="!comment.isRead" type="danger" size="small">未读</el-tag>
            </div>
            
            <!-- 显示评论所属作品 -->
            <div v-if="!currentWork && comment.videoTitle" class="comment-work">
              <span class="work-label">作品:</span>
              <span class="work-name" @click="filterByWork(comment)">{{ comment.videoTitle }}</span>
            </div>
            
            <div class="comment-text">{{ comment.content }}</div>
            
            <div v-if="comment.replyContent" class="reply-content">
              <strong>已回复:</strong> {{ comment.replyContent }}
            </div>
            
            <div class="comment-footer">
              <span class="platform-info">
                {{ getPlatformName(comment.platform) }} · {{ comment.likeCount }} 赞
              </span>
              <div class="comment-actions">
                <el-button
                  v-if="!comment.replyContent"
                  type="primary"
                  link
                  size="small"
                  @click="openReplyDialog(comment)"
                >
                  回复
                </el-button>
                <el-button
                  v-if="!comment.isRead"
                  type="primary"
                  link
                  size="small"
                  @click="markAsRead(comment.id)"
                >
                  标记已读
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        style="margin-top: 20px"
        @change="loadComments"
      />
    </div>
    
    <!-- 回复对话框 -->
    <el-dialog v-model="showReplyDialog" title="回复评论" width="500px">
      <div class="reply-original">
        <strong>原评论:</strong>
        <p>{{ replyTarget?.content }}</p>
      </div>
      <el-input
        v-model="replyContent"
        type="textarea"
        :rows="4"
        placeholder="输入回复内容"
      />
      <template #footer>
        <el-button @click="showReplyDialog = false">取消</el-button>
        <el-button type="primary" @click="handleReply" :loading="replying">
          回复
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '@/api/request';
import { accountsApi } from '@/api/accounts';
import { PLATFORMS } from '@media-manager/shared';
import type { Comment, PlatformAccount, PlatformType, CommentStats, Work } from '@media-manager/shared';
import dayjs from 'dayjs';

const route = useRoute();
const router = useRouter();

const loading = ref(false);
const replying = ref(false);
const showReplyDialog = ref(false);

const comments = ref<Comment[]>([]);
const accounts = ref<PlatformAccount[]>([]);
const works = ref<Work[]>([]);
const stats = ref<CommentStats>({ totalCount: 0, unreadCount: 0, unrepliedCount: 0, todayCount: 0 });
const replyTarget = ref<Comment | null>(null);
const replyContent = ref('');

const filter = reactive({
  workId: undefined as number | undefined,
  accountId: undefined as number | undefined,
  isRead: undefined as boolean | undefined,
  keyword: '',
});

// 当前选中的作品
const currentWork = computed(() => {
  if (!filter.workId) return null;
  return works.value.find(w => w.id === filter.workId) || null;
});

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0,
});

function getPlatformName(platform: PlatformType) {
  return PLATFORMS[platform]?.name || platform;
}

function formatDate(date: string) {
  return dayjs(date).format('YYYY-MM-DD HH:mm');
}

async function loadComments() {
  loading.value = true;
  try {
    const result = await request.get('/api/comments', {
      params: {
        page: pagination.page,
        pageSize: pagination.pageSize,
        workId: filter.workId,
        accountId: filter.accountId,
        isRead: filter.isRead,
        keyword: filter.keyword || undefined,
      },
    });
    comments.value = result.items;
    pagination.total = result.total;
  } catch {
    // 错误已处理
  } finally {
    loading.value = false;
  }
}

async function loadStats() {
  try {
    stats.value = await request.get('/api/comments/stats');
  } catch {
    // 错误已处理
  }
}

async function loadAccounts() {
  try {
    accounts.value = await accountsApi.getAccounts();
  } catch {
    // 错误已处理
  }
}

async function loadWorks() {
  try {
    const result = await request.get('/api/works', {
      params: { pageSize: 100 },
    });
    works.value = result.items || [];
  } catch {
    // 错误已处理
  }
}

function onWorkChange() {
  pagination.page = 1;
  loadComments();
  // 更新 URL
  if (filter.workId) {
    router.replace({ query: { workId: filter.workId } });
  } else {
    router.replace({ query: {} });
  }
}

function clearWorkFilter() {
  filter.workId = undefined;
  router.replace({ query: {} });
  loadComments();
}

function filterByWork(comment: Comment) {
  if (comment.workId) {
    filter.workId = comment.workId;
    router.replace({ query: { workId: comment.workId } });
    loadComments();
  }
}

function openReplyDialog(comment: Comment) {
  replyTarget.value = comment;
  replyContent.value = '';
  showReplyDialog.value = true;
}

async function handleReply() {
  if (!replyTarget.value || !replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容');
    return;
  }
  
  replying.value = true;
  try {
    await request.post('/api/comments/reply', {
      commentId: replyTarget.value.id,
      content: replyContent.value,
    });
    ElMessage.success('回复成功');
    showReplyDialog.value = false;
    loadComments();
    loadStats();
  } catch {
    // 错误已处理
  } finally {
    replying.value = false;
  }
}

async function markAsRead(commentId: number) {
  try {
    await request.post('/api/comments/read', { commentIds: [commentId] });
    loadComments();
    loadStats();
  } catch {
    // 错误已处理
  }
}

async function markAllAsRead() {
  const unreadIds = comments.value.filter(c => !c.isRead).map(c => c.id);
  if (unreadIds.length === 0) return;
  
  try {
    await request.post('/api/comments/read', { commentIds: unreadIds });
    ElMessage.success('已全部标记为已读');
    loadComments();
    loadStats();
  } catch {
    // 错误已处理
  }
}

onMounted(() => {
  // 从 URL 获取 workId
  if (route.query.workId) {
    filter.workId = parseInt(route.query.workId as string);
  }
  
  loadWorks();
  loadComments();
  loadStats();
  loadAccounts();
});
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  
  h2 { margin: 0; }
  
  .header-stats {
    display: flex;
    gap: 20px;
    color: $text-secondary;
  }
}

.filter-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.comment-list {
  min-height: 200px;
}

.comment-item {
  display: flex;
  gap: 16px;
  padding: 16px 0;
  border-bottom: 1px solid $border-lighter;
  
  &:last-child { border-bottom: none; }
  
  .comment-content {
    flex: 1;
    
    .comment-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
      
      .author-name { font-weight: 500; }
      .comment-time { font-size: 12px; color: $text-secondary; }
    }
    
    .comment-text {
      color: $text-primary;
      line-height: 1.6;
    }
    
    .reply-content {
      margin-top: 12px;
      padding: 12px;
      background: $bg-base;
      border-radius: 4px;
      font-size: 14px;
      color: $text-regular;
    }
    
    .comment-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 12px;
      
      .platform-info {
        font-size: 12px;
        color: $text-secondary;
      }
    }
  }
}

.reply-original {
  margin-bottom: 16px;
  padding: 12px;
  background: $bg-base;
  border-radius: 4px;
  
  p { margin: 8px 0 0; }
}

.current-work-card {
  margin-bottom: 20px;
  
  .work-preview {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .work-cover {
      width: 80px;
      height: 45px;
      object-fit: cover;
      border-radius: 4px;
      background: #f0f0f0;
    }
    
    .work-info {
      flex: 1;
      
      .work-title {
        font-weight: 500;
        margin-bottom: 4px;
      }
      
      .work-meta {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 12px;
        color: $text-secondary;
      }
    }
  }
}

.comment-work {
  margin: 4px 0 8px;
  font-size: 12px;
  
  .work-label {
    color: $text-secondary;
  }
  
  .work-name {
    color: $primary-color;
    cursor: pointer;
    
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
