<template>
  <div class="notification-drawer-content">
    <!-- 顶部 Tab：通知 / 消息 -->
    <div class="drawer-tabs">
      <div class="tab-item" :class="{ active: activeTab === 'notice' }" @click="activeTab = 'notice'">通知</div>
      <div class="tab-item" :class="{ active: activeTab === 'message' }" @click="activeTab = 'message'">消息</div>
    </div>

    <div class="drawer-body">
      <!-- 左侧分类：通知 Tab 与 消息 Tab 不同 -->
      <div class="drawer-side">
        <template v-if="activeTab === 'notice'">
          <div
            v-for="cat in noticeCategories"
            :key="cat.key"
            class="side-item"
            :class="{ active: activeCategory === cat.key }"
            @click="switchNoticeCategory(cat.key)"
          >
            <el-icon class="side-icon">
              <component :is="cat.icon" />
            </el-icon>
            <span class="side-text">{{ cat.title }}</span>
            <el-badge v-if="cat.unread > 0" :value="cat.unread" class="side-badge" />
          </div>
        </template>
        <template v-else>
          <div
            v-for="cat in messageCategories"
            :key="cat.key"
            class="side-item"
            :class="{ active: messageCategory === cat.key }"
            @click="switchMessageCategory(cat.key)"
          >
            <el-icon class="side-icon">
              <component :is="cat.icon" />
            </el-icon>
            <span class="side-text">{{ cat.title }}</span>
            <el-badge v-if="cat.unread > 0" :value="handleReadCount(cat.unread)" class="side-badge" />
          </div>
        </template>
      </div>

      <!-- 右侧：通知列表（系统通知/订单提醒：卡片式；互动：头像+发送者+内容+日期） -->
      <div v-if="activeTab === 'notice'" class="drawer-main-wrap">
        <div class="drawer-main">
          <div v-if="currentLoading" class="empty-tip">
            <el-icon class="is-loading" :size="24">
              <Loading />
            </el-icon>
            <span style="margin-left: 8px">加载中...</span>
          </div>
          <template v-else>
            <!-- 系统通知、订单提醒：卡片式 -->
            <template v-if="activeCategory !== 'related'">
              <div
                v-for="(item, index) in currentList"
                :key="item.id + '_' + index"
                class="notice-card"
                :class="{ unread: item.unread }"
              >
                <div class="card-row">
                  <span class="card-title">
                    {{ item.title }}
                    <span v-if="item.unread" class="unread-dot" />
                  </span>
                  <span class="card-date">{{ item.date }}</span>
                </div>
                <div class="card-content">
                  {{ processContent(item) }}
                </div>
                <div class="card-actions">
                  <el-button size="small" @click="handleViewDetail(item)"> 查看详情 </el-button>
                  <!-- <el-button size="small" @click="handleDelete(item, index)"> 删除 </el-button> -->
                </div>
              </div>
            </template>
            <!-- 互动：头像+发送者+内容+日期+删除（与商家端 inform 列表一致） -->
            <template v-else>
              <div
                v-for="(item, index) in currentList"
                :key="item.id + '_' + index"
                class="message-card"
                :class="{ unread: item.unread }"
                @click.stop="handleAvatarClick(item)"
              >
                <div class="message-avatar avatar-clickable">
                  <el-avatar :size="40" :src="item.userImage">
                    <el-icon><UserFilled /></el-icon>
                  </el-avatar>
                  <span v-if="item.unread" class="unread-dot message-unread-dot" />
                </div>
                <div class="message-body">
                  <div class="message-row">
                    <span class="message-sender">{{ item.userName || item.title || "未知" }}</span>
                    <span class="message-date">{{ item.date }}</span>
                  </div>
                  <div class="message-content" v-if="item.title == '关注通知' || item.title == '动态通知'">
                    {{ item.userName }} {{ item.content }}
                  </div>
                  <div class="message-content" v-else>
                    {{ processContent(item) }}
                  </div>
                  <div class="message-actions">
                    <el-button size="small" type="default" @click.stop="handleDelete(item, index)"> 删除 </el-button>
                  </div>
                </div>
              </div>
            </template>
            <div v-if="currentList.length === 0" class="empty-tip">暂无数据</div>
          </template>
        </div>
        <div v-if="currentPagination.total > 0" class="pagination-wrap">
          <el-pagination
            :current-page="currentPagination.pageNum"
            :page-size="currentPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="currentPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            small
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>

      <!-- 右侧：消息列表（如图：头像 + 发送者 + 红点 + 内容 + 日期 + 删除） -->
      <div v-else class="drawer-main-wrap">
        <div class="drawer-main">
          <div v-if="messageLoading" class="empty-tip">
            <el-icon class="is-loading" :size="24">
              <Loading />
            </el-icon>
            <span style="margin-left: 8px">加载中...</span>
          </div>
          <!-- @click="handleMessageItemClick(item)" -->
          <template v-else>
            <div
              v-for="(item, index) in currentMessageList"
              :key="item.id + '_' + index"
              class="message-card message-card-clickable"
              :class="{ unread: item.unread }"
              @click="handleMessageItemClick(item)"
            >
              <div class="message-avatar">
                <el-avatar :size="40" :src="item.avatar">
                  <el-icon><UserFilled /></el-icon>
                </el-avatar>
              </div>
              <div class="message-body">
                <div class="message-row">
                  <span class="message-sender">{{ item.senderName }}</span>
                  <span class="message-date">{{ item.date }}</span>
                </div>
                <div class="message-content-row">
                  <span class="message-content">{{ processContent(item) }}</span>
                  <div class="message-status">
                    <!-- 非免打扰：显示数字徽标 -->
                    <span v-if="item.isNotDisturb !== '1' && (item.notReadCount ?? 0) > 0" class="message-count">
                      {{ handleReadCount(item.notReadCount!) }}
                    </span>
                    <!-- 免打扰：显示小红点 -->
                    <span v-else-if="item.isNotDisturb === '1' && (item.notReadCount ?? 0) > 0" class="message-dot" />
                  </div>
                </div>
                <!-- 未关注人消息、消息列表：删除按钮（接口 deleteMessageByPhoneId） -->
                <div class="message-actions">
                  <el-button size="small" type="default" @click.stop="handleDeleteMessage(item, index)"> 删除 </el-button>
                </div>
              </div>
            </div>
            <div v-if="currentMessageList.length === 0" class="empty-tip">暂无数据</div>
          </template>
        </div>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" :title="currentDetail?.title" width="500px">
      <div class="detail-dialog-content" v-if="currentDetail?.title == '关注通知' || currentDetail?.title == '动态通知'">
        {{ currentDetail?.userName }} {{ currentDetail?.content }}
      </div>
      <div class="detail-dialog-content" v-else>
        <div style="font-size: 14px; font-weight: bold; text-align: left">
          {{ currentDetail?.createTime }}
        </div>
        {{ currentDetail?.content }}
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, markRaw } from "vue";
import { useRouter } from "vue-router";
import { House, List, User, Loading, Message, UserFilled } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { localGet } from "@/utils";
import {
  getNoticeListForHeader,
  readNoticeById,
  deleteNoticeById,
  getCountUnreadByType,
  getMessageList,
  getStrangerMessageNum,
  deleteMessageByPhoneId
} from "@/api/modules/headerNotice";
import type { NoFriendMessageItem } from "@/api/modules/headerNotice";

const emit = defineEmits<{ (e: "close"): void }>();
const router = useRouter();

interface NoticeItem {
  id: string;
  title: string;
  content: string;
  date: string;
  unread: boolean;
  /** 原始创建时间（接口返回 createdTime） */
  createTime?: string;
  /** 意见反馈回复通知：context 中的 feedbackId，用于跳转反馈详情 */
  feedbackId?: string | number;
  /** 互动类：发送者信息，用于跳转动态主页 */
  userName?: string;
  userImage?: string;
  userId?: string | number;
  phoneId?: string;
  storeUserId?: string | number;
  /** 类型，用于 processContent 展示 */
  type?: string;
}

interface MessageItem {
  id: string;
  senderName: string;
  content: string;
  date: string;
  unread: boolean;
  /** 未读数量，用于展示红点/数字 */
  notReadCount?: number;
  /** 免打扰：'0' 非免打扰显示数字，'1' 免打扰显示小红点（与商家端一致） */
  isNotDisturb?: string;
  avatar?: string;
  /** 发送方 phoneId，用于跳转聊天页 */
  phoneId?: string;
  /** 发送方 id，用于跳转聊天页 */
  senderId?: string;
  /** 消息类型，用于 processContent 展示 */
  type?: string;
  /** 语音时长等，用于 getVoiceDuration */
  voiceDuration?: number;
  duration?: number;
  [key: string]: any;
}

const activeTab = ref<"notice" | "message">("notice");
const activeCategory = ref("system");
const messageCategory = ref("unfollowed");

// 通知 Tab 分类
const noticeTypeByKey: Record<string, number> = {
  system: 1,
  order: 2,
  related: 0
};
// 与商家端一致：系统通知、订单提醒、互动（其余通知均为互动类别）。icon 用 markRaw 避免被转为响应式触发 Vue 警告
const noticeCategories = ref([
  { key: "system", title: "系统通知", icon: markRaw(House), unread: 0 },
  { key: "order", title: "订单提醒", icon: markRaw(List), unread: 0 },
  { key: "related", title: "互动", icon: markRaw(User), unread: 0 }
]);

// 消息 Tab 分类（如图：未关注人消息、消息列表）
const messageCategories = ref([
  { key: "unfollowed", title: "未关注人消息", icon: markRaw(User), unread: 0 },
  { key: "messageList", title: "消息列表", icon: markRaw(Message), unread: 0 }
]);

const listByCategory = ref<Record<string, NoticeItem[]>>({
  system: [],
  order: [],
  related: []
});

// 消息列表数据：未关注人消息、消息列表均走接口
const messageListByCategory = ref<Record<string, MessageItem[]>>({
  unfollowed: [],
  messageList: []
});

const messageLoading = ref(false);

// 每个通知分类的分页与加载态
const paginationByCategory = ref<Record<string, { pageNum: number; pageSize: number; total: number }>>({
  system: { pageNum: 1, pageSize: 10, total: 0 },
  order: { pageNum: 1, pageSize: 10, total: 0 },
  related: { pageNum: 1, pageSize: 10, total: 0 }
});
const loadingByCategory = ref<Record<string, boolean>>({
  system: false,
  order: false,
  related: false
});

const detailVisible = ref(false);
const currentDetail = ref<NoticeItem | null>(null);

const currentList = computed(() => {
  return listByCategory.value[activeCategory.value] ?? [];
});

const currentPagination = computed(() => {
  return paginationByCategory.value[activeCategory.value] ?? { pageNum: 1, pageSize: 10, total: 0 };
});

const currentLoading = computed(() => {
  return loadingByCategory.value[activeCategory.value] ?? false;
});

const currentMessageList = computed(() => {
  return messageListByCategory.value[messageCategory.value] ?? [];
});

function switchNoticeCategory(key: string) {
  activeCategory.value = key;
  const list = listByCategory.value[key] ?? [];
  const loading = loadingByCategory.value[key];
  if (list.length === 0 && !loading) {
    paginationByCategory.value[key].pageNum = 1;
    fetchNoticeList(key);
  }
}

function switchMessageCategory(key: string) {
  messageCategory.value = key;
  if (key === "unfollowed") {
    fetchNoFriendMessage();
  } else if (key === "messageList") {
    fetchMessageList();
  }
}

// 未关注人消息：/message/getNoFriendMessage，参数 receiverId。映射与商家端 message-notices 一致
function mapNoFriendToMessageItem(item: NoFriendMessageItem): MessageItem {
  const createdTime = item.createdTime ?? "";
  const dateStr = createdTime.includes(" ") ? createdTime.split(" ")[0].replace(/-/g, "/") : createdTime.replace(/-/g, "/");
  const notReadCount = item.notReadCount ?? (item.isRead === 0 ? 1 : 0);
  return {
    id: String(item.id ?? ""),
    senderName: item.senderName ?? item.userName ?? "",
    content: item.content ?? "",
    date: dateStr,
    unread: item.isRead === 0,
    notReadCount,
    isNotDisturb: (item as any).isNotDisturb ?? "0",
    avatar: item.userImage ?? item.senderImg ?? item.storeImg ?? undefined,
    phoneId: (item as any).phoneId != null ? String((item as any).phoneId) : undefined,
    senderId: item.senderId != null ? String(item.senderId) : undefined,
    type: item.type,
    voiceDuration: (item as any).voiceDuration ?? (item as any).duration,
    duration: (item as any).duration
  };
}

// 未关注人消息未读数：使用 message/getStrangerMessageNum 接口，取 data.notReadCount
async function fetchUnfollowedUnreadCount() {
  const receiverId = getReceiverId();
  if (!receiverId) {
    const cat = messageCategories.value.find(c => c.key === "unfollowed");
    if (cat) cat.unread = 0;
    return;
  }
  try {
    const res: any = await getStrangerMessageNum({ receiverId: "store_" + receiverId });
    if (res?.mas == "暂无承载数据" || res?.msg == "暂无承载数据") {
      const cat = messageCategories.value.find(c => c.key === "unfollowed");
      if (cat) cat.unread = 0;
      return;
    }
    const data = res?.data ?? res;
    const notReadCount = data?.notReadCount ?? 0;
    const cat = messageCategories.value.find(c => c.key === "unfollowed");
    if (cat) cat.unread = Number(notReadCount) || 0;
  } catch (e) {
    const cat = messageCategories.value.find(c => c.key === "unfollowed");
    if (cat) cat.unread = 0;
  }
}

// 陌生人/未关注人消息列表：使用 message/getMessageList，friendType=2（与商家端 message-notFriend 一致）
async function fetchNoFriendMessage() {
  const receiverId = getReceiverId();
  if (!receiverId) {
    messageListByCategory.value.unfollowed = [];
    await fetchUnfollowedUnreadCount();
    return;
  }
  messageLoading.value = true;
  try {
    const res: any = await getMessageList({ receiverId: "store_" + receiverId, friendType: 2 });
    const data = res?.data ?? res;
    if (data?.msg == "暂无承载数据") {
      messageListByCategory.value.unfollowed = [];
      const cat = messageCategories.value.find(c => c.key === "unfollowed");
      if (cat) cat.unread = 0;
      return;
    }
    const rawList = Array.isArray(data) ? data : data ? [data] : [];
    const list: MessageItem[] = rawList.map((item: NoFriendMessageItem) => mapNoFriendToMessageItem(item));
    messageListByCategory.value.unfollowed = list;
    await fetchUnfollowedUnreadCount();
  } catch (e) {
    messageListByCategory.value.unfollowed = [];
    const cat = messageCategories.value.find(c => c.key === "unfollowed");
    if (cat) cat.unread = 0;
  } finally {
    messageLoading.value = false;
  }
}

// 消息列表：/message/getMessageList，friendType=1 仅返回已关注/好友消息（不包含未关注人，与商家端一致）
async function fetchMessageList() {
  const receiverId = getReceiverId();
  if (!receiverId) {
    messageListByCategory.value.messageList = [];
    const cat = messageCategories.value.find(c => c.key === "messageList");
    if (cat) cat.unread = 0;
    return;
  }
  messageLoading.value = true;
  try {
    const res: any = await getMessageList({ receiverId: "store_" + receiverId, friendType: 1 });
    const data = res?.data ?? res;
    const rawList = Array.isArray(data) ? data : data ? [data] : [];
    const list: MessageItem[] = rawList.map((item: NoFriendMessageItem) => mapNoFriendToMessageItem(item));
    messageListByCategory.value.messageList = list;
    const unreadTotal = rawList.reduce(
      (sum: number, item: NoFriendMessageItem) => sum + (item.notReadCount ?? (item.isRead === 0 ? 1 : 0)),
      0
    );
    const cat = messageCategories.value.find(c => c.key === "messageList");
    if (cat) cat.unread = unreadTotal;
  } catch (e) {
    messageListByCategory.value.messageList = [];
    const cat = messageCategories.value.find(c => c.key === "messageList");
    if (cat) cat.unread = 0;
  } finally {
    messageLoading.value = false;
  }
}

// 与原有通知页面一致的 receiverId
function getReceiverId(): string {
  return localGet("iphone") || localGet("geeker-user")?.userInfo?.phone || "";
}

// 未读数量展示：超过 99 显示 99（与商家端 handleReadCount 一致）
function handleReadCount(val: number): string {
  if (Number(val) > 99) return "99";
  return String(val);
}

// 点击消息列表项：关闭抽屉并跳转聊天页（与 storeDecoration 装修聊天一致，receiverId 用 phoneId）
function handleMessageItemClick(item: MessageItem) {
  const receiverId = item.phoneId ?? item.senderId;

  if (!receiverId) return;
  emit("close");
  const params = new URLSearchParams({
    receiverId: String(receiverId),
    uName: encodeURIComponent(item.senderName || "用户"),
    userImage: item.avatar ? encodeURIComponent(item.avatar) : ""
  });
  router.push(`/storeDecorationManagement/decorationChat?${params.toString()}`);
}

// 删除消息（未关注人消息、消息列表通用，接口 deleteMessageByPhoneId）
async function handleDeleteMessage(item: MessageItem, index: number) {
  const receiverId = getReceiverId();
  const senderId = item.phoneId ?? item.senderId;
  if (!receiverId || !senderId) {
    ElMessage.error("无法删除");
    return;
  }
  try {
    await ElMessageBox.confirm("确定要删除这条消息吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    await deleteMessageByPhoneId({
      receiverId: "store_" + receiverId,
      senderId: String(senderId)
    });
    const key = messageCategory.value;
    messageListByCategory.value[key] = currentMessageList.value.filter((_, i) => i !== index);
    const cat = messageCategories.value.find(c => c.key === key);
    if (cat && cat.unread > 0) cat.unread = Math.max(0, cat.unread - (item.notReadCount ?? 1));
    if (key === "unfollowed") await fetchUnfollowedUnreadCount();
    ElMessage.success("删除成功");
  } catch (e) {
    if (e !== "cancel" && e !== "close") ElMessage.error("删除失败");
  }
}

// 根据类型显示内容（与商家端一致）
function getVoiceDuration(item: { voiceDuration?: number; duration?: number; [key: string]: any }): string {
  const sec = item?.voiceDuration ?? item?.duration ?? 0;
  return sec ? `${sec}` : "0";
}
function processContent(item: { type?: string; content?: string; [key: string]: any }): string {
  switch (String(item.type ?? "")) {
    case "1":
      return item.content ?? "";
    case "2":
      return "[图片]";
    case "3":
      return "[分享]";
    case "4":
      return "[交易请求]";
    case "5":
      return "[签到]";
    case "6":
      return "[签到确认]";
    case "8":
      return "[视频]";
    case "9":
      return "[修改交易请求]";
    case "10":
      return "[定位共享]";
    case "11":
      return "[委托]";
    case "13":
      return "[语音]" + getVoiceDuration(item) + '"';
    default:
      return item.content ?? "";
  }
}

// 与原有通知页面一致的 context 解析
function parseContext(context: string | undefined): string {
  if (!context) return "";
  try {
    const parsed = typeof context === "string" ? JSON.parse(context) : context;
    return parsed?.message || context;
  } catch {
    return context;
  }
}

/** 从 context 解析 feedbackId（意见反馈回复通知） */
function parseFeedbackIdFromContext(context: string | undefined): string | number | undefined {
  if (!context) return undefined;
  try {
    const parsed = typeof context === "string" ? JSON.parse(context) : context;
    const id = parsed?.feedbackId;
    return id != null ? id : undefined;
  } catch {
    return undefined;
  }
}

// 互动类内容：商家端 context 可能为 "类型|split|内容1|split|内容2"，取第一段或解析 JSON
function getInteractionContent(context: string | undefined): string {
  if (!context) return "";
  if (typeof context === "string" && context.includes("|split|")) {
    return context.split("|split|")[0]?.trim() || context;
  }
  return parseContext(context);
}

// 统一请求：/alienStorePlatform/notice/getNoticeList，noticeType 系统=1、订单提醒=2、与我相关=0，分页查询
async function fetchNoticeList(catKey: string) {
  const receiverId = getReceiverId();
  if (!receiverId) {
    listByCategory.value[catKey] = [];
    paginationByCategory.value[catKey].total = 0;
    return;
  }
  const noticeType = noticeTypeByKey[catKey] ?? 1;
  const pagination = paginationByCategory.value[catKey];
  loadingByCategory.value[catKey] = true;
  try {
    const res: any = await getNoticeListForHeader({
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      receiverId: "store_" + receiverId,
      noticeType
    });
    const data = res?.data ?? res;
    const records = data?.records ?? data?.list ?? [];
    const total = data?.total ?? 0;
    const isRelated = catKey === "related";
    const list: NoticeItem[] = records.map((item: any) => {
      const rawContext = item.context ?? item.content ?? "";
      const content = isRelated ? getInteractionContent(rawContext) : parseContext(rawContext);
      const dateRaw = item.createdTime ?? "";
      const dateStr = dateRaw.includes(" ") ? dateRaw.split(" ")[0].replace(/-/g, "/") : dateRaw.replace(/-/g, "/");
      const feedbackId = parseFeedbackIdFromContext(rawContext);
      return {
        id: String(item.id),
        title: item.title ?? "",
        content,
        date: dateStr,
        unread: !item.isRead,
        createTime: item.createdTime ?? "",
        type: item.type,
        ...(feedbackId != null && { feedbackId }),
        ...(isRelated && {
          userName: item.userName ?? item.senderName ?? item.title ?? "",
          userImage: item.userImage ?? item.storeImg ?? item.senderImg,
          userId: item.userId ?? item.storeUserId,
          phoneId: item.phoneId ?? item.senderId,
          storeUserId: item.storeUserId ?? item.userId
        })
      };
    });
    listByCategory.value[catKey] = list;
    paginationByCategory.value[catKey].total = total;
  } catch (e) {
    listByCategory.value[catKey] = [];
    paginationByCategory.value[catKey].total = 0;
  } finally {
    loadingByCategory.value[catKey] = false;
  }
}

// 按类型拉取未读数量：noticeType 0-与我相关 1-系统通知 2-订单提醒
async function fetchNoticeUnreadCounts() {
  const receiverId = getReceiverId();
  if (!receiverId) {
    noticeCategories.value.forEach(c => (c.unread = 0));
    return;
  }
  const receiverIdParam = "store_" + receiverId;
  try {
    const [res1, res2, res0] = await Promise.all([
      getCountUnreadByType({ noticeType: 1, receiverId: receiverIdParam }),
      getCountUnreadByType({ noticeType: 2, receiverId: receiverIdParam }),
      getCountUnreadByType({ noticeType: 0, receiverId: receiverIdParam })
    ]);
    const systemCat = noticeCategories.value.find(c => c.key === "system");
    const orderCat = noticeCategories.value.find(c => c.key === "order");
    const relatedCat = noticeCategories.value.find(c => c.key === "related");
    if (systemCat) systemCat.unread = Number((res1 as any)?.data ?? (res1 as any) ?? 0);
    if (orderCat) orderCat.unread = Number((res2 as any)?.data ?? (res2 as any) ?? 0);
    if (relatedCat) relatedCat.unread = Number((res0 as any)?.data ?? (res0 as any) ?? 0);
  } catch (e) {
    noticeCategories.value.forEach(c => (c.unread = 0));
  }
}

// 进入通知页面时：用 countUnreadByType 刷新三个标签未读数，并拉取当前分类列表
function refreshAllNoticeCategories() {
  fetchNoticeUnreadCounts();
  fetchNoticeList(activeCategory.value);
}

function handleSizeChange(size: number) {
  const key = activeCategory.value;
  paginationByCategory.value[key].pageSize = size;
  paginationByCategory.value[key].pageNum = 1;
  fetchNoticeList(key);
}

function handlePageChange(page: number) {
  const key = activeCategory.value;
  paginationByCategory.value[key].pageNum = page;
  fetchNoticeList(key);
}

async function handleViewDetail(item: NoticeItem) {
  if (item.unread) {
    try {
      const res: any = await readNoticeById({ id: item.id });
      const ok = res?.code === 200 || res?.code === "200";
      if (ok) {
        const key = activeCategory.value;
        const list = listByCategory.value[key] ?? [];
        const idx = list.findIndex(i => i.id === item.id);
        if (idx !== -1) list[idx].unread = false;
        const cat = noticeCategories.value.find(c => c.key === key);
        if (cat && cat.unread > 0) cat.unread -= 1;
      }
    } catch (e) {
      // 仍打开详情
    }
  }

  // 意见反馈回复通知：跳转反馈详情页
  if (item.title === "意见反馈回复通知" && item.feedbackId != null) {
    emit("close");
    router.push({ path: "/feedback/detail", query: { id: String(item.feedbackId) } });
    return;
  }

  currentDetail.value = item;
  detailVisible.value = true;
}

// 互动列表：点击头像跳转动态主页（与 dynamicManagement/index 的 handleViewUserProfile 一致）
function handleAvatarClick(item: NoticeItem) {
  console.log(item, "item");
  const phoneId = item.phoneId ?? item.userId;
  if (!phoneId) return;
  emit("close");
  router.push({
    path: "/dynamicManagement/userDynamic",
    query: {
      userId: String(item.storeUserId ?? item.userId ?? ""),
      phoneId: String(phoneId),
      userName: item.userName ?? "",
      userAvatar: item.userImage ?? ""
    }
  });
}

async function handleDelete(item: NoticeItem, index: number) {
  try {
    await ElMessageBox.confirm("确定要删除这条通知吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    await deleteNoticeById({ id: item.id });
    const key = activeCategory.value;
    listByCategory.value[key] = currentList.value.filter((_, i) => i !== index);
    const cat = noticeCategories.value.find(c => c.key === key);
    if (cat && item.unread) cat.unread = Math.max(0, cat.unread - 1);
    paginationByCategory.value[key].total = Math.max(0, paginationByCategory.value[key].total - 1);
    ElMessage.success("删除成功");
  } catch (e) {
    if (e !== "cancel" && e !== "close") ElMessage.error("删除失败");
  }
}
/** 刷新全部（供 WebSocket 消息到达时实时更新，与商家端一致） */
function refresh() {
  if (activeTab.value === "notice") {
    fetchNoticeUnreadCounts();
    fetchNoticeList(activeCategory.value);
  } else {
    fetchUnfollowedUnreadCount();
    fetchNoFriendMessage();
    fetchMessageList();
  }
}

defineExpose({ refresh });

onMounted(() => {
  refreshAllNoticeCategories();
});

watch(activeCategory, val => {
  const list = listByCategory.value[val] ?? [];
  const loading = loadingByCategory.value[val];
  if (list.length === 0 && !loading) {
    paginationByCategory.value[val].pageNum = 1;
    fetchNoticeList(val);
  }
});

watch(activeTab, val => {
  if (val === "notice") {
    refreshAllNoticeCategories();
  } else if (val === "message") {
    messageCategory.value = "unfollowed";
    fetchNoFriendMessage();
    fetchMessageList();
  }
});
</script>

<style scoped lang="scss">
.notification-drawer-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 480px;
}
.drawer-tabs {
  display: flex;
  gap: 32px;
  padding: 18px 0 14px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  .tab-item {
    padding-bottom: 6px;
    font-size: 16px;
    color: var(--el-text-color-secondary);
    cursor: pointer;
    &.active {
      font-weight: 600;
      color: var(--el-color-primary);
      border-bottom: 2px solid var(--el-color-primary);
    }
  }
}
.drawer-body {
  display: flex;
  flex: 1;
  gap: 20px;
  min-height: 0;
  margin-top: 16px;
}
.drawer-side {
  display: flex;
  flex-shrink: 0;
  flex-direction: column;
  gap: 6px;
  width: 170px;
  padding: 12px 0;
  background: var(--el-fill-color-lighter);
  border-radius: 8px;
  .side-item {
    display: flex;
    gap: 10px;
    align-items: center;
    padding: 12px 14px;
    margin: 0 8px;
    font-size: 14px;
    color: var(--el-text-color-regular);
    cursor: pointer;
    border-radius: 6px;
    &.active {
      font-weight: 500;
      color: var(--el-color-primary);
      background: var(--el-color-primary-light-9);
    }
  }
  .side-icon {
    font-size: 18px;
  }
  .side-text {
    flex: 1;
  }
  .side-badge {
    :deep(.el-badge__content) {
      border: none;
    }
  }
}
.drawer-main-wrap {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-width: 0;
}
.drawer-main {
  flex: 1;
  min-width: 0;
  padding-right: 4px;
  overflow-y: auto;
}
.pagination-wrap {
  display: flex;
  flex-shrink: 0;
  justify-content: flex-end;
  padding: 12px 0 0;
  margin-top: 8px;
  border-top: 1px solid var(--el-border-color-lighter);
}
.message-card {
  display: flex;
  gap: 14px;
  padding: 14px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  &:last-child {
    border-bottom: none;
  }
  &.message-card-clickable {
    cursor: pointer;
  }
  .message-avatar {
    position: relative;
    flex-shrink: 0;
    &.avatar-clickable {
      cursor: pointer;
    }
    .message-unread-dot {
      position: absolute;
      top: 0;
      right: 0;
      width: 8px;
      height: 8px;
      background: var(--el-color-danger);
      border-radius: 50%;
    }
  }
  .message-body {
    flex: 1;
    min-width: 0;
    cursor: pointer;
  }
  .message-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 6px;
  }
  .message-sender {
    display: flex;
    gap: 6px;
    align-items: center;
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-primary);
    .unread-dot {
      flex-shrink: 0;
      width: 6px;
      height: 6px;
      background: var(--el-color-danger);
      border-radius: 50%;
    }
  }
  .message-date {
    flex-shrink: 0;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
  .message-content-row {
    display: flex;
    gap: 10px;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
  }
  .message-content {
    flex: 1;
    min-width: 0;
    overflow: hidden;
    font-size: 14px;
    line-height: 1.5;
    color: var(--el-text-color-regular);
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .message-status {
    position: relative;
    display: flex;
    flex-shrink: 0;
    align-items: center;
  }
  .message-count {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 20px;
    height: 20px;
    padding: 0 6px;
    font-size: 12px;
    font-weight: 500;
    color: #ffffff;
    background: #ff2442;
    border-radius: 10px;
  }
  .message-dot {
    width: 8px;
    height: 8px;
    background: var(--el-color-danger);
    border-radius: 50%;
  }
  .message-actions {
    display: flex;
    justify-content: flex-end;
  }
}
.notice-card {
  padding: 18px 20px;
  margin-bottom: 12px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  transition: all 0.2s;
  &:last-child {
    margin-bottom: 0;
  }
  .card-row {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .card-title {
    display: flex;
    gap: 8px;
    align-items: center;
    font-size: 15px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    .unread-dot {
      flex-shrink: 0;
      width: 8px;
      height: 8px;
      background: var(--el-color-danger);
      border-radius: 50%;
    }
  }
  .card-date {
    flex-shrink: 0;
    font-size: 13px;
    color: var(--el-text-color-secondary);
  }
  .card-content {
    margin-bottom: 12px;
    font-size: 14px;
    line-height: 1.6;
    color: var(--el-text-color-regular);
  }
  .card-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
  }
}
.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  font-size: 15px;
  color: var(--el-text-color-secondary);
  text-align: center;
}
.detail-dialog-content {
  padding: 10px 0;
  font-size: 14px;
  line-height: 1.8;
  color: var(--el-text-color-regular);
}
</style>
