<template>
  <view class="page">
    <view class="nav-bar">
      <view class="nav-btn" @click="goBack">
        <text class="nav-icon">←</text>
      </view>
      <text class="nav-title">消息通知</text>
      <view class="nav-btn" @click="markAllRead">
        <text class="read-all">全部已读</text>
      </view>
    </view>

    <scroll-view scroll-y class="content" :scroll-top="scrollTop">
      <view v-if="notifications.length === 0 && !loading" class="empty">
        <text class="empty-icon">🔔</text>
        <text class="empty-text">暂无通知</text>
      </view>

      <view v-else class="notification-list">
        <view
          v-for="item in notifications"
          :key="item.id"
          class="notification-item"
          :class="{ unread: !item.isRead }"
          @click="markAsRead(item)"
        >
          <view class="notification-icon" :class="getIconClass(item.type)">
            <text>{{ getIcon(item.type) }}</text>
          </view>
          <view class="notification-content">
            <text class="notification-title">{{ item.title }}</text>
            <text class="notification-desc">{{ item.content }}</text>
            <text class="notification-time">{{ formatTime(item.createdAt) }}</text>
          </view>
          <view v-if="!item.isRead" class="unread-dot"></view>
        </view>
      </view>

      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { get, put } from '../../utils/request';

// scroll-top 用于避免 scrollTop 错误
const scrollTop = ref(0);

const notifications = ref<any[]>([]);
const loading = ref(false);

function goBack() {
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({ url: '/pages/index/index' });
  }
}

function getIcon(type: string): string {
  const icons: Record<string, string> = {
    audio_completed: '🎵',
    book_completed: '📖',
    video_completed: '🎬',
    member_expiring: '⚠️',
    member_expired: '❌',
    daily_reminder: '📅',
  };
  return icons[type] || '🔔';
}

function getIconClass(type: string): string {
  if (type.includes('completed')) return 'success';
  if (type.includes('expiring')) return 'warning';
  if (type.includes('expired')) return 'error';
  return 'info';
}

function formatTime(dateStr: string): string {
  const date = new Date(dateStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;

  return `${date.getMonth() + 1}/${date.getDate()}`;
}

async function fetchNotifications() {
  loading.value = true;
  try {
    const data = await get('/notifications');
    notifications.value = data || [];
  } catch (error) {
    console.error('获取通知失败:', error);
  } finally {
    loading.value = false;
  }
}

async function markAsRead(item: any) {
  if (item.isRead) return;

  try {
    await put(`/notifications/${item.id}/read`);
    item.isRead = true;
  } catch (error) {
    console.error('标记已读失败:', error);
  }
}

async function markAllRead() {
  const unreadCount = notifications.value.filter((n) => !n.isRead).length;
  if (unreadCount === 0) {
    uni.showToast({ title: '没有未读消息', icon: 'none' });
    return;
  }

  try {
    await put('/notifications/read-all');
    notifications.value.forEach((n) => (n.isRead = true));
    uni.showToast({ title: '已全部标为已读', icon: 'success' });
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
}

onMounted(() => {
  fetchNotifications();
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f5f5;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 44rpx 32rpx 24rpx;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-icon {
  font-size: 40rpx;
  color: #ffffff;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
}

.read-all {
  font-size: 26rpx;
  color: #ffffff;
}

.content {
  padding: 24rpx;
  height: calc(100vh - 160rpx);
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #6b7280;
}

.notification-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.notification-item {
  display: flex;
  gap: 16rpx;
  padding: 24rpx;
  background: #ffffff;
  border-radius: 16rpx;
  position: relative;
}

.notification-item.unread {
  background: #f0f9ff;
}

.notification-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;
  flex-shrink: 0;
}

.notification-icon.success {
  background: #dcfce7;
}

.notification-icon.warning {
  background: #fef3c7;
}

.notification-icon.error {
  background: #fee2e2;
}

.notification-icon.info {
  background: #e0f2fe;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #1f2937;
  display: block;
  margin-bottom: 8rpx;
}

.notification-desc {
  font-size: 24rpx;
  color: #6b7280;
  line-height: 1.5;
  display: block;
  margin-bottom: 8rpx;
}

.notification-time {
  font-size: 22rpx;
  color: #9ca3af;
  display: block;
}

.unread-dot {
  position: absolute;
  top: 32rpx;
  right: 24rpx;
  width: 16rpx;
  height: 16rpx;
  background: #ef4444;
  border-radius: 50%;
}

.loading {
  text-align: center;
  padding: 32rpx;
}

.loading text {
  font-size: 24rpx;
  color: #9ca3af;
}
</style>
