<template>
  <view class="container pb-tabbar">
    <!-- 筛选工具栏 -->
    <view class="filter-toolbar">
      <view class="filter-tabs">
        <view 
          v-for="tab in filterTabs" 
          :key="tab.key" 
          :class="['tab-item', activeTab === tab.key ? 'active' : '']"
          @click="onTabChange(tab.key)"
        >
          <text class="tab-text">{{ tab.name }}</text>
          <text v-if="getCount(tab.key) > 0" class="count">({{ getCount(tab.key) }})</text>
        </view>
      </view>
      <view v-if="messageStore.unreadCount > 0" class="read-all" @click="markAllAsRead">
        <text>全部已读</text>
      </view>
    </view>

    <!-- 消息列表 -->
    <view class="msg-list">
      <view 
        v-for="(msg, index) in filteredMessages" 
        :key="index" 
        class="msg-card card-anim"
        @click="goToDetail(msg)"
      >
        <view class="msg-header">
          <text class="msg-title">{{ msg.title }}</text>
          <view v-if="msg.unread" class="unread-dot"></view>
          <text v-else class="time-text">{{ msg.time }}</text>
        </view>
        <view class="msg-body">
          <view class="info-row">
            <text class="label">岗位：</text>
            <text class="value">{{ msg.position }}</text>
          </view>
          <view class="info-row flex-between">
            <view class="left-box">
              <text class="label">公司：</text>
              <text class="value">{{ msg.company }}</text>
            </view>
            <view class="right-box">
              <text v-if="msg.unread" class="time-text-inline">{{ msg.time }}</text>
              <image src="/static/icons/chevron-right.svg" class="chevron"></image>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-if="filteredMessages.length === 0" class="empty-box">
        <text class="empty-text">暂无相关消息</text>
      </view>
    </view>
    
    <view class="no-more">—— 已到底啦~ ——</view>
    <view class="tabbar-placeholder"></view>

    <!-- Custom Tabbar -->
    <custom-tabbar :activeIndex="2"></custom-tabbar>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import CustomTabbar from '../../components/custom-tabbar/custom-tabbar.vue';
import { messageStore } from '../../store/message.js';
import { getMessageList, readAllMessages, readMessage } from '../../api/message.js';

const activeTab = ref('all');
const filterTabs = [
  { name: '全部', key: 'all' },
  { name: '未读', key: 'unread' },
  { name: '已读', key: 'read' }
];

const messages = ref([]);
const loading = ref(false);

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true;
  try {
    // 始终获取全部消息，由前端过滤，保证 Tab 上的计数稳定
    const res = await getMessageList();
    if (res.code === 200) {
      // 兼容多种返回结构：res.data (数组), res.rows (分页), res.data.list (某些自定义结构)
      let list = [];
      if (Array.isArray(res.data)) {
        list = res.data;
      } else if (res.rows) {
        list = res.rows;
      } else if (res.data && res.data.list) {
        list = res.data.list;
      }
      
      messages.value = list.map(item => ({
        id: item.id,
        title: item.title || '系统通知',
        position: item.positionName || '系统消息',
        company: item.companyName || '审计之家',
        status: item.status,
        desc: item.content,
        time: item.createTime ? item.createTime.substring(5, 16) : '',
        unread: item.isRead === 0
      }));
      updateGlobalUnread();
    }
  } catch (e) {
    console.error('获取消息列表失败', e);
  } finally {
    loading.value = false;
  }
};

// 监听并更新全局未读数
const updateGlobalUnread = () => {
  const count = messages.value.filter(m => m.unread).length;
  messageStore.setUnreadCount(count);
};

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

onShow(() => {
  fetchMessages();
});

onPullDownRefresh(async () => {
  await fetchMessages();
  uni.stopPullDownRefresh();
});

// 监听标签切换
const onTabChange = (key) => {
  activeTab.value = key;
  // 不再重新请求后端，直接切换本地过滤
};

const getCount = (key) => {
  if (key === 'unread') return messageStore.unreadCount;
  // 全部和已读的计数暂时不显示或显示列表长度，主要关注未读数
  if (key === 'all') return messages.value.length;
  if (key === 'read') return messages.value.filter(m => !m.unread).length;
  return 0;
};

const filteredMessages = computed(() => {
  if (activeTab.value === 'unread') return messages.value.filter(m => m.unread);
  if (activeTab.value === 'read') return messages.value.filter(m => !m.unread);
  return messages.value;
});

const markAllAsRead = async () => {
  try {
    const res = await readAllMessages();
    if (res.code === 200) {
      messages.value.forEach(m => m.unread = false);
      updateGlobalUnread();
      uni.showToast({ title: '已全部设为已读', icon: 'none' });
    }
  } catch (e) {
    console.error('标记已读失败', e);
  }
};

const goToDetail = async (msg) => {
  if (msg.unread) {
    try {
      await readMessage(msg.id);
      msg.unread = false;
      // 成功进入详情并标记已读后，全局未读数减1
      messageStore.setUnreadCount(Math.max(0, messageStore.unreadCount - 1));
    } catch (e) {
      console.error('标记单条已读失败', e);
    }
  }
  uni.navigateTo({
    url: `/pages/message/msgdetail?data=${encodeURIComponent(JSON.stringify(msg))}`
  });
};
</script>

<style lang="scss" scoped>
/* 样式保持不变... */
.container {
  min-height: 100vh;
  background-color: #F8F9FB;
}

.filter-toolbar {
  position: sticky;
  top: 0;
  z-index: 100;
  background-color: #F8F9FB;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .filter-tabs {
    display: flex;
    gap: 30rpx;
    
    .tab-item {
      display: flex;
      align-items: center;
      position: relative;
      padding: 10rpx 0;
      
      .tab-text {
        font-size: 28rpx;
        color: #666666;
      }
      
      .count {
        font-size: 22rpx;
        color: #999999;
        margin-left: 4rpx;
      }
      
      &.active {
        .tab-text {
          color: #1F6CFF;
          font-weight: bold;
        }
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 20rpx;
          height: 4rpx;
          background-color: #1F6CFF;
          border-radius: 2rpx;
        }
      }
    }
  }
  
  .read-all {
    font-size: 26rpx;
    color: #1F6CFF;
    &:active { opacity: 0.7; }
  }
}

.msg-list {
  padding: 0 30rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.msg-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.02);
  
  .msg-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    
    .msg-title {
      font-size: 34rpx;
      font-weight: bold;
      color: #1A1A1A;
    }
    
    .unread-dot {
      width: 14rpx;
      height: 14rpx;
      background-color: #FF4D4F;
      border-radius: 50%;
    }
    
    .time-text {
      font-size: 24rpx;
      color: #CCCCCC;
    }
  }
  
  .msg-body {
    .info-row {
      display: flex;
      align-items: center;
      margin-bottom: 8rpx;
      &:last-child { margin-bottom: 0; }
      
      .label {
        font-size: 28rpx;
        color: #999999;
      }
      
      .value {
        font-size: 28rpx;
        color: #666666;
      }
    }
    
    .flex-between {
      justify-content: space-between;
      .left-box { display: flex; align-items: center; }
      .right-box {
        display: flex;
        align-items: center;
        .time-text-inline {
          font-size: 24rpx;
          color: #CCCCCC;
          margin-right: 12rpx;
        }
      }
      .chevron {
        width: 32rpx;
        height: 32rpx;
        opacity: 0.2;
      }
    }
  }
}

.empty-box {
  padding: 100rpx 0;
  display: flex;
  flex-direction: center;
  justify-content: center;
  .empty-text {
    font-size: 28rpx;
    color: #999999;
  }
}

.no-more {
  text-align: center;
  font-size: 24rpx;
  color: #CCCCCC;
  padding: 60rpx 0;
}

.tabbar-placeholder {
  height: 120rpx;
  padding-bottom: env(safe-area-inset-bottom);
}

.card-anim {
  animation: slideUp 0.5s ease-out backwards;
  @for $i from 1 through 10 {
    &:nth-child(#{$i}) { animation-delay: #{$i * 0.05s}; }
  }
}

@keyframes slideUp {
  from { transform: translateY(20rpx); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}
</style>
