<template>
  <div class="dynamic-management-container">
    <!-- 头部：Tabs和发布按钮 -->
    <div class="header-section">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="推荐" name="recommend" />
        <el-tab-pane label="关注" name="follow" />
      </el-tabs>
      <div class="action-buttons">
        <el-button type="primary" @click="handlePublish"> 发布动态 </el-button>
      </div>
    </div>
    <!-- 动态列表（推荐和关注共用） -->
    <div v-if="dynamicList.length > 0" class="content-section">
      <div class="dynamic-grid">
        <div v-for="item in paginatedList" :key="item.id" class="dynamic-card" @click="handleCardClick(item)">
          <!-- 图片/视频区域 -->
          <div class="dynamic-image-wrapper">
            <!-- 视频 -->
            <video v-if="item.isVideo && item.imageUrl" :src="item.imageUrl" class="dynamic-image" controls preload="metadata" />
            <!-- 图片 -->
            <img v-else-if="item.imageUrl" :src="item.imageUrl" :alt="item.title" class="dynamic-image" />
            <!-- 占位符 -->
            <div v-else class="image-placeholder">
              <el-icon :size="48" color="#999">
                <Picture />
              </el-icon>
            </div>
          </div>

          <!-- 动态内容 -->
          <div class="dynamic-content">
            <div class="dynamic-text">
              {{ item.title }}
            </div>

            <!-- 用户信息和点赞 -->
            <div class="dynamic-footer">
              <div class="user-info">
                <div class="user-avatar">
                  <img v-if="item.userAvatar" :src="item.userAvatar" :alt="item.userName" />
                  <el-icon v-else :size="24">
                    <Avatar />
                  </el-icon>
                </div>
                <span class="user-name">{{ item.userName }}</span>
              </div>

              <div class="like-section" @click.stop="handleLike(item)">
                <i class="iconfont icon-dianzanb" :style="{ fontSize: '18px', color: item.isLike == '1' ? '#f56c6c' : '#999' }" />
                <span class="like-count">{{ item.dianzanCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-section">
      <el-empty :description="activeTab === 'follow' ? '暂无关注的动态' : '暂无动态数据'" />
    </div>

    <!-- 分页 -->
    <div v-if="dynamicList.length > 0" class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 动态详情 Drawer -->
    <el-drawer
      v-model="detailDrawerVisible"
      direction="rtl"
      size="90%"
      :show-close="false"
      destroy-on-close
      class="detail-drawer"
    >
      <template #header>
        <div class="drawer-header">
          <el-button class="close-btn" text @click="handleCloseDetail">
            <el-icon :size="24">
              <Close />
            </el-icon>
          </el-button>
        </div>
      </template>

      <div v-if="currentDetail" class="detail-content">
        <!-- 主内容区域 -->
        <div class="detail-main">
          <!-- 图片/视频轮播展示 -->
          <div class="media-container">
            <!-- 多媒体轮播 -->
            <el-carousel
              v-if="currentDetail.mediaList && currentDetail.mediaList.length > 0"
              :autoplay="false"
              :loop="false"
              indicator-position="outside"
              arrow="always"
              height="100%"
              class="media-carousel"
              @change="handleCarouselChange"
            >
              <el-carousel-item v-for="(media, index) in currentDetail.mediaList" :key="index">
                <!-- 视频 -->
                <video
                  v-if="media.type === 'video'"
                  :ref="el => setVideoRef(el, index)"
                  :src="media.url"
                  class="detail-media detail-video"
                  controls
                  preload="metadata"
                  @play="handleVideoPlay(index)"
                />
                <!-- 图片 -->
                <img v-else :src="media.url" :alt="currentDetail.title" class="detail-media detail-image" />
              </el-carousel-item>
            </el-carousel>
            <!-- 占位符 -->
            <div v-else class="media-placeholder">
              <el-icon :size="80" color="#dcdfe6">
                <Picture />
              </el-icon>
            </div>
            <!-- 媒体计数指示器 -->
            <div v-if="currentDetail.mediaList && currentDetail.mediaList.length > 1" class="media-counter">
              {{ currentCarouselIndex + 1 }} / {{ currentDetail.mediaList.length }}
            </div>
          </div>

          <!-- 底部信息 -->
          <div class="detail-info">
            <div class="author-info">
              <div class="author-avatar">
                <img
                  v-if="currentDetail.author?.avatar || currentDetail.userAvatar"
                  :src="currentDetail.author?.avatar || currentDetail.userAvatar"
                  :alt="currentDetail.author?.name || currentDetail.userName"
                />
                <el-icon v-else :size="32">
                  <Avatar />
                </el-icon>
              </div>
              <div class="author-details">
                <div class="author-name">@{{ currentDetail.author?.name || currentDetail.userName }}</div>
                <div class="publish-time">
                  {{ currentDetail.createdTime }}
                </div>
              </div>
            </div>
            <div style="padding-bottom: 10px; color: #ffffff">
              {{ currentDetail.title }}
            </div>
            <div class="detail-description">
              <p
                v-if="isDescriptionExpanded || (currentDetail.context && currentDetail.context.length >= 20)"
                :class="{ 'text-ellipsis': !isDescriptionExpanded }"
              >
                {{ currentDetail.context }}
              </p>
              <span v-if="currentDetail.context" class="expand-btn" @click="toggleDescription">
                {{ isDescriptionExpanded ? "收起" : "展开" }}
              </span>
            </div>
          </div>
        </div>

        <!-- 右侧操作栏 -->
        <div class="action-bar">
          <!-- 作者头像 -->
          <div class="action-item author-action">
            <div class="action-avatar" @click="handleViewUserProfile">
              <img
                v-if="currentDetail.author?.avatar || currentDetail.userAvatar"
                :src="currentDetail.author?.avatar || currentDetail.userAvatar"
                :alt="currentDetail.author?.name || currentDetail.userName"
              />
              <el-icon v-else :size="40" color="#fff">
                <Avatar />
              </el-icon>
              <!-- 关注按钮 (定位在头像右下角) -->
              <div v-if="currentDetail.isFollowThis == 0 && !isMyDynamic" class="follow-badge" @click.stop="handleFollowInDetail">
                <el-icon :size="16" color="#fff">
                  <Plus />
                </el-icon>
              </div>
            </div>
          </div>

          <!-- 点赞 -->
          <div class="action-item" @click="handleDetailLike">
            <div class="action-icon">
              <i
                class="iconfont icon-dianzanb"
                :style="{ fontSize: '28px', color: currentDetail.isLike == '1' ? '#f56c6c' : '#fff' }"
              />
            </div>
            <div class="action-count">
              {{ currentDetail.dianzanCount }}
            </div>
          </div>

          <!-- 评论 -->
          <div class="action-item" @click="handleShowComments">
            <div class="action-icon">
              <el-icon :size="28" color="#fff">
                <ChatDotRound />
              </el-icon>
            </div>
            <div class="action-count">
              {{ currentDetail.commentCount }}
            </div>
          </div>

          <!-- 分享 -->
          <div class="action-item" @click="handleShare">
            <div class="action-icon">
              <el-icon :size="28" color="#fff">
                <Share />
              </el-icon>
            </div>
            <div class="action-count">分享</div>
          </div>

          <!-- 更多 -->
          <el-popover placement="left" :width="120" trigger="click" popper-class="more-actions-popover">
            <template #reference>
              <div class="action-item">
                <div class="action-icon">
                  <el-icon :size="28" color="#fff">
                    <MoreFilled />
                  </el-icon>
                </div>
              </div>
            </template>
            <div class="more-actions-menu">
              <!-- 如果是当前用户的动态，显示编辑和删除 -->
              <template v-if="isMyDynamic">
                <div class="menu-item" style="display: flex; align-items: center; cursor: pointer" @click="handleDeleteDynamic">
                  <el-icon :size="18">
                    <Delete /> </el-icon
                  >&nbsp;&nbsp;
                  <span>删除</span>
                </div>
              </template>
              <!-- 如果不是当前用户的动态，显示举报和拉黑 -->
              <template v-else>
                <div
                  class="menu-item"
                  style="display: flex; align-items: center; padding-bottom: 10px; cursor: pointer"
                  @click="handleReportDynamic"
                >
                  <el-icon :size="18">
                    <Warning /> </el-icon
                  >&nbsp;&nbsp;
                  <span>举报</span>
                </div>
                <div class="menu-item" style="display: flex; align-items: center; cursor: pointer" @click="handleBlockUserClick">
                  <el-icon :size="18">
                    <CircleClose /> </el-icon
                  >&nbsp;&nbsp;
                  <span>拉黑</span>
                </div>
              </template>
            </div>
          </el-popover>
        </div>
      </div>
    </el-drawer>

    <!-- 评论侧边栏 -->
    <el-drawer v-model="commentDrawerVisible" title="评论" direction="rtl" size="400px" destroy-on-close>
      <!-- 评论列表 -->
      <div class="comment-list-container">
        <div v-if="commentListData.length > 0" class="comment-list">
          <div v-for="comment in commentListData" :key="comment.id" class="comment-item">
            <div class="comment-avatar">
              <img v-if="comment.userImage" :src="comment.userImage" :alt="comment.userName" />
              <el-icon v-else :size="32">
                <Avatar />
              </el-icon>
            </div>
            <div class="comment-content-wrapper">
              <div class="comment-header">
                <span class="comment-user-name">{{ comment.userName }}</span>
              </div>
              <div class="comment-text">
                {{ comment.commentContent }}
              </div>

              <div class="comment-actions">
                <span class="comment-action-item" @click="handleLikeComment(comment)">
                  <i class="iconfont icon-dianzanb" :style="{ fontSize: '16px', color: comment.isLiked ? '#f56c6c' : '#999' }" />
                  <span>{{ comment.likeCount || 0 }}</span>
                </span>
                <span class="comment-action-item" @click="handleReplyComment(comment)">
                  <el-icon :size="16">
                    <ChatDotRound />
                  </el-icon>
                  <span>回复</span>
                </span>
              </div>
              <!-- 商家回复 -->
              <div v-for="item in comment.storeComment" :key="item.id" class="store-comment-wrapper">
                <div class="store-comment-item">
                  <div class="store-comment-avatar">
                    <img v-if="item.userImage" :src="item.userImage" :alt="item.userName" />
                    <el-icon v-else :size="24">
                      <Avatar />
                    </el-icon>
                  </div>
                  <div class="store-comment-content">
                    <div class="store-comment-header">
                      <span class="store-comment-user-name">{{ item.userName || "商家" }}</span>
                      <span class="store-comment-time">{{ item.createdTime || item.createDate }}</span>
                    </div>
                    <div class="store-comment-text">
                      {{ item.commentContent }}
                      <span
                        class="comment-action-item"
                        @click="handleLikeComment(item)"
                        style="display: flex; align-items: center"
                      >
                        <i
                          class="iconfont icon-dianzanb"
                          :style="{ fontSize: '16px', color: item.isLiked ? '#f56c6c' : '#999' }"
                        />&nbsp;
                        <span>{{ item.likeCount || 0 }}</span>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无评论" />
      </div>

      <!-- 评论输入框 -->
      <div class="comment-input-wrapper">
        <!-- 回复提示 -->
        <div v-if="replyingComment" class="reply-hint">
          <span class="reply-text">回复 @{{ replyingComment.userName }}</span>
          <el-icon class="cancel-reply" @click="handleCancelReply">
            <Close />
          </el-icon>
        </div>
        <el-input
          v-model="commentInput"
          type="textarea"
          :rows="3"
          :placeholder="replyingComment ? '输入回复内容...' : '你要评论点什么呢~'"
          maxlength="500"
          show-word-limit
        />
        <el-button type="primary" :loading="commentSubmitting" @click="handleSubmitComment">
          {{ replyingComment ? "回复" : "发送" }}
        </el-button>
      </div>
    </el-drawer>

    <!-- 举报对话框 -->
    <el-dialog v-model="reportDialogVisible" title="举报理由" width="500px" destroy-on-close @close="handleCloseReportDialog">
      <div class="report-dialog-content">
        <div class="report-tip">请选择最符合的原因，以便于我们进行的处理</div>

        <!-- 举报原因选项 -->
        <div class="report-reasons">
          <el-radio-group v-model="reportForm.reason">
            <el-radio label="用户违规"> 用户违规 </el-radio>
            <el-radio label="色情低俗"> 色情低俗 </el-radio>
            <el-radio label="违法违规"> 违法违规 </el-radio>
            <el-radio label="侮辱谩骂、煽动对立"> 侮辱谩骂、煽动对立 </el-radio>
            <el-radio label="涉嫌诈骗"> 涉嫌诈骗 </el-radio>
            <el-radio label="人身攻击"> 人身攻击 </el-radio>
            <el-radio label="种族歧视"> 种族歧视 </el-radio>
            <el-radio label="政治敏感"> 政治敏感 </el-radio>
            <el-radio label="虚假、不实内容"> 虚假、不实内容 </el-radio>
            <el-radio label="违反公德秩序"> 违反公德秩序 </el-radio>
            <el-radio label="危害人身安全"> 危害人身安全 </el-radio>
            <el-radio label="网络暴力"> 网络暴力 </el-radio>
            <el-radio label="其他原因"> 其他原因 </el-radio>
          </el-radio-group>
        </div>

        <!-- 详细描述（仅"其他原因"时显示） -->
        <div v-if="reportForm.reason === '其他原因'" class="report-description">
          <el-input
            v-model="reportForm.description"
            type="textarea"
            :rows="4"
            placeholder="请您在此处填写具体原因,我们会在第一时间为您处理!（必填）"
            maxlength="300"
            show-word-limit
          />
        </div>

        <!-- 上传凭证 -->
        <div class="report-upload">
          <div class="upload-title">上传凭证</div>
          <el-upload
            v-model:file-list="reportForm.fileList"
            list-type="picture-card"
            :limit="9"
            :on-preview="handleReportPreview"
            :on-remove="handleReportRemove"
            :before-upload="beforeReportUpload"
            :http-request="handleReportUpload"
            accept="image/*"
            multiple
          >
            <el-icon :size="24">
              <Plus />
            </el-icon>
          </el-upload>
        </div>

        <!-- 同意协议 -->
        <div class="report-agreement">
          <el-checkbox v-model="reportForm.agreed"> 同时拉黑该用户 </el-checkbox>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reportDialogVisible = false"> 取消 </el-button>
          <el-button type="primary" :loading="reportSubmitting" @click="handleSubmitReport"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享给好友" width="500px" destroy-on-close @close="handleCloseShareDialog">
      <div class="share-dialog-content">
        <!-- 好友列表 -->
        <div class="share-friend-list">
          <div v-if="filteredShareFriendList.length > 0">
            <div
              v-for="friend in filteredShareFriendList"
              :key="friend.id"
              class="share-friend-item"
              @click="handleSelectFriend(friend)"
            >
              <div class="friend-info">
                <div class="friend-avatar">
                  <img v-if="friend.avatar" :src="friend.avatar" :alt="friend.name" />
                  <el-icon v-else :size="40">
                    <Avatar />
                  </el-icon>
                </div>
                <div class="friend-name">
                  {{ friend.name }}
                </div>
              </div>
              <el-icon v-if="selectedFriends.includes(friend.id)" :size="20" color="#409eff">
                <CircleCheck />
              </el-icon>
            </div>
          </div>
          <el-empty v-else description="暂无好友" />
        </div>

        <!-- 已选择的好友 -->
        <div v-if="selectedFriends.length > 0" class="selected-friends">
          <div class="selected-title">已选择 {{ selectedFriends.length }} 位好友</div>
          <div class="selected-list">
            <el-tag v-for="friendId in selectedFriends" :key="friendId" closable @close="handleRemoveFriend(friendId)">
              {{ shareFriendList.find(f => f.id === friendId)?.name }}
            </el-tag>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="shareDialogVisible = false"> 取消 </el-button>
          <el-button
            type="primary"
            :loading="shareSubmitting"
            :disabled="selectedFriends.length === 0"
            @click="handleConfirmShare"
          >
            确认分享
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="dynamicManagementIndex">
import { ref, reactive, computed, onMounted, onActivated, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Picture,
  Avatar,
  Close,
  ChatDotRound,
  Share,
  MoreFilled,
  Edit,
  Delete,
  Warning,
  CircleClose,
  Plus,
  Search,
  CircleCheck
} from "@element-plus/icons-vue";
import {
  toggleFollowUser,
  blockUser,
  uploadImg,
  saveComment,
  commentList,
  type CommentListParams,
  getMutualAttention,
  addTransferCount,
  deleteDynamicsById,
  getUserDynamics,
  likeDynamicNew,
  unlikeDynamicNew,
  getUserByPhone,
  reportUserViolation
} from "@/api/modules/newLoginApi";

// import { uploadImg } from "@/api/modules/upload";
import { normalizeCommonCommentListResponse, countTopAndNestedComments } from "@/utils/commonCommentList";
import { useUserStore } from "@/stores/modules/user";
import { useWebSocketStore } from "@/stores/modules/websocket";

const router = useRouter();
const userStore = useUserStore();
const socketStore = useWebSocketStore();

// WebSocket 基础地址（与商家端一致，分享前连接）
const WS_BASE = import.meta.env.VITE_WS_BASE || "ws://192.168.10.80:8000/alienStore/socket/";

// 举报原因到违规类型的映射
const violationTypeMap: Record<string, number> = {
  用户违规: 1,
  色情低俗: 2,
  违法违规: 3,
  "侮辱谩骂、煽动对立": 4,
  涉嫌诈骗: 5,
  人身攻击: 6,
  种族歧视: 7,
  政治敏感: 8,
  "虚假、不实内容": 9,
  违反公德秩序: 10,
  危害人身安全: 11,
  网络暴力: 12,
  其他原因: 13
};

// 接口定义
// 媒体项类型
interface MediaItem {
  url: string;
  type: "image" | "video";
}

interface DynamicItem {
  isLike: any;
  dianzanCount: any;
  createdTime: any;
  context: string;
  id: number;
  title: string;
  content: string;
  imageUrl: string;
  userName: string;
  userAvatar: string;
  likeCount: number;
  isLiked: boolean;
  createTime: string;
  userId?: string | number; // 发布者ID
  phoneId?: string; // 发布者店铺ID
  storeUserId?: string | number; // 小店用户ID（用于举报）
  userType?: number; // 发布者用户类型：1商家，2用户
  phone?: string; // 发布者手机号
  isFollowed?: number; // 是否已关注：0未关注，1已关注
  isFollowThis?: number; // 是否已关注：0未关注，1已关注（用于判断关注按钮显示）
  isVideo?: boolean; // 是否为视频
  mediaType?: string; // 媒体类型：image 或 video
  mediaList?: MediaItem[]; // 媒体列表（支持多张图片和视频）
}

interface DetailItem extends DynamicItem {
  author?: {
    id: number;
    name: string;
    avatar: string;
  };
  context: string;
  commentCount: number;
  isFollowThis?: number; // 是否已关注：0未关注，1已关注（用于判断关注按钮显示）
}

// 响应式数据
const activeTab = ref("recommend");
const dynamicList = ref<DynamicItem[]>([]);
const isfollowed = ref(0); // 0: 推荐, 1: 关注

// 详情 Drawer 相关
const detailDrawerVisible = ref(false);
const currentDetail = ref<DetailItem | null>(null);

// 描述展开/收起状态
const isDescriptionExpanded = ref(false);

// 轮播相关
const currentCarouselIndex = ref(0);
const videoRefs = ref<Map<number, HTMLVideoElement>>(new Map());

// 设置视频引用
const setVideoRef = (el: any, index: number) => {
  if (el) {
    videoRefs.value.set(index, el as HTMLVideoElement);
  }
};

// 轮播切换时暂停所有视频
const handleCarouselChange = (newIndex: number) => {
  // 暂停所有视频
  videoRefs.value.forEach(video => {
    if (video && !video.paused) {
      video.pause();
    }
  });
  currentCarouselIndex.value = newIndex;
};

// 视频播放时暂停其他视频
const handleVideoPlay = (currentIndex: number) => {
  videoRefs.value.forEach((video, index) => {
    if (index !== currentIndex && video && !video.paused) {
      video.pause();
    }
  });
};
// 举报对话框相关
const reportDialogVisible = ref(false);
const reportSubmitting = ref(false);
const reportForm = reactive({
  reason: "用户违规", // 默认选择第一个选项
  description: "",
  fileList: [] as any[],
  agreed: false
});

// 分享对话框相关
interface ShareFriend {
  id: number;
  name: string;
  avatar: string;
  phoneId?: string;
}

const shareDialogVisible = ref(false);
const shareSubmitting = ref(false);
const shareSearch = ref("");
const shareFriendList = ref<ShareFriend[]>([]);
const selectedFriends = ref<number[]>([]);

// 过滤后的好友列表
const filteredShareFriendList = computed(() => {
  if (!shareSearch.value) {
    return shareFriendList.value;
  }
  const keyword = shareSearch.value.toLowerCase();
  return shareFriendList.value.filter(friend => friend.name.toLowerCase().includes(keyword));
});

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 直接使用动态列表（后端已完成分页）
const paginatedList = computed(() => {
  return dynamicList.value;
});

// 判断当前详情是否是当前用户的动态
const isMyDynamic = computed(() => {
  const currentUserStoreId = userStore.userInfo?.storeId;
  const dynamicStoreUserId = currentDetail.value?.storeUserId; // ✅ 添加可选链操作符

  // 通过 storeId 和 storeUserId 判断是否是当前用户的动态
  const result = currentUserStoreId == dynamicStoreUserId;
  console.log("是否是自己发布的作品:", result);

  return result;
});

// 标签切换
const handleTabClick = (tab: any) => {
  // 根据切换的 tab 更新 isfollowed 的值
  // 使用传入的 tab.props.name 获取当前点击的 tab，而不是 activeTab.value
  const tabName = tab?.props?.name || tab?.paneName || activeTab.value;

  if (tabName === "recommend") {
    isfollowed.value = 0; // 推荐
  } else if (tabName === "follow") {
    isfollowed.value = 1; // 关注
  }

  pagination.page = 1;
  loadDynamicList();
};

// 发布动态
const handlePublish = () => {
  // 校验是否已入驻店铺
  if (!userStore.userInfo?.storeId) {
    ElMessage.warning("请先入驻店铺");
    return;
  }

  router.push("/dynamicManagement/publishDynamic");
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.page = 1;
  loadDynamicList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.page = val;
  loadDynamicList();
};

// 根据 phoneId 判断用户类型
const getUserTypeFromPhoneId = (phoneId: string | undefined): number => {
  if (!phoneId) return 1; // 默认商家

  const prefix = phoneId.split("_")[0]; // 截取 "_" 之前的文字
  return prefix === "store" ? 1 : 2; // store = 商家(1), 其他 = 用户(2)
};

// 获取黑名单列表（从 localStorage）
const getBlockedUserList = (): string[] => {
  try {
    const blockedList = localStorage.getItem("blockedUserList");
    return blockedList ? JSON.parse(blockedList) : [];
  } catch (error) {
    console.error("获取黑名单失败:", error);
    return [];
  }
};

// 添加到黑名单（保存到 localStorage）
const addToBlockedList = (phoneId: string) => {
  try {
    const blockedList = getBlockedUserList();
    if (!blockedList.includes(phoneId)) {
      blockedList.push(phoneId);
      localStorage.setItem("blockedUserList", JSON.stringify(blockedList));
      console.log("已添加到黑名单:", phoneId, "当前黑名单:", blockedList);
    }
  } catch (error) {
    console.error("添加黑名单失败:", error);
  }
};

// 加载动态列表
const loadDynamicList = async () => {
  try {
    // 获取店铺ID（从 userStore 中获取，如果没有则使用默认值）
    const phoneId = userStore.userInfo?.phoneId;

    const res = await getUserDynamics({
      type: 2, // 固定值，表示动态类型
      isfollowed: isfollowed.value, // 0 推荐, 1 关注（使用全局变量）
      myself: 0, // 0 表示他人的动态
      page: pagination.page,
      size: pagination.pageSize,
      phoneId: `store_${userStore.userInfo?.phone}`
    });

    // 处理返回的数据
    if (res.data) {
      // 根据实际返回的数据结构进行映射
      const responseData = res.data as any;
      let list = responseData.records;

      // 获取黑名单并过滤
      const blockedList = getBlockedUserList();
      if (blockedList.length > 0) {
        const originalLength = list.length;
        list = list.filter((item: any) => {
          const itemPhoneId = item.phoneId || item.storeId || "";
          return !blockedList.includes(itemPhoneId);
        });
        const filteredCount = originalLength - list.length;
        if (filteredCount > 0) {
          console.log(`已过滤 ${filteredCount} 条被拉黑用户的动态`);
        }
      }

      dynamicList.value = list.map((item: any) => {
        const phoneId = item.phoneId || item.storeId;
        const userType = getUserTypeFromPhoneId(phoneId); // 根据 phoneId 判断用户类型

        // 从 phoneId 中提取手机号（"_" 之后的部分）
        let phone = item.phone || item.userPhone || item.mobile || "";
        if (!phone && phoneId && phoneId.includes("_")) {
          phone = phoneId.split("_")[1]; // 截取 "_" 之后的文字作为手机号
        }

        // 输出关注状态（仅第一条）
        if (item.id === list[0].id) {
          console.log("接口返回的isFollowThis:", item.isFollowThis, "(0=未关注, 1=已关注)");
        }

        // 解析媒体列表（支持多张图片和视频）
        const mediaUrl = item.imagePath || "";
        const mediaUrls = mediaUrl
          .split(",")
          .map((url: string) => url.trim())
          .filter((url: string) => url);
        const mediaList: MediaItem[] = mediaUrls.map((url: string) => ({
          url,
          type: url.toLowerCase().endsWith(".mp4") ? ("video" as const) : ("image" as const)
        }));

        const firstUrl = mediaUrls[0] || "";
        const isVideo = firstUrl.toLowerCase().endsWith(".mp4");
        const mediaType = isVideo ? "video" : "image";

        // 获取用户头像（优先使用 userImage 字段）
        const userAvatar = item.userImage || item.userAvatar || item.avatar || item.headImg || "";

        return {
          // 保留接口返回的所有原始字段
          ...item,
          // 额外添加的处理字段
          id: item.id || item.dynamicId,
          title: item.title || item.content || item.dynamicContent || "这家店超好吃....",
          content: item.content || item.dynamicContent || "",
          imageUrl: firstUrl, // 使用第一个URL（兼容旧逻辑）
          mediaList, // 完整媒体列表
          userName: item.userName || item.nickname || item.storeName || "用户",
          userAvatar: userAvatar,
          likeCount: item.likeCount || item.praiseCount || 0,
          isLiked: item.isLiked || item.isPraise || false,
          createTime: item.createTime || item.createDate || new Date().toISOString(),
          userId: item.userId || item.createUserId,
          phoneId: phoneId,
          storeUserId: item.storeUserId || item.userId || item.createUserId, // 小店用户ID
          userType: userType, // 用户类型：1商家，2用户
          phone: phone, // 手机号（从 phoneId 或其他字段获取）
          isFollowed: item.isFollowThis, // 使用isFollowThis字段：0未关注（显示按钮），1已关注（隐藏按钮）
          isFollowThis: item.isFollowThis, // 是否已关注：0未关注，1已关注（用于判断关注按钮显示）
          isVideo: isVideo, // 是否为视频
          mediaType: mediaType // 媒体类型
        };
      });

      pagination.total = responseData.total || responseData.totalCount || list.length;
    }
  } catch (error) {
    console.error("加载动态列表失败:", error);
    ElMessage.error("加载动态列表失败");
    // 失败时清空列表
    dynamicList.value = [];
    pagination.total = 0;
  }
};

// 点击卡片 - 查看详情（直接使用列表数据）
const handleCardClick = async (item: DynamicItem) => {
  console.log("点击动态:", item);
  console.log("isFollowThis值:", item.isFollowThis, "(0=未关注显示按钮, 1=已关注隐藏按钮)");
  console.log("isMyDynamic:", isMyDynamic.value);
  // 重置描述展开状态
  isDescriptionExpanded.value = false;
  // 直接使用列表数据构建详情
  currentDetail.value = {
    ...item,
    author: {
      id: 0,
      name: item.userName,
      avatar: item.userAvatar
    },
    context: item.context,
    createdTime: item.createdTime,
    dianzanCount: item.dianzanCount,
    isLike: item.isLike,

    commentCount: 0,
    isFollowThis: item.isFollowThis // 使用item.isFollowThis而不是item.isFollowed
  };
  detailDrawerVisible.value = true;

  // 打开抽屉时加载评论列表
  await loadCommentList();
};

// 列表点赞/取消点赞
const handleLike = async (item: DynamicItem) => {
  try {
    // 获取当前用户的手机号，并在前面拼接 "store_"
    const phone = userStore.userInfo?.phone || "";
    const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;

    const params = {
      userId: currentUserPhoneId, // 当前用户phoneId
      huifuId: item.id, // 动态ID
      type: 2 // 2表示点赞
    };
    // 根据当前点赞状态调用不同的接口
    if (item.isLike == "1") {
      // 已点赞，调用取消点赞接口
      await unlikeDynamicNew(params);
    } else {
      // 未点赞，调用点赞接口
      await likeDynamicNew(params);
    }
    await loadDynamicList();

    // ElMessage.success(item.isLike != "1" ? "点赞成功" : "取消点赞");
  } catch (error) {
    console.error("列表点赞操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 关闭详情
const handleCloseDetail = () => {
  detailDrawerVisible.value = false;
  // 暂停所有视频
  videoRefs.value.forEach(video => {
    if (video && !video.paused) {
      video.pause();
    }
  });
  setTimeout(() => {
    currentDetail.value = null;
    currentCarouselIndex.value = 0;
    videoRefs.value.clear();
  }, 300);
};

// 详情页点赞（表单方式提交）
const handleDetailLike = async () => {
  if (!currentDetail.value) return;

  try {
    // 获取当前用户的手机号，并在前面拼接 "store_"
    const phone = userStore.userInfo?.phone || "";
    const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;

    const params = {
      userId: currentUserPhoneId, // 当前用户phoneId
      huifuId: currentDetail.value.id, // 动态ID
      type: 2 // 2表示点赞
    };

    // 根据当前点赞状态调用不同的接口
    if (currentDetail.value.isLike == "1") {
      // 已点赞，调用取消点赞接口

      await unlikeDynamicNew(params);
    } else {
      // 未点赞，调用点赞接口
      await likeDynamicNew(params);
    }

    // 重新加载动态列表以获取最新数据
    await loadDynamicList();

    // 更新当前详情的点赞状态（从重新加载的列表中获取）
    const updatedItem = dynamicList.value.find(item => item.id === currentDetail.value?.id);
    if (updatedItem && currentDetail.value) {
      currentDetail.value.isLike = updatedItem.isLike;
      currentDetail.value.dianzanCount = updatedItem.dianzanCount;
    }
  } catch (error) {
    console.error("点赞操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 切换描述展开/收起
const toggleDescription = () => {
  isDescriptionExpanded.value = !isDescriptionExpanded.value;
};

// 显示评论
// 评论相关
const commentDrawerVisible = ref(false);
const commentListData = ref<any[]>([]);
const commentInput = ref("");
const commentSubmitting = ref(false);
const currentCommentDynamicId = ref<number | string>("");
const replyingComment = ref<any>(null); // 当前正在回复的评论

const handleShowComments = () => {
  if (!currentDetail.value) return;
  commentDrawerVisible.value = true;
  currentCommentDynamicId.value = currentDetail.value.id;
  // 清空评论输入框
  commentInput.value = "";
  // 清空回复评论
  replyingComment.value = null;
};

// 加载评论列表
const loadCommentList = async () => {
  if (!currentDetail.value) return;

  try {
    const params: CommentListParams = {
      pageNum: 1,
      pageSize: 100,
      sourceId: currentDetail.value.id,
      sourceType: 2
    };
    const uid = userStore.userInfo?.userId ?? userStore.userInfo?.id;
    if (uid !== undefined && uid !== null && uid !== "") {
      const n = Number(uid);
      if (Number.isFinite(n)) params.userId = Math.trunc(n);
    }
    const res: any = await commentList(params);
    if (res.code === 200) {
      const list = normalizeCommonCommentListResponse(res.data);
      commentListData.value = list;
      if (currentDetail.value) {
        const raw = res.data;
        const pageTotal =
          raw && typeof raw === "object" && !Array.isArray(raw) && typeof (raw as { total?: number }).total === "number"
            ? (raw as { total: number }).total
            : undefined;
        currentDetail.value.commentCount =
          pageTotal !== undefined && pageTotal >= 0 ? pageTotal : countTopAndNestedComments(list);
      }
      console.log("评论列表:", commentListData.value);
    }
  } catch (error) {
    console.error("加载评论列表失败:", error);
  }
};

// 提交评论
const handleSubmitComment = async () => {
  if (!commentInput.value.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }

  if (!currentDetail.value) {
    ElMessage.error("动态信息不存在");
    return;
  }

  try {
    commentSubmitting.value = true;

    // 判断是回复评论还是评论动态
    const isReply = !!replyingComment.value;

    const params: any = {
      replyId: isReply ? replyingComment.value.id : "", // 回复评论时传评论ID，否则为空
      commentContent: commentInput.value,
      businessType: "2",
      businessId: String(currentDetail.value.id),
      storeId: userStore.userInfo?.storeId || userStore.userInfo?.createdId,
      commentStar: "",
      phoneId: `store_${userStore.userInfo?.phone}`
    };

    const res: any = await saveComment(params);
    if (res.code === 200) {
      ElMessage.success(isReply ? "回复成功" : "评论成功");
      commentInput.value = "";
      replyingComment.value = null; // 清空回复状态
      await loadCommentList();
    } else {
      ElMessage.error(res.message || (isReply ? "回复失败" : "评论失败"));
    }
  } catch (error) {
    console.error("提交评论失败:", error);
    ElMessage.error(replyingComment.value ? "回复失败" : "评论失败");
  } finally {
    commentSubmitting.value = false;
  }
};

// 点赞评论
const handleLikeComment = async (comment: any) => {
  console.log(comment);
  try {
    // 获取当前用户的手机号，并在前面拼接 "store_"
    const phone = userStore.userInfo?.phone || "";
    const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;

    const params = {
      userId: currentUserPhoneId, // 当前用户phoneId
      huifuId: comment.id, // 动态ID
      type: 1 // 2表示点赞
    };

    // 根据当前点赞状态调用不同的接口
    if (comment.isLiked) {
      // 已点赞，调用取消点赞接口
      await unlikeDynamicNew(params);
    } else {
      // 未点赞，调用点赞接口
      await likeDynamicNew(params);
    }

    // 切换点赞状态
    comment.isLiked = !comment.isLiked;
    comment.likeCount += comment.isLiked ? 1 : -1;
  } catch (error) {
    console.error("列表点赞操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 回复评论
const handleReplyComment = (comment: any) => {
  replyingComment.value = comment;
  commentInput.value = ``;
  // 聚焦到输入框
  setTimeout(() => {
    const textarea = document.querySelector(".comment-input-wrapper textarea") as HTMLTextAreaElement;
    if (textarea) {
      textarea.focus();
    }
  }, 100);
};

// 取消回复
const handleCancelReply = () => {
  replyingComment.value = null;
  commentInput.value = "";
};

// 分享（参考商家端 newDetail：分享前先连接 WebSocket）
const handleShare = async () => {
  const phone = userStore.userInfo?.phone || "";
  const senderId = phone.startsWith("store_") ? phone : `store_${phone}`;
  const wsUrl = `${WS_BASE.replace(/\/$/, "")}/${senderId}`;
  try {
    if (!socketStore.isConnected || socketStore.lastConnectedUrl !== wsUrl) {
      const connected = await socketStore.connect(wsUrl);
      if (!connected) {
        ElMessage.warning("连接失败，请稍后重试");
        return;
      }
    }
  } catch (e) {
    console.error("WebSocket 连接失败:", e);
    ElMessage.warning("连接失败，请稍后重试");
    return;
  }
  shareDialogVisible.value = true;
  await loadShareFriendList();
};

// 加载好友列表
const loadShareFriendList = async () => {
  try {
    // 获取当前用户的手机号，并在前面拼接 "store_"
    const phone = userStore.userInfo?.phone || "";
    const fansId = phone.startsWith("store_") ? phone : `store_${phone}`;

    const res: any = await getMutualAttention({
      page: 1,
      size: 1000,
      fansId: fansId,
      name: ""
    });

    if (res.code === 200) {
      const dataList = res.data?.records || res.data?.list || res.data || [];
      shareFriendList.value = dataList.map((item: any) => ({
        id: item.id || item.userId,
        name: item.userName || item.nickname || item.name || "用户",
        avatar: item.userImage || item.avatar || item.headImg || "",
        phoneId: item.phoneId || item.fansId || ""
      }));
      console.log("加载好友列表成功:", shareFriendList.value);
    }
  } catch (error) {
    console.error("加载好友列表失败:", error);
    ElMessage.error("加载好友列表失败");
    shareFriendList.value = [];
  }
};

// 搜索好友
const handleShareSearch = () => {
  // 搜索由计算属性自动处理
};

// 选择好友
const handleSelectFriend = (friend: ShareFriend) => {
  const index = selectedFriends.value.indexOf(friend.id);
  if (index > -1) {
    // 已选择，取消选择
    selectedFriends.value.splice(index, 1);
  } else {
    // 未选择，添加选择
    selectedFriends.value.push(friend.id);
  }
};

// 移除已选择的好友
const handleRemoveFriend = (friendId: number) => {
  const index = selectedFriends.value.indexOf(friendId);
  if (index > -1) {
    selectedFriends.value.splice(index, 1);
  }
};

// 确认分享（参考商家端 newDetail：通过 WebSocket sendMessage 发送给每位好友，再调 addTransferCount）
const handleConfirmShare = async () => {
  if (selectedFriends.value.length === 0) {
    ElMessage.warning("请选择要分享的好友");
    return;
  }

  if (!currentDetail.value) {
    ElMessage.error("动态信息不存在");
    return;
  }

  const phone = userStore.userInfo?.phone || "";
  const senderId = phone.startsWith("store_") ? phone : `store_${phone}`;
  const detailPayload = {
    ...currentDetail.value,
    imageList: currentDetail.value.imagePath.split(","),
    cover: currentDetail.value.imagePath.split(",")[0]
  };
  try {
    shareSubmitting.value = true;

    // 先通过 WebSocket 给每位选中好友发送动态分享消息（与商家端 sendMessage 格式一致）
    for (const friendId of selectedFriends.value) {
      const friend = shareFriendList.value.find(f => f.id === friendId);
      const receiverId = friend?.phoneId || friend?.id;
      if (!receiverId) continue;
      await socketStore.sendMessage({
        category: "message",
        receiverId,
        senderId,
        type: 3,
        text: {
          sendType: "dynamicShare",
          url: JSON.stringify(detailPayload)
        }
      });
    }

    // 再调用 addTransferCount 接口，传递动态 id（与商家端一致）
    const res: any = await addTransferCount({
      id: currentDetail.value.id
    });

    if (res.code === 200) {
      ElMessage.success(`已分享给 ${selectedFriends.value.length} 位好友`);
      shareDialogVisible.value = false;
      // 更新当前详情的分享数
      if (typeof (currentDetail.value as any).transferCount === "number") {
        (currentDetail.value as any).transferCount += selectedFriends.value.length;
      }
    } else {
      ElMessage.error(res.message || "分享失败");
    }
  } catch (error) {
    console.error("分享失败:", error);
    ElMessage.error("分享失败");
  } finally {
    shareSubmitting.value = false;
  }
};

// 关闭分享对话框
const handleCloseShareDialog = () => {
  shareSearch.value = "";
  selectedFriends.value = [];
  shareFriendList.value = [];
};

// 查看用户主页
const handleViewUserProfile = () => {
  if (!currentDetail.value) return;
  // 跳转到他人动态主页，传递用户信息
  router.push({
    path: "/dynamicManagement/userDynamic",
    query: {
      userId: currentDetail.value.storeOrUserId || "",
      phoneId: currentDetail.value.phoneId || "",
      userName: currentDetail.value.userName || "",
      userAvatar: currentDetail.value.userAvatar || "",
      phone: currentDetail.value.phone || ""
    }
  });
};

// 详情页关注（右侧操作栏）
const handleFollowInDetail = async () => {
  if (!currentDetail.value) return;

  try {
    const phone = userStore.userInfo?.phone || "";
    const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;

    await toggleFollowUser({
      followedId: currentDetail.value.phoneId || "",
      fansId: currentUserPhoneId,
      fansType: 2
    });

    // 更新关注状态
    if (currentDetail.value) {
      currentDetail.value.isFollowed = 1;
      currentDetail.value.isFollowThis = 1; // 同时更新isFollowThis字段
    }

    // 同步更新列表中的状态
    const listItem = dynamicList.value.find(item => item.id === currentDetail.value?.id);
    if (listItem) {
      listItem.isFollowed = 1;
      listItem.isFollowThis = 1; // 同时更新列表项的isFollowThis状态
    }

    ElMessage.success("关注成功");
  } catch (error) {
    console.error("关注操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 编辑动态
const handleEditDynamic = () => {
  if (!currentDetail.value) return;
  detailDrawerVisible.value = false;
  router.push({
    path: "/dynamicManagement/publishDynamic",
    query: { id: currentDetail.value.id }
  });
};

// 删除动态
const handleDeleteDynamic = async () => {
  if (!currentDetail.value) return;

  try {
    await ElMessageBox.confirm("确定要删除这条动态吗？删除后将无法恢复。", "删除确认", {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "el-button--danger"
    }).then(async () => {
      if (!currentDetail.value) return;
      const res: any = await deleteDynamicsById({ id: currentDetail.value.id });
      if (res.code === 200) {
        ElMessage.success("删除成功");
        detailDrawerVisible.value = false;
        const index = dynamicList.value.findIndex(item => item.id === currentDetail.value?.id);
        if (index > -1) {
          dynamicList.value.splice(index, 1);
        }
      }
    });
  } catch {
    // 用户取消删除
  }
};

// 举报动态
const handleReportDynamic = () => {
  reportDialogVisible.value = true;
};

// 举报图片预览
const handleReportPreview = (uploadFile: any) => {
  console.log("预览图片", uploadFile);
};

// 移除举报图片
const handleReportRemove = (uploadFile: any, uploadFiles: any[]) => {
  // 已由 v-model:file-list 自动处理
};

// 举报图片上传前验证
const beforeReportUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 自定义举报图片上传
const handleReportUpload = async (options: any) => {
  const { file, onSuccess, onError } = options;

  try {
    const uploadFormData = new FormData();
    uploadFormData.append("file", file);

    const response: any = await uploadImg(uploadFormData);

    const url =
      response?.data && (Array.isArray(response.data) && response.data.length > 0 ? response.data[0] : response.data.fileUrl);
    if (response && response.code === 200 && url) {
      onSuccess({
        url
      });
    } else {
      ElMessage.error(response?.msg || "图片上传失败");
      onError(new Error(response?.msg || "图片上传失败"));
    }
  } catch (error) {
    console.error("图片上传失败:", error);
    ElMessage.error("图片上传失败");
    onError(error);
  }
};

// 提交举报
const handleSubmitReport = async () => {
  // 验证表单
  if (!reportForm.reason) {
    ElMessage.warning("请选择举报原因");
    return;
  }

  // 只有选择"其他原因"时才验证详细描述
  if (reportForm.reason === "其他原因" && !reportForm.description.trim()) {
    ElMessage.warning("请填写详细描述");
    return;
  }

  if (!currentDetail.value) {
    ElMessage.warning("动态信息异常");
    return;
  }

  reportSubmitting.value = true;

  try {
    // 获取违规类型编号
    const violationType = violationTypeMap[reportForm.reason];

    // 获取举报凭证图片（如果有多张，用逗号分隔）
    const reportEvidenceImg = reportForm.fileList
      .map((f: any) => f.url || f.response?.url)
      .filter(Boolean)
      .join(",");

    // 获取当前用户信息
    const currentUserId = userStore.userInfo?.id || userStore.userInfo?.userId || "";
    const currentUserType = userStore.userInfo?.userType || userStore.userInfo?.type || 1; // 用户类型：1商家，2用户，默认1

    // 获取被举报用户类型（从 phoneId 解析）
    const reportedUserType = currentDetail.value.userType || 1;

    // 根据手机号获取被举报人ID
    let reportedUserId = currentDetail.value.storeUserId || currentDetail.value.userId || "";
    if (currentDetail.value.phone) {
      try {
        const userRes = await getUserByPhone({ phone: currentDetail.value.phone });
        const userData = userRes.data as any;
        if (userData && userData.id) {
          reportedUserId = userData.id;
          console.log("通过手机号获取到被举报人ID:", reportedUserId);
        }
      } catch (error) {
        console.error("获取被举报人ID失败:", error);
        // 如果获取失败，使用原有的 storeUserId
      }
    }

    console.log("当前用户类型:", userStore.userInfo);
    console.log("被举报用户类型:", reportedUserType);
    console.log("被举报人ID:", reportedUserId);
    console.log("动态详情:", currentDetail.value);

    // 调用举报接口
    await reportUserViolation({
      dynamicsId: currentDetail.value.id, // 动态ID
      reportContextType: "2", // 举报上下文类型：2表示动态
      violationType: violationType, // 违规类型
      otherReasonContent: reportForm.reason === "其他原因" ? reportForm.description : "", // 只有选择"其他原因"时才传详细描述
      reportEvidenceImg: reportEvidenceImg, // 举报凭证图片
      reportedUserId: reportedUserId, // 被举报用户ID（通过手机号获取）
      reportedUserType: reportedUserType, // 被举报用户类型（从 phoneId 解析）
      reportingUserId: currentUserId, // 举报人ID
      reportingUserType: currentUserType // 举报人类型（当前登录用户类型）
    });

    // 如果同时拉黑该用户
    if (reportForm.agreed) {
      try {
        // 调用拉黑接口（跳过确认对话框）
        await handleBlockUser(true);
        ElMessage.success("举报提交成功，已拉黑该用户");
      } catch (blockError) {
        console.error("拉黑失败:", blockError);
        ElMessage.warning("举报提交成功，但拉黑失败");
      }
    } else {
      ElMessage.success("举报提交成功，我们会尽快处理");
    }

    reportDialogVisible.value = false;
  } catch (error) {
    console.error("举报提交失败:", error);
    ElMessage.error("举报提交失败");
  } finally {
    reportSubmitting.value = false;
  }
};

// 关闭举报对话框
const handleCloseReportDialog = () => {
  reportForm.reason = "用户违规"; // 重置为默认选项
  reportForm.description = "";
  reportForm.fileList = [];
  reportForm.agreed = false;
};

// 监听举报原因变化，如果不是"其他原因"则清空详细描述
watch(
  () => reportForm.reason,
  newReason => {
    if (newReason !== "其他原因") {
      reportForm.description = "";
    }
  }
);
// 拉黑用户（点击菜单项）
const handleBlockUserClick = () => {
  handleBlockUser(false);
};

// 拉黑用户
const handleBlockUser = async (skipConfirm: boolean = false) => {
  if (!currentDetail.value) return;

  try {
    // 如果不跳过确认，显示确认对话框
    if (!skipConfirm) {
      await ElMessageBox.confirm("拉黑后将不再看到该用户的动态，确定要拉黑吗？", "拉黑确认", {
        confirmButtonText: "确定拉黑",
        cancelButtonText: "取消",
        type: "warning"
      });
    }

    // 获取当前用户信息
    const currentUserId = userStore.userInfo?.id || userStore.userInfo?.userId || "";
    const currentUserType = userStore.userInfo?.userType || userStore.userInfo?.type || 1; // 用户类型：1商家，2用户，默认1

    // 获取被拉黑用户类型（从 phoneId 解析）
    const blockedUserType = currentDetail.value.userType || 1;

    console.log("当前用户信息:", userStore.userInfo);
    console.log("当前用户类型:", currentUserType);
    console.log("被拉黑用户类型:", blockedUserType);
    console.log("动态详情:", currentDetail.value);

    // 调用拉黑接口
    await blockUser({
      blockerType: currentUserType, // 拉黑者类型（当前登录用户类型）
      blockedType: blockedUserType, // 被拉黑者类型（从 phoneId 解析）
      blockerId: currentUserId, // 拉黑者ID（当前登录用户）
      blockedId: currentDetail.value.storeUserId || currentDetail.value.userId || "" // 被拉黑者ID
    });

    if (!skipConfirm) {
      ElMessage.success("已拉黑该用户");
    }

    // 保存被拉黑用户的 phoneId 到 localStorage
    const blockedPhoneId = currentDetail.value.phoneId;
    if (blockedPhoneId) {
      addToBlockedList(blockedPhoneId);
    }

    detailDrawerVisible.value = false;

    // 重新加载动态列表（会自动应用黑名单过滤）
    await loadDynamicList();
  } catch (error) {
    if (!skipConfirm) {
      // 单独拉黑时，用户取消操作或接口失败
      console.error("拉黑失败:", error);
      if (error !== "cancel") {
        ElMessage.error("拉黑失败");
      }
    } else {
      // 举报后自动拉黑失败，抛出错误
      throw error;
    }
  }
};

// 初始化
onMounted(() => {
  loadDynamicList();
});

// 页面激活时刷新列表（从发布页面返回时触发）
onActivated(() => {
  loadDynamicList();
});
</script>

<style scoped lang="scss">
@import "@/assets/dianzanFont/iconfont.css";
.dynamic-management-container {
  min-height: calc(100vh - 120px);
  padding: 20px;
  background: #ffffff;

  // 头部区域
  .header-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    border-bottom: 1px solid #e4e7ed;
    :deep(.el-tabs) {
      flex: 1;
      margin-bottom: -1px;
      .el-tabs__header {
        margin-bottom: 0;
      }
      .el-tabs__nav-wrap::after {
        display: none;
      }
    }
    .action-buttons {
      padding-bottom: 10px;
      margin-left: 20px;
    }
  }

  // 内容区域
  .content-section {
    margin-top: 20px;
  }

  // 动态网格布局
  .dynamic-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 20px;

    @media (width <= 1400px) {
      grid-template-columns: repeat(2, 1fr);
    }

    @media (width <= 768px) {
      grid-template-columns: repeat(1, 1fr);
    }
  }

  // 动态卡片
  .dynamic-card {
    overflow: hidden;
    cursor: pointer;
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    transition: all 0.3s;
    &:hover {
      box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
      transform: translateY(-2px);
    }

    // 图片区域
    .dynamic-image-wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 220px;
      overflow: hidden;
      background: #f5f7fa;
      .dynamic-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .image-placeholder {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
      }
    }

    // 动态内容
    .dynamic-content {
      padding: 12px 16px;
      .dynamic-text {
        margin-bottom: 12px;
        overflow: hidden;
        font-size: 14px;
        color: #333333;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      // 底部信息
      .dynamic-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .user-info {
          display: flex;
          gap: 8px;
          align-items: center;
          .user-avatar {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            overflow: hidden;
            background: #e4e7ed;
            border-radius: 50%;
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
          .user-name {
            font-size: 13px;
            color: #666666;
          }
        }
        .like-section {
          display: flex;
          gap: 4px;
          align-items: center;
          .like-icon {
            cursor: pointer;
            transition: color 0.3s;
            &:hover {
              color: #f56c6c;
            }
          }
          .like-count {
            font-size: 13px;
            color: #666666;
          }
        }
      }
    }
  }

  // 空状态
  .empty-section {
    padding: 80px 0;
    text-align: center;
  }

  // 分页
  .pagination-section {
    display: flex;
    justify-content: center;
    padding: 20px 0;
    margin-top: 30px;
  }

  // 详情 Drawer
  :deep(.detail-drawer) {
    .el-drawer__header {
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      z-index: 10;
      padding: 0;
      margin: 0;
      background: transparent;
    }
    .el-drawer__body {
      padding: 0;
      background: #000000;
    }
    .drawer-header {
      padding: 20px;
      .close-btn {
        padding: 8px;
        font-size: 24px;
        color: #ffffff;
        background: #ffffff;
      }
    }
    .detail-content {
      position: relative;
      display: flex;
      width: 100%;
      height: 100%;

      // 主内容区域
      .detail-main {
        display: flex;
        flex: 1;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 80px 120px 40px 40px;
        .media-container {
          position: relative;
          display: flex;
          flex: 1;
          align-items: center;
          justify-content: center;
          width: 100%;
          max-width: 800px;
          min-height: 400px;
          .media-carousel {
            width: 100%;
            height: 100%;
            min-height: 400px;
            max-height: 70vh;
            :deep(.el-carousel__container) {
              height: 100% !important;
              min-height: 400px;
            }
            :deep(.el-carousel__item) {
              display: flex;
              align-items: center;
              justify-content: center;
              background: transparent;
            }
            :deep(.el-carousel__arrow) {
              width: 48px;
              height: 48px;
              font-size: 24px;
              color: #ffffff;
              background-color: rgb(0 0 0 / 40%);
              border: none;
              &:hover {
                background-color: rgb(0 0 0 / 60%);
              }
            }
            :deep(.el-carousel__indicators) {
              bottom: -30px;
              .el-carousel__indicator {
                .el-carousel__button {
                  width: 8px;
                  height: 8px;
                  background-color: rgb(255 255 255 / 40%);
                  border-radius: 50%;
                }
                &.is-active .el-carousel__button {
                  background-color: #409eff;
                }
              }
            }
          }
          .detail-media {
            max-width: 100%;
            max-height: 65vh;
            object-fit: contain;
            border-radius: 8px;
          }
          .detail-image {
            max-width: 100%;
            max-height: 65vh;
            object-fit: contain;
            border-radius: 8px;
          }
          .detail-video {
            width: 100%;
            max-height: 65vh;
            background: #000000;
            border-radius: 8px;
          }
          .media-placeholder {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 400px;
            height: 400px;
            background: rgb(255 255 255 / 5%);
            border-radius: 8px;
          }
          .media-counter {
            position: absolute;
            right: 16px;
            bottom: -24px;
            padding: 4px 12px;
            font-size: 14px;
            color: #ffffff;
            background: rgb(0 0 0 / 50%);
            border-radius: 12px;
          }
        }
        .detail-info {
          width: 100%;
          max-width: 800px;
          padding: 20px 0;
          .author-info {
            display: flex;
            gap: 12px;
            align-items: center;
            margin-bottom: 16px;
            .author-avatar {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 40px;
              height: 40px;
              overflow: hidden;
              background: rgb(255 255 255 / 10%);
              border-radius: 50%;
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
            .author-details {
              flex: 1;
              .author-name {
                margin-bottom: 4px;
                font-size: 16px;
                font-weight: 500;
                color: #ffffff;
              }
              .publish-time {
                font-size: 13px;
                color: rgb(255 255 255 / 60%);
              }
            }
          }
          .detail-description {
            position: relative;
            font-size: 15px;
            line-height: 1.6;
            color: #ffffff;
            p {
              margin: 0;
              word-break: break-word;
              &.text-ellipsis {
                display: -webkit-box;
                overflow: hidden;
                text-overflow: ellipsis;
                -webkit-line-clamp: 2;
                line-clamp: 2;
                -webkit-box-orient: vertical;
              }
            }
            .expand-btn {
              display: inline-block;
              margin-top: 8px;
              font-size: 14px;
              color: #409eff;
              cursor: pointer;
              user-select: none;
              &:hover {
                color: #66b1ff;
              }
            }
          }
        }
      }

      // 右侧操作栏
      .action-bar {
        position: fixed;
        right: 40px;
        bottom: 100px;
        z-index: 10;
        display: flex;
        flex-direction: column;
        gap: 24px;
        .action-item {
          display: flex;
          flex-direction: column;
          gap: 6px;
          align-items: center;
          cursor: pointer;
          transition: transform 0.3s;
          &:hover {
            transform: scale(1.1);
          }
          &.author-action {
            cursor: pointer;
            &:hover {
              transform: scale(1.1);
            }
          }
          .action-avatar {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 48px;
            height: 48px;
            overflow: visible;
            cursor: pointer;
            background: rgb(255 255 255 / 20%);
            border: 2px solid #ffffff;
            border-radius: 50%;
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
              border-radius: 50%;
            }
            .follow-badge {
              position: absolute;
              right: -4px;
              bottom: -4px;
              z-index: 2;
              display: flex;
              align-items: center;
              justify-content: center;
              width: 24px;
              height: 24px;
              cursor: pointer;
              background: #409eff;
              border: 2px solid #ffffff;
              border-radius: 50%;
              transition: transform 0.2s;
              &:hover {
                transform: scale(1.15);
              }
            }
          }
          .action-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 48px;
            height: 48px;
            background: rgb(0 0 0 / 50%);
            backdrop-filter: blur(10px);
            border-radius: 50%;
            &.follow-icon {
              background: #409eff;
            }
          }
          .action-count {
            font-size: 13px;
            color: #ffffff;
            text-align: center;
            text-shadow: 0 1px 3px rgb(0 0 0 / 50%);
          }
        }
      }
    }
  }

  // 更多操作 Popover
  :deep(.more-actions-popover) {
    min-width: 120px;
    padding: 8px 0;
    background: rgb(0 0 0 / 90%);
    backdrop-filter: blur(10px);
    border: 1px solid rgb(255 255 255 / 10%);
    .el-popper__arrow::before {
      background: rgb(0 0 0 / 90%);
      border: 1px solid rgb(255 255 255 / 10%);
    }
    .more-actions-menu {
      .menu-item {
        display: flex;
        gap: 10px;
        align-items: center;
        padding: 10px 16px;
        font-size: 14px;
        line-height: 20px;
        color: #ffffff;
        cursor: pointer;
        transition: all 0.3s;
        &:hover {
          background: rgb(255 255 255 / 10%);
        }
        .el-icon {
          display: inline-flex;
          flex-shrink: 0;
          align-items: center;
          justify-content: center;
          width: 18px;
          height: 18px;
          color: #ffffff;
          vertical-align: middle;
        }
        span {
          display: inline-block;
          line-height: 20px;
          vertical-align: middle;
        }
      }
    }
  }

  // 举报对话框
  :deep(.el-dialog) {
    .report-dialog-content {
      .report-tip {
        margin-bottom: 20px;
        font-size: 14px;
        line-height: 1.6;
        color: #606266;
      }
      .report-reasons {
        margin-bottom: 20px;
        .el-radio-group {
          display: flex;
          flex-wrap: wrap;
          gap: 12px 16px;
          .el-radio {
            height: auto;
            margin-right: 0;
            white-space: nowrap;
            .el-radio__label {
              font-size: 14px;
              color: #303133;
            }
          }
        }
      }
      .report-description {
        margin-bottom: 20px;
        :deep(.el-textarea__inner) {
          font-size: 14px;
        }
      }
      .report-upload {
        margin-bottom: 20px;
        .upload-title {
          margin-bottom: 12px;
          font-size: 14px;
          font-weight: 500;
          color: #303133;
        }
        :deep(.el-upload-list) {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }
        :deep(.el-upload--picture-card) {
          width: 100px;
          height: 100px;
          border-radius: 4px;
        }
        :deep(.el-upload-list--picture-card .el-upload-list__item) {
          width: 100px;
          height: 100px;
          margin: 0;
          border-radius: 4px;
        }
      }
      .report-agreement {
        .el-checkbox {
          .el-checkbox__label {
            font-size: 14px;
            color: #606266;
          }
        }
      }
    }
    .dialog-footer {
      display: flex;
      gap: 12px;
      justify-content: flex-end;
    }
  }

  // 评论侧边栏样式
  .comment-list-container {
    flex: 1;
    height: calc(100vh - 200px);
    padding: 0 20px;
    overflow-y: auto;
    .comment-list {
      .comment-item {
        display: flex;
        gap: 12px;
        padding: 16px 0;
        border-bottom: 1px solid #f0f0f0;
        &:last-child {
          border-bottom: none;
        }
        .comment-avatar {
          display: flex;
          flex-shrink: 0;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          overflow: hidden;
          background: #f5f5f5;
          border-radius: 50%;
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        .comment-content-wrapper {
          flex: 1;
          min-width: 0;
          .comment-header,
          .store-comment-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 8px;
            .comment-user-name {
              font-size: 14px;
              font-weight: 500;
              color: #303133;
            }
            .comment-time {
              font-size: 12px;
              color: #909399;
            }
          }
          .comment-text {
            margin-bottom: 8px;
            font-size: 14px;
            line-height: 1.6;
            color: #606266;
            word-break: break-all;
          }

          // 商家回复样式
          .store-comment-wrapper {
            padding: 12px;
            margin-top: 12px;
            background: #f5f7fa;
            border-radius: 8px;
            .store-comment-item {
              display: flex;
              gap: 10px;
              .store-comment-avatar {
                display: flex;
                flex-shrink: 0;
                align-items: center;
                justify-content: center;
                width: 32px;
                height: 32px;
                overflow: hidden;
                background: #ffffff;
                border-radius: 50%;
                img {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                }
              }
              .store-comment-content {
                flex: 1;
                min-width: 0;
                .store-comment-header {
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  margin-bottom: 6px;
                  .store-comment-user-name {
                    font-size: 13px;
                    font-weight: 500;
                    color: #409eff;
                  }
                  .store-comment-time {
                    font-size: 11px;
                    color: #909399;
                  }
                }
                .store-comment-text {
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  font-size: 13px;
                  line-height: 1.5;
                  color: #606266;
                  word-break: break-all;
                }
              }
            }
          }
          .comment-actions {
            display: flex;
            gap: 20px;
            .comment-action-item {
              display: flex;
              gap: 4px;
              align-items: center;
              font-size: 13px;
              color: #909399;
              cursor: pointer;
              transition: color 0.3s;
              &:hover {
                color: #409eff;
              }
              span {
                font-size: 13px;
              }
            }
          }
        }
      }
    }
  }
  .comment-input-wrapper {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 16px 20px;
    background: #ffffff;
    border-top: 1px solid #e4e7ed;
    box-shadow: 0 -2px 8px rgb(0 0 0 / 5%);
    .reply-hint {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 12px;
      margin-bottom: 8px;
      background: #f5f7fa;
      border-radius: 4px;
      .reply-text {
        font-size: 13px;
        color: #409eff;
      }
      .cancel-reply {
        font-size: 16px;
        color: #909399;
        cursor: pointer;
        transition: color 0.3s;
        &:hover {
          color: #f56c6c;
        }
      }
    }
    :deep(.el-textarea) {
      margin-bottom: 12px;
    }
    .el-button {
      width: 100%;
    }
  }

  // 分享对话框
  .share-dialog-content {
    .search-box {
      margin-bottom: 16px;
    }
    .share-friend-list {
      max-height: 400px;
      margin-bottom: 16px;
      overflow-y: auto;
      .share-friend-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px;
        cursor: pointer;
        border-radius: 8px;
        transition: background-color 0.3s;
        &:hover {
          background-color: #f5f7fa;
        }
        .friend-info {
          display: flex;
          gap: 12px;
          align-items: center;
          .friend-avatar {
            display: flex;
            flex-shrink: 0;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            overflow: hidden;
            background: #f5f5f5;
            border-radius: 50%;
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
          .friend-name {
            font-size: 14px;
            font-weight: 500;
            color: #303133;
          }
        }
      }
    }
    .selected-friends {
      padding: 12px;
      background: #f5f7fa;
      border-radius: 8px;
      .selected-title {
        margin-bottom: 8px;
        font-size: 13px;
        color: #606266;
      }
      .selected-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        .el-tag {
          max-width: 120px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>
