<template>
  <div class="notice-page">
    <!-- 头部 -->
    <div class="header">
      <el-button class="back-btn" @click="handleBack"> 返回 </el-button>
      <el-button class="mark-all-read-btn" v-if="noticeList.length != 0" @click="handleMarkAllRead">
        <el-icon><CircleCheck /></el-icon>
        一键已读
      </el-button>
    </div>

    <!-- 通知列表 -->
    <div class="notice-list">
      <!-- 空状态 -->
      <div v-if="total === 0" class="empty-state">
        <img src="@/assets/images/notData.png" alt="暂无数据" class="empty-image" />
        <p class="empty-text">暂无数据</p>
      </div>
      <!-- 通知卡片列表 -->
      <div v-for="(item, index) in noticeList" :key="index" class="notice-card" :class="{ unread: !item.isRead }">
        <div class="card-header">
          <h3 class="card-title">
            {{ item.title }}
          </h3>
          <div class="card-time-wrapper">
            <span class="card-time">{{ item.createdTime }}</span>
            <span v-if="!item.isRead" class="unread-dot" />
          </div>
        </div>
        <div class="card-content">
          <div>{{ parseContext(item.context) }}</div>
          <el-button class="view-detail-btn" @click="handleViewDetail(item)"> 查看详情 </el-button>
        </div>
      </div>
    </div>

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

    <!-- 详情对话框 -->
    <el-dialog v-model="dialogVisible" :title="currentNotice?.title" width="500px" :close-on-click-modal="false">
      <div class="dialog-content">
        {{ parseContext(currentNotice?.context || currentNotice?.content) }}
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { CircleCheck } from "@element-plus/icons-vue";
import { getNoticeList, markAllNoticesAsRead, markNoticeAsRead } from "@/api/modules/homeEntry";
import { useRouter } from "vue-router";
const router = useRouter();
import mittBus from "@/utils/mittBus";
import { localGet } from "@/utils/index";
import { get } from "lodash";

interface NoticeItem {
  id: number;
  title: string;
  time?: string;
  createdTime?: string;
  content: string;
  context?: string;
  isRead: boolean;
}

onMounted(() => {});
// 返回按钮
const handleBack = () => {
  router.back();
};

const noticeList = ref<NoticeItem[]>([]);
const total = ref<number>(0);
const pageNum = ref<number>(1);
const pageSize = ref<number>(10);

// 获取用户手机号
const getReceiverId = () => {
  return localGet("iphone") || localGet("geeker-user")?.userInfo?.phone || "";
};

const getList = async () => {
  let res: any = await getNoticeList({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    receiverId: "store_" + getReceiverId(),
    noticeType: 1
  });
  if (res.code == 200) {
    noticeList.value = res.data?.records || res.data?.list || [];
    total.value = res.data?.total || 0;
  }
};
getList();
// 每页条数改变
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  pageNum.value = 1; // 重置到第一页
  getList();
};

// 当前页改变
const handleCurrentChange = (current: number) => {
  pageNum.value = current;
  getList();
};

const dialogVisible = ref(false);
const currentNotice = ref<NoticeItem | null>(null);

// 一键已读
const handleMarkAllRead = async () => {
  let res: any = await markAllNoticesAsRead({ receiverId: "store_" + getReceiverId(), noticeType: 1 });
  if (res.code == 200) {
    ElMessage.success("操作成功");
    // 重置到第一页并刷新列表
    pageNum.value = 1;
    getList();
    // 通知 Message 组件更新未读数量
    mittBus.emit("updateUnreadCount");
  } else {
    ElMessage.error(res.message);
  }
};

// 解析 context JSON 字符串，提取 message 字段
const parseContext = (context: string | undefined): string => {
  if (!context) return "";
  try {
    // 如果 context 是 JSON 字符串，先解析
    const parsed = typeof context === "string" ? JSON.parse(context) : context;
    // 提取 message 字段
    return parsed?.message || context;
  } catch (error) {
    // 如果不是有效的 JSON，直接返回原字符串
    return context;
  }
};

// 查看详情
const handleViewDetail = async (item: NoticeItem) => {
  // 如果未读，调用接口标记为已读
  if (!item.isRead) {
    try {
      const res: any = await markNoticeAsRead({
        id: item.id
      });
      if (res.code == 200) {
        // 标记为已读
        item.isRead = true;
        // 通知 Message 组件更新未读数量
        mittBus.emit("updateUnreadCount");
      } else {
        ElMessage.error(res.message || "标记已读失败");
      }
    } catch (error) {
      console.error("标记已读失败:", error);
      ElMessage.error("标记已读失败，请重试");
    }
  }
  // 显示详情对话框
  currentNotice.value = item;
  dialogVisible.value = true;
};
</script>

<style scoped lang="scss">
.notice-page {
  min-height: calc(100vh - 100px);
  padding: 20px;
  background: #ffffff;
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    .title {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
    }
    .mark-all-read-btn {
      color: #606266;
      background: #ffffff;
      border-color: #dcdfe6;
      .el-icon {
        margin-right: 4px;
      }
    }
  }
  .notice-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
    margin-bottom: 20px;
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 80px 20px;
      .empty-image {
        width: 360px;
        height: 360px;
        margin-bottom: 20px;
      }
      .empty-text {
        margin: 0;
        font-size: 16px;
        color: #909399;
      }
    }
    .notice-card {
      padding: 20px;
      background: #ffffff;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      transition: all 0.3s;

      // &.unread {
      //   border-color: #409eff;
      // }
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12px;
        .card-title {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
        .card-time-wrapper {
          display: flex;
          gap: 8px;
          align-items: center;
          .card-time {
            font-size: 14px;
            color: #909399;
          }
          .unread-dot {
            display: inline-block;
            width: 8px;
            height: 8px;
            background: #f56c6c;
            border-radius: 50%;
          }
        }
      }
      .card-content {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        line-height: 1.6;
        color: #606266;
      }
      .card-footer {
        display: flex;
        justify-content: flex-end;
        .view-detail-btn {
          padding: 8px 16px;
          font-size: 14px;
          color: #606266;
          background: #ffffff;
          border-color: #dcdfe6;
        }
      }
    }
  }
  .pagination-section {
    display: flex;
    justify-content: flex-end;
    padding-top: 20px;
    margin-top: 20px;
    border-top: 1px solid #e4e7ed;
  }
}
.dialog-content {
  padding: 10px 0;
  font-size: 14px;
  line-height: 1.8;
  color: #303133;
}
</style>
