<template>
  <div class="user-dynamic-container">
    <!-- 用户信息卡片 -->
    <div class="user-card">
      <div class="user-header">
        <div class="user-avatar-section">
          <div class="user-avatar-large">
            <img v-if="userInfo.avatar" :src="userInfo.avatar" :alt="userInfo.name" />
            <el-icon v-else :size="60">
              <Avatar />
            </el-icon>
          </div>
          <div class="user-info-text">
            <div class="user-name">
              {{ userInfo.name }}
            </div>
            <div class="user-stats">
              <span class="stat-item">{{ userInfo.followCount || 0 }} 关注</span>
              <span class="stat-divider">|</span>
              <span class="stat-item">{{ userInfo.fansCount || 0 }} 粉丝</span>
              <span class="stat-divider">|</span>
              <span class="stat-item">{{ userInfo.likeCount || 0 }} 获赞</span>
            </div>
          </div>
        </div>

        <!-- 右侧操作按钮（只在他人主页显示） -->
        <div v-if="!isMyPage" class="user-actions">
          <el-button type="primary" @click="handleFollow">
            {{ isFollowed ? "已关注" : "关注" }}
          </el-button>
          <el-dropdown trigger="click" @command="handleCommand">
            <el-button>
              <el-icon>
                <MoreFilled />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="report"> 举报 </el-dropdown-item>
                <el-dropdown-item command="block"> 拉黑 </el-dropdown-item>
                <el-dropdown-item v-if="isFriend && isStoreUser" command="gift"> 赠券 </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <div class="user-bio">
        {{ userInfo.jianjie }}
      </div>
    </div>

    <!-- 标签页 -->
    <div class="tabs-section">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="动态" name="dynamic" />
      </el-tabs>
    </div>

    <!-- 内容区域 -->
    <div v-if="contentList.length > 0" class="content-section">
      <!-- 动态卡片网格 -->
      <div class="content-grid">
        <div v-for="item in paginatedList" :key="item.id" class="content-card" @click="handleCardClick(item)">
          <!-- 封面图片区域 -->
          <div class="content-cover-wrapper">
            <img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.title" class="content-cover" />
            <div v-else class="cover-placeholder">
              <el-icon :size="48" color="#999">
                <Picture />
              </el-icon>
            </div>
          </div>

          <!-- 底部信息 -->
          <div class="content-footer">
            <div class="footer-left">
              <el-icon :size="14" color="#666">
                <View />
              </el-icon>
              <span class="view-count">{{ item.viewCount || 0 }}</span>
            </div>
            <div class="footer-right">
              <i class="iconfont icon-dianzanb" :style="{ fontSize: '14px', color: item.isLike == '1' ? '#f56c6c' : '#666' }" />
              <span class="like-count">{{ item.dianzanCount || 0 }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-section">
      <el-empty description="暂无动态" />
    </div>

    <!-- 分页 -->
    <div v-if="contentList.length > 0" class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[12, 24, 36, 48]"
        :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="userInfo.avatar" :src="userInfo.avatar" :alt="userInfo.name" />
                <el-icon v-else :size="32">
                  <Avatar />
                </el-icon>
              </div>
              <div class="author-details">
                <div class="author-name">@{{ userInfo.name }}</div>
                <div class="publish-time">
                  {{ currentDetail.createTime }}
                </div>
              </div>
            </div>

            <div class="detail-description">
              <p>{{ currentDetail.title }}</p>
            </div>
          </div>
        </div>

        <!-- 右侧操作栏 -->
        <div class="action-bar">
          <!-- 作者头像 -->
          <div class="action-item author-action">
            <div class="action-avatar">
              <img v-if="userInfo.avatar" :src="userInfo.avatar" :alt="userInfo.name" />
              <el-icon v-else :size="40" color="#fff">
                <Avatar />
              </el-icon>
              <!-- 关注按钮 (定位在头像右下角) -->
              <div v-if="!isFollowed && !isMyPage" 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.isLiked ? '#f56c6c' : '#fff' }"
              />
            </div>
            <div class="action-count">
              {{ currentDetail.likeCount }}
            </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 || 0 }}
            </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 v-if="!isMyPage" 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">
              <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="handleBlockUserFromDrawer"
              >
                <el-icon :size="18">
                  <CircleClose /> </el-icon
                >&nbsp;&nbsp;
                <span>拉黑</span>
              </div>
            </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.userAvatar" :src="comment.userAvatar" :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="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>

    <!-- 举报对话框 -->
    <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="giftCouponDialogVisible"
      title="赠送好友优惠券"
      width="600px"
      destroy-on-close
      @close="closeGiftCouponDialog"
    >
      <div class="gift-coupon-dialog-body">
        <div class="gift-type-section">
          <div class="section-label">请选择赠送类型</div>
          <el-radio-group v-model="giftCouponFormData.giftType" @change="onGiftTypeChange">
            <el-radio :label="1"> 满减券 </el-radio>
            <el-radio :label="2"> 折扣券 </el-radio>
          </el-radio-group>
        </div>
        <div class="coupon-rows-section">
          <div class="section-label">选择优惠券</div>
          <div v-for="(row, index) in giftCouponFormData.rows" :key="row.key" class="coupon-row">
            <el-select
              v-model="row.couponId"
              placeholder="选择优惠券"
              style="flex: 1; min-width: 0"
              clearable
              :loading="giftCouponListLoading"
              @visible-change="(visible: boolean) => visible && loadGiftCouponList(giftCouponFormData.giftType)"
              @change="onGiftRowCouponChange(row)"
            >
              <el-option
                v-for="coupon in giftCouponList"
                :key="coupon.id"
                :label="coupon.name"
                :value="coupon.id"
                :disabled="isGiftCouponSelectedInOtherRow(coupon.id, index)"
              />
            </el-select>
            <div class="quantity-cell">
              <el-input
                type="number"
                :model-value="row.quantity === 0 ? '' : row.quantity"
                placeholder="请输入赠券数量"
                class="quantity-input"
                :min="1"
                :max="getGiftRowMaxQuantity(row)"
                @input="(val: string | number) => setGiftRowQuantity(row, val)"
              />
              <span v-if="row.couponId" class="quantity-limit-hint"> 最多可赠 {{ getGiftRowMaxQuantity(row) }} 张 </span>
            </div>
            <el-button type="danger" link :icon="Delete" circle title="删除" @click="removeGiftCouponRow(index)" />
          </div>
          <el-button type="primary" link class="add-coupon-btn" @click="addGiftCouponRow">
            <el-icon><Plus /></el-icon>
            添加商家优惠券
          </el-button>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeGiftCouponDialog"> 取消 </el-button>
          <el-button type="primary" :disabled="!canSubmitGiftCoupon" @click="handleGiftCouponSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="userDynamic">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Avatar,
  Picture,
  View,
  Close,
  Share,
  MoreFilled,
  Plus,
  Delete,
  Warning,
  CircleClose,
  ChatDotRound,
  CircleCheck
} from "@element-plus/icons-vue";
import {} from "@/api/modules/dynamicManagement";
import {
  getUserDynamicsList,
  cancelFollewed,
  toggleFollowUser,
  getMutualAttention,
  addTransferCount,
  getCouponList,
  setFriendCoupon,
  saveComment,
  commentList,
  type CommentListParams,
  getUserByPhone,
  reportUserViolation,
  uploadImg,
  likeDynamicNew,
  unlikeDynamicNew,
  blockUser
} from "@/api/modules/newLoginApi";
import { useUserStore } from "@/stores/modules/user";
import { localGet } from "@/utils";
import { normalizeCommonCommentListResponse, countTopAndNestedComments } from "@/utils/commonCommentList";

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

// 从路由参数获取用户信息
const targetUserId = ref((route.query.userId as string) || "");
const targetPhoneId = ref((route.query.phoneId as string) || "");
const targetUserName = ref((route.query.userName as string) || "");
const targetUserAvatar = ref((route.query.userAvatar as string) || "");
const targetUserPhone = ref((route.query.phone as string) || "");

// 接口定义
interface MediaItem {
  url: string;
  type: "image" | "video";
}

interface ContentItem {
  id: number;
  title: string;
  coverUrl: string;
  viewCount: number;
  likeCount: number;
  isLiked: boolean;
  isLike?: string; // "0" 或 "1"
  createTime: string;
  commentCount?: number;
  mediaList?: MediaItem[];
  dianzanCount: number;
}

interface ShareFriend {
  id: number;
  name: string;
  avatar: string;
  phoneId?: string;
}

// 响应式数据
const activeTab = ref("dynamic");
const contentList = ref<ContentItem[]>([]);
const isFollowed = ref(false); // 是否已关注
const isFriend = ref(false); // 是否互为好友（互相关注）

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

// 视频轮播相关
const videoRefs = ref<HTMLVideoElement[]>([]);
const currentCarouselIndex = ref(0);

// 举报对话框相关
const reportDialogVisible = ref(false);
const reportSubmitting = ref(false);
const reportForm = reactive({
  reason: "用户头像", // 默认选择第一个选项
  description: "",
  fileList: [] as any[],
  agreed: false
});

// 评论相关
const commentDrawerVisible = ref(false);
const commentListData = ref<any[]>([]);
const commentInput = ref("");
const commentSubmitting = ref(false);
const replyingComment = ref<any>(null);

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

// 用户信息
const userInfo = reactive({
  name: targetUserName.value || "用户主页",
  avatar: targetUserAvatar.value,
  jianjie: "",
  followCount: 0, // 关注数
  fansCount: 0, // 粉丝数
  likeCount: 0 // 获赞数
});

// 当前主页用户是否为商家（phoneId 以 store_ 开头）
const isStoreUser = computed(() => !!targetPhoneId.value && targetPhoneId.value.startsWith("store_"));

// 判断是否是当前用户自己的主页
const isMyPage = computed(() => {
  const currentUserStoreId = userStore.userInfo?.storeId;
  const targetStoreId = targetUserId.value; // 目标用户的storeUserId

  console.log("===== isMyPage 判断 =====");
  console.log("当前用户storeId:", currentUserStoreId);
  console.log("目标用户storeUserId:", targetStoreId);

  // 通过 storeId 和 storeUserId 判断是否是当前用户的主页
  const result = currentUserStoreId == targetStoreId;
  console.log("是否是自己的主页:", result);

  return result;
});

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

// 计算分页后的列表
const paginatedList = computed(() => {
  return contentList.value;
});

// 标签切换
const handleTabClick = () => {
  pagination.page = 1;
  loadContentList();
};

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

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

// 点击卡片
const handleCardClick = async (item: any) => {
  try {
    // 解析媒体列表（支持多张图片和视频）
    const mediaUrl = item.imagePath || item.coverUrl || "";
    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");

    currentDetail.value = {
      ...item,
      mediaList,
      coverUrl: firstUrl,
      type: isVideo ? "video" : "image"
    };

    detailDrawerVisible.value = true;

    // 重置轮播索引
    currentCarouselIndex.value = 0;

    // 打开抽屉时立即加载评论列表
    await loadCommentList();
  } 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;
    videoRefs.value = [];
  }, 300);
};

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

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

// 视频播放
const handleVideoPlay = (index: number) => {
  // 暂停其他视频
  videoRefs.value.forEach((video, i) => {
    if (i !== index && video && !video.paused) {
      video.pause();
    }
  });
};

// 详情页点赞
const handleDetailLike = () => {
  if (!currentDetail.value) return;

  currentDetail.value.isLiked = !currentDetail.value.isLiked;
  currentDetail.value.likeCount += currentDetail.value.isLiked ? 1 : -1;

  ElMessage.success(currentDetail.value.isLiked ? "点赞成功" : "取消点赞");
};

// 显示评论
const handleShowComments = async () => {
  if (!currentDetail.value) return;
  commentDrawerVisible.value = true;
  await loadCommentList();
};

// 加载评论列表
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 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 // 1表示评论点赞
    };

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

    // 切换点赞状态
    comment.isLiked = !comment.isLiked;
    comment.likeCount += comment.isLiked ? 1 : -1;

    ElMessage.success(comment.isLiked ? "点赞成功" : "取消点赞");
  } 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 = "";
};

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

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

  try {
    commentSubmitting.value = true;

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

    // 判断是回复评论还是评论动态
    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: phoneId
    };

    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 handleShare = async () => {
  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 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);
  }
};

// 确认分享
const handleConfirmShare = async () => {
  if (selectedFriends.value.length === 0) {
    ElMessage.warning("请选择要分享的好友");
    return;
  }

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

  try {
    shareSubmitting.value = true;

    // 调用 addTransferCount 接口，传递动态 id
    const res: any = await addTransferCount({
      id: currentDetail.value.id
    });

    if (res.code === 200) {
      ElMessage.success(`已分享给 ${selectedFriends.value.length} 位好友`);
      shareDialogVisible.value = false;

      // 可以在这里更新动态的分享数（如果需要的话）
      console.log("分享成功，动态ID:", currentDetail.value.id);
    } 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 handleFollow = async () => {
  try {
    // 获取当前用户的手机号，并在前面拼接 "store_"
    const phone = userStore.userInfo?.phone || "";
    const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;

    // 根据当前状态调用不同接口
    if (isFollowed.value) {
      // 已关注 → 取消关注
      await cancelFollewed({
        followedId: targetPhoneId.value, // 被关注用户phoneId
        fansId: currentUserPhoneId // 当前用户phoneId (格式: store_xxx)
      });
      isFollowed.value = false;
      ElMessage.success("取消关注成功");
    } else {
      // 未关注 → 关注
      await toggleFollowUser({
        followedId: targetPhoneId.value, // 被关注用户phoneId
        fansId: currentUserPhoneId, // 当前用户phoneId (格式: store_xxx)
        fansType: 2 // 2表示关注
      });
      isFollowed.value = true;
      ElMessage.success("关注成功");
    }
  } catch (error) {
    console.error("关注操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 详情页关注（右侧操作栏）
const handleFollowInDetail = async () => {
  try {
    const phone = userStore.userInfo?.phone || "";
    const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;

    await toggleFollowUser({
      followedId: targetPhoneId.value,
      fansId: currentUserPhoneId,
      fansType: 2
    });

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

// 更多操作菜单
const handleCommand = (command: string) => {
  switch (command) {
    case "gift":
      handleGiftCoupon();
      break;
    case "report":
      handleReportUser();
      break;
    case "block":
      handleBlockUserClick();
      break;
  }
};

// 赠券弹窗相关（按设计：赠送类型 + 多行优惠券）
const giftCouponDialogVisible = ref(false);
const giftFriendList = ref<{ id: number | string; name: string; phoneId?: string }[]>([]);
const giftFriendListLoading = ref(false);
const giftCouponList = ref<{ id: number | string; name: string; singleQty?: number }[]>([]);
const giftCouponListLoaded = ref(false);
const giftCouponListLoading = ref(false);
let giftCouponRowKey = 0;
const giftCouponFormData = reactive<{
  friendId: string | number;
  giftType: 1 | 2; // 1-满减券 2-折扣券（与 zengJuan/index 一致）
  rows: { key: number; couponId: string | number; quantity: number }[];
}>({
  friendId: "",
  giftType: 1,
  rows: [{ key: ++giftCouponRowKey, couponId: "", quantity: 0 }]
});

const loadGiftFriendList = async () => {
  giftFriendListLoading.value = true;
  try {
    const phone = userStore.userInfo?.phone || "";
    const fansId = phone.startsWith("store_") ? phone : `store_${phone}`;
    const res: any = await getMutualAttention({ page: 1, size: 999, fansId, name: "" });
    if (res?.code === 200) {
      const records = res.data?.records || res.data?.list || res.data || [];
      giftFriendList.value = records.map((item: any) => ({
        id: item.id ?? item.userId,
        name: item.username ?? item.userName ?? item.nickname ?? "用户",
        phoneId: item.phoneId ?? item.fansId
      }));
      const target = giftFriendList.value.find(
        (f: any) => String(f.phoneId) === targetPhoneId.value || String(f.id) === targetUserId.value
      );
      if (target) giftCouponFormData.friendId = target.id;
    } else {
      giftFriendList.value = [];
    }
  } catch {
    giftFriendList.value = [];
  } finally {
    giftFriendListLoading.value = false;
  }
};

const loadGiftCouponList = async (giftType: 1 | 2 = giftCouponFormData.giftType) => {
  giftCouponListLoading.value = true;
  try {
    const storeId = localGet("createdId") || userStore.userInfo?.storeId || userStore.userInfo?.createdId;
    // 与 zengJuan/index 一致：getFriendCouponList 即 getStoreAllCouponListPaginateNot，传参 storeId、status、type、couponType
    const params = {
      storeId,
      status: 0,
      type: 1,
      couponType: giftType
    };

    const res: any = await getCouponList(params);
    if (res?.code === 200) {
      const list = res.data?.records ?? res.data?.list ?? res.data ?? [];
      const rawList = Array.isArray(list) ? list : [];
      if (giftType === 1) {
        // 满减券：id 用 couponId，提交时传 couponId
        giftCouponList.value = rawList.map((item: any) => ({
          id: item.couponId ?? item.id,
          name: item.name ?? item.couponName ?? "",
          singleQty: item.singleQty != null ? Number(item.singleQty) : 100
        }));
      } else {
        // 折扣券：id 用 voucherId，提交时传 voucherId
        giftCouponList.value = rawList.map((item: any) => ({
          id: item.voucherId ?? item.id ?? item.couponId,
          name: item.name ?? item.couponName ?? "",
          singleQty: item.singleQty != null ? Number(item.singleQty) : 100
        }));
      }
    } else {
      giftCouponList.value = [];
      giftCouponListLoaded.value = true;
    }
  } catch {
    giftCouponList.value = [];
  } finally {
    giftCouponListLoading.value = false;
  }
};

// 切换赠送类型时：清空列表、重置行（与 zengJuan handleTabClick 一致）
const onGiftTypeChange = () => {
  giftCouponList.value = [];
  giftCouponListLoaded.value = false;
  giftCouponFormData.rows = [{ key: ++giftCouponRowKey, couponId: "", quantity: 0 }];
  loadGiftCouponList(giftCouponFormData.giftType);
};

const addGiftCouponRow = () => {
  giftCouponFormData.rows.push({
    key: ++giftCouponRowKey,
    couponId: "",
    quantity: 0
  });
};

const removeGiftCouponRow = (index: number) => {
  giftCouponFormData.rows.splice(index, 1);
};

// 判断该券是否已被其他行选中（当前行可选，其他行已选则禁用）
const isGiftCouponSelectedInOtherRow = (couponId: string | number, currentRowIndex: number) => {
  return giftCouponFormData.rows.some(
    (row, i) => i !== currentRowIndex && row.couponId !== "" && row.couponId != null && String(row.couponId) === String(couponId)
  );
};

// 根据所选券的 singleQty 限制该行数量上限
const getGiftRowMaxQuantity = (row: { couponId: string | number; quantity: number }) => {
  if (row.couponId === "" || row.couponId == null) return 100;
  const coupon = giftCouponList.value.find((c: any) => String(c.id) === String(row.couponId));
  const max = coupon?.singleQty != null ? Number(coupon.singleQty) : 100;
  return Math.max(1, max);
};

// 切换所选券时，若当前数量超过新券 singleQty 则自动压到上限
const onGiftRowCouponChange = (row: { couponId: string | number; quantity: number }) => {
  const max = getGiftRowMaxQuantity(row);
  if (row.quantity > max) row.quantity = max;
};

// 输入时即时限制：不允许超出最大数量；允许先清空再输入其他数字（空时暂存为 0，展示为空）
const setGiftRowQuantity = (row: { couponId: string | number; quantity: number }, val: string | number | undefined) => {
  const max = getGiftRowMaxQuantity(row);
  if (val === "" || val == null || Number.isNaN(Number(val))) {
    row.quantity = 0; // 允许清空，便于用户删除后输入新数量
    return;
  }
  const num = Number(val);
  row.quantity = Math.min(Math.max(1, num), max);
};

// 严格校验：赠送对象存在 + 至少一行已选券且数量有效 + 每一行要么未选券（可忽略）要么已选券且数量有效，不允许存在「未选券但占着一行」的不完整行
const canSubmitGiftCoupon = computed(() => {
  if (!giftCouponFormData.friendId) return false;
  const validRows = giftCouponFormData.rows.filter(r => r.couponId !== "" && r.couponId != null && r.quantity >= 1);
  if (validRows.length < 1) return false;
  // 存在未选券的行则不允许提交（避免一行有券、一行没选券仍能点确定）
  const hasIncompleteRow = giftCouponFormData.rows.some(r => (r.couponId === "" || r.couponId == null) && r.quantity >= 1);
  return !hasIncompleteRow;
});

const closeGiftCouponDialog = () => {
  giftCouponDialogVisible.value = false;
  giftCouponFormData.friendId = "";
  giftCouponFormData.giftType = 1;
  giftCouponFormData.rows = [{ key: ++giftCouponRowKey, couponId: "", quantity: 0 }];
  giftCouponListLoaded.value = false;
};

const handleGiftCouponSubmit = async () => {
  if (!giftCouponFormData.friendId) {
    ElMessage.warning("数据填写不完整，无法确定赠送对象");
    return;
  }
  const validRows = giftCouponFormData.rows.filter(r => r.couponId !== "" && r.couponId != null && r.quantity >= 1);
  if (validRows.length === 0) {
    ElMessage.warning("数据填写不完整，请至少选择一张优惠券并填写数量");
    return;
  }
  const hasIncompleteRow = giftCouponFormData.rows.some(r => (r.couponId === "" || r.couponId == null) && r.quantity >= 1);
  if (hasIncompleteRow) {
    ElMessage.warning("数据填写不完整，请为每一行选择优惠券或删除未选券的行");
    return;
  }
  if (!canSubmitGiftCoupon.value) {
    ElMessage.warning("数据填写不完整，请至少选择一张优惠券并填写数量");
    return;
  }
  try {
    // 与 zengJuan setFriendCoupons 一致：couponIds 为 { couponId, singleQty } 或 { voucherId, singleQty }，friendStoreUserId 为好友 storeId
    const isVoucher = giftCouponFormData.giftType === 2;
    const couponIds = validRows.map(r =>
      isVoucher ? { couponId: r.couponId, singleQty: r.quantity } : { couponId: r.couponId, singleQty: r.quantity }
    );
    const params = {
      couponIds,
      friendStoreUserId: String(giftCouponFormData.friendId)
    };
    const res: any = await setFriendCoupon(params);
    if (res?.code === 200) {
      ElMessage.success("赠送成功");
      closeGiftCouponDialog();
    } else {
      ElMessage.error(res?.msg || "赠送失败");
    }
  } catch (error: any) {
    console.error("赠送失败:", error);
    ElMessage.error(error?.message || "赠送失败");
  }
};

// 赠券：打开赠送好友优惠券弹窗（不跳转）
const handleGiftCoupon = () => {
  giftCouponDialogVisible.value = true;
  loadGiftFriendList();
  loadGiftCouponList(1);
};

// 切换满减券/折扣券时：清空下拉列表、只保留一行选择（与 zengJuan 一致）
watch(
  () => giftCouponFormData.giftType,
  () => {
    giftCouponList.value = [];
    giftCouponListLoaded.value = false;
    giftCouponFormData.rows = [{ key: ++giftCouponRowKey, couponId: "", quantity: 0 }];
  }
);

// 举报用户
const handleReportUser = () => {
  reportDialogVisible.value = true;
};

// 举报动态（从详情页）
const handleReportDynamic = () => {
  reportDialogVisible.value = true;
};

// 拉黑用户（点击菜单项）
const handleBlockUserClick = () => {
  handleBlockUser(false);
};

// 从详情页拉黑用户
const handleBlockUserFromDrawer = () => {
  handleBlockUser(false);
};

// 拉黑用户
const handleBlockUser = async (skipConfirm: boolean = false) => {
  try {
    if (!skipConfirm) {
      await ElMessageBox.confirm("拉黑后将不再看到该用户的动态，确定要拉黑吗？", "拉黑确认", {
        confirmButtonText: "确定拉黑",
        cancelButtonText: "取消",
        type: "warning"
      });
    }

    const phone = userStore.userInfo?.phone || "";
    const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;
    const currentUserId = userStore.userInfo?.id || userStore.userInfo?.userId || "";
    const currentUserType = userStore.userInfo?.userType || userStore.userInfo?.type || 1;

    // 从 targetPhoneId 解析被拉黑用户类型
    const prefix = targetPhoneId.value.split("_")[0];
    const blockedUserType = prefix === "store" ? 1 : 2;

    await blockUser({
      blockerType: currentUserType,
      blockedType: blockedUserType,
      blockerId: currentUserId,
      blockedId: targetUserId.value
    });

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

    // 返回上一页
    router.back();
  } catch (error) {
    if (!skipConfirm && error !== "cancel") {
      console.error("拉黑失败:", error);
      ElMessage.error("拉黑失败");
    } else if (skipConfirm) {
      throw error;
    }
  }
};

// 举报图片预览
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;
  }

  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;

    // 从 targetPhoneId 解析被举报用户类型
    const prefix = targetPhoneId.value.split("_")[0];
    const reportedUserType = prefix === "store" ? 1 : 2;

    // 根据手机号获取被举报人ID
    let reportedUserId = targetUserId.value;
    if (targetUserPhone.value) {
      try {
        const userRes = await getUserByPhone({ phone: targetUserPhone.value });
        const userData = userRes.data as any;
        if (userData && userData.id) {
          reportedUserId = userData.id;
        }
      } catch (error) {
        console.error("获取被举报人ID失败:", error);
      }
    }

    await reportUserViolation({
      dynamicsId: 0, // 举报用户不需要dynamicsId
      reportContextType: "1", // 1表示举报用户
      violationType: violationType,
      otherReasonContent: reportForm.reason === "其他举报" ? reportForm.description : "",
      reportEvidenceImg: reportEvidenceImg,
      reportedUserId: reportedUserId,
      reportedUserType: reportedUserType,
      reportingUserId: currentUserId,
      reportingUserType: currentUserType
    });

    if (reportForm.agreed) {
      try {
        await handleBlockUser(true);
        ElMessage.success("举报提交成功，已拉黑该用户");
      } catch (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 loadContentList = async () => {
  try {
    if (!targetPhoneId.value) {
      ElMessage.warning("用户信息异常");
      return;
    }

    // 获取当前登录用户的phoneId
    const phone = userStore.userInfo?.phone || "";
    const currentUserPhoneId = phone.startsWith("store_") ? phone : `store_${phone}`;

    console.log("目标用户phoneId:", targetPhoneId.value);

    const res = await getUserDynamicsList({
      myselfPhoneId: currentUserPhoneId, // 当前登录用户的phoneId
      phoneId: targetPhoneId.value, // 目标用户的phoneId
      type: 2,
      page: pagination.page,
      size: pagination.pageSize
    });

    if (res.data) {
      const responseData = res.data as any;
      const list = responseData.lifeUserDynamics || [];

      // 更新用户信息（从 storeUser 字段）
      if (responseData.storeUser) {
        const storeUserData = responseData.storeUser;
        userInfo.name = storeUserData.storeName || storeUserData.userName || storeUserData.name || userInfo.name;
        userInfo.avatar = storeUserData.avatar || storeUserData.headImg || userInfo.avatar;
        userInfo.jianjie = storeUserData.jianjie || storeUserData.storeBlurb || storeUserData.bio || userInfo.jianjie || "";
        userInfo.followCount = responseData.followListSum || 0;
        userInfo.fansCount = responseData.fansListSum || 0;
        userInfo.likeCount = responseData.likeListSum || 0;
      }

      // 更新关注状态（0未关注，1已关注）
      const isFollowedValue = responseData.isFollowed ?? responseData.isFollow ?? 0;
      isFollowed.value = isFollowedValue === 1;

      contentList.value = list.map((item: any) => ({
        id: item.id || item.dynamicId,
        title: item.title || item.content || item.dynamicContent || "",
        coverUrl: item.imagePath || item.coverUrl || "",
        likeCount: item.likeCount || item.praiseCount || 0,
        isLiked: item.isLiked || item.isPraise || false,
        createTime: item.createTime || item.createDate || "",
        dianzanCount: item.dianzanCount || 0
      }));

      pagination.total = responseData.total || responseData.totalCount || list.length;
    }
  } catch (error) {
    console.error("加载动态失败:", error);
    ElMessage.error("加载动态失败");
  }
};

// 加载是否与当前主页用户互为好友（用于展示赠券入口）
const loadIsFriend = async () => {
  if (!targetPhoneId.value) return;
  try {
    const phone = userStore.userInfo?.phone || "";
    const fansId = phone.startsWith("store_") ? phone : `store_${phone}`;
    const res: any = await getMutualAttention({
      page: 1,
      size: 1000,
      fansId,
      name: ""
    });
    if (res?.code === 200) {
      const dataList = res.data?.records || res.data?.list || res.data || [];
      isFriend.value = dataList.some(
        (item: any) => (item.phoneId || item.fansId || item.storeUserId || "") === targetPhoneId.value
      );
    }
  } catch {
    isFriend.value = false;
  }
};

// 初始化
onMounted(() => {
  loadContentList();
  loadIsFriend();
});
</script>

<style scoped lang="scss">
.user-dynamic-container {
  min-height: calc(100vh - 120px);
  padding: 20px;
  background: #ffffff;

  // 用户信息卡片
  .user-card {
    padding: 24px;
    margin-bottom: 20px;
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    .user-header {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      margin-bottom: 16px;
      .user-avatar-section {
        display: flex;
        flex: 1;
        gap: 16px;
        align-items: center;
        .user-avatar-large {
          display: flex;
          flex-shrink: 0;
          align-items: center;
          justify-content: center;
          width: 80px;
          height: 80px;
          overflow: hidden;
          background: #f5f7fa;
          border-radius: 50%;
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        .user-info-text {
          flex: 1;
          .user-name {
            margin-bottom: 8px;
            font-size: 20px;
            font-weight: 600;
            color: #303133;
          }
          .user-stats {
            display: flex;
            gap: 8px;
            align-items: center;
            font-size: 14px;
            color: #606266;
            .stat-item {
              cursor: pointer;
              transition: color 0.3s;
              &:hover {
                color: #409eff;
              }
            }
            .stat-divider {
              color: #dcdfe6;
            }
          }
        }
      }
      .user-actions {
        display: flex;
        gap: 12px;
        align-items: center;
        :deep(.el-button) {
          min-width: 80px;
        }
      }
    }
    .user-bio {
      font-size: 14px;
      line-height: 1.6;
      color: #606266;
    }
  }

  // 标签页区域
  .tabs-section {
    margin-bottom: 20px;
    border-bottom: 1px solid #e4e7ed;
    :deep(.el-tabs) {
      .el-tabs__header {
        margin-bottom: 0;
      }
      .el-tabs__nav-wrap::after {
        display: none;
      }
    }
  }

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

  // 内容网格布局
  .content-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;

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

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

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

  // 内容卡片
  .content-card {
    cursor: pointer;
    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);
    }

    // 封面区域
    .content-cover-wrapper {
      position: relative;
      width: 100%;
      aspect-ratio: 16 / 9;
      margin-bottom: 8px;
      overflow: hidden;
      background: #f5f7fa;
      border-radius: 8px;
      .content-cover {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .cover-placeholder {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
      }
    }

    // 底部信息
    .content-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 4px;
      .footer-left {
        display: flex;
        gap: 4px;
        align-items: center;
        padding-top: 5px;
      }
      .footer-right {
        display: flex;
        gap: 4px;
        align-items: center;
        padding-top: 5px;
      }
      .view-count,
      .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 {
            font-size: 15px;
            line-height: 1.6;
            color: #ffffff;
            p {
              margin: 0;
            }
          }
        }
      }

      // 右侧操作栏
      .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: default;
            &:hover {
              transform: none;
            }
          }
          .action-avatar {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 48px;
            height: 48px;
            overflow: visible;
            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 / 20%);
    .more-actions-menu {
      .menu-item {
        display: flex;
        gap: 8px;
        align-items: center;
        padding: 10px 16px;
        font-size: 14px;
        color: #ffffff;
        cursor: pointer;
        transition: background 0.3s;
        &:hover {
          background: rgb(255 255 255 / 10%);
        }
        .el-icon {
          font-size: 18px;
        }
      }
    }
  }

  // 举报对话框和分享对话框
  :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;
          }
        }
      }
    }

    // 分享对话框
    .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;
          }
        }
      }
    }
    .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%;
    }
  }
}
.gift-coupon-dialog-body {
  .gift-type-section,
  .coupon-rows-section {
    margin-bottom: 20px;
  }
  .section-label {
    margin-bottom: 12px;
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
  }
  .coupon-row {
    display: flex;
    gap: 12px;
    align-items: center;
    align-items: start;
    margin-bottom: 12px;
    .quantity-cell {
      display: flex;
      flex-shrink: 0;
      flex-direction: column;
      gap: 4px;
    }
    .quantity-input {
      width: 140px;
    }
    .quantity-limit-hint {
      font-size: 12px;
      line-height: 1.2;
      color: var(--el-color-warning);
    }
  }
  .add-coupon-btn {
    display: inline-flex;
    gap: 4px;
    align-items: center;
    padding-left: 0;
    color: var(--el-color-primary);
  }
}
</style>

<style scoped>
@import "@/assets/dianzanFont/iconfont.css";
</style>
