<template>
  <a-card title="我的消息">
    <a-tabs v-model:activeKey="activeKey">
      <!-- 使用customRender来渲染带徽章的标签 -->
      <a-tab-pane key="all">
        <template #tab>
          <span class="tab-label">
            全部
            <a-badge 
              v-if="allUnreadCount > 0" 
              :count="allUnreadCount" 
              class="tab-badge"
              :offset="[5, -2]"
            />
          </span>
        </template>
      </a-tab-pane>
      
      <a-tab-pane key="money">
        <template #tab>
          <span class="tab-label">
            资金消息
            <a-badge 
              v-if="moneyUnreadCount > 0" 
              :count="moneyUnreadCount" 
              class="tab-badge"
              :offset="[5, -2]"
            />
          </span>
        </template>
      </a-tab-pane>
      
      <a-tab-pane key="secure">
        <template #tab>
          <span class="tab-label">
            安全消息
            <a-badge 
              v-if="secureUnreadCount > 0" 
              :count="secureUnreadCount" 
              class="tab-badge"
              :offset="[5, -2]"
            />
          </span>
        </template>
      </a-tab-pane>
      
      <a-tab-pane key="active">
        <template #tab>
          <span class="tab-label">
            活动消息
            <a-badge 
              v-if="activeUnreadCount > 0" 
              :count="activeUnreadCount" 
              class="tab-badge"
              :offset="[5, -2]"
            />
          </span>
        </template>
      </a-tab-pane>
    </a-tabs>
    
    <a-table 
      :columns="columns"
      :data-source="billData" 
      :pagination="pagination" 
      @change="handleTableChange"
      :loading="loading" 
      class="bill-table" 
      :scroll="{ x: 1200 }"
      bordered>
      
      <!-- 消息类型列自定义渲染 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'messageType'">
          <span :class="{ 'unread-title': !record.is_read }">
            {{ getMessageTypeText(record.messageType) }}
          </span>
        </template>
        
        <template v-else-if="column.dataIndex === 'title'">
          <span :class="{ 'unread-title': !record.is_read, 'read-title': record.is_read }">
            {{ record.title }}
          </span>
        </template>
        
        <template v-else-if="column.dataIndex === 'is_read'">
          <a-tag :class="record.is_read ? 'status-read' : 'status-unread'">
            {{ record.is_read ? '已读' : '未读' }}
          </a-tag>
        </template>
      </template>
      
    </a-table>
  </a-card>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, watch, computed } from 'vue';
import { getMessageList } from '@/apis/home';

// 当前激活的 Tab
const activeKey = ref('all');

// 加载状态
const loading = ref(false);

// 表格数据
const billData = ref<any[]>([]);

// 所有消息数据（用于统计未读数量）
const allMessages = ref<any[]>([]);

// 当前筛选的消息类型（传给后端）
const messageType = ref<string>('');

// Tab key 映射到后端 messageType 值
const keyToMessageType: Record<string, string> = {
  all: '',
  money: 'FinancialMessage',
  secure: 'SecurityMessage',
  active: 'ActivityMessage'
};

// 消息类型映射（前端显示用）
const messageTypeMap: Record<string, string> = {
  FinancialMessage: '资金消息',
  SecurityMessage: '安全消息',
  ActivityMessage: '活动消息',
  // 如果还有其他可能的消息类型，可以在这里添加
};

// 获取消息类型的中文文本
const getMessageTypeText = (type: string) => {
  return messageTypeMap[type] || type || '未知类型';
};

// 计算各个标签页的未读数量
const allUnreadCount = computed(() => {
  return allMessages.value.filter(msg => !msg.is_read).length;
});

const moneyUnreadCount = computed(() => {
  return allMessages.value.filter(msg => 
    msg.messageType === 'FinancialMessage' && !msg.is_read
  ).length;
});

const secureUnreadCount = computed(() => {
  return allMessages.value.filter(msg => 
    msg.messageType === 'SecurityMessage' && !msg.is_read
  ).length;
});

const activeUnreadCount = computed(() => {
  return allMessages.value.filter(msg => 
    msg.messageType === 'ActivityMessage' && !msg.is_read
  ).length;
});

// 表格列定义
const columns = [
  {
    title: '消息类型',
    dataIndex: 'messageType',
    key: 'messageType',
    width: 200
  },
  {
    title: '消息标题',
    dataIndex: 'title',
    key: 'title',
    width: 400
  },
  {
    title: '发送时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'is_read',
    key: 'is_read',
    width: 100
  }
];

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
});

// 表格分页/排序/筛选变化（目前只处理分页）
const handleTableChange = (page: any) => {
  pagination.value.current = page.current;
  pagination.value.pageSize = page.pageSize;
  getDataList();
};

// 获取所有消息（用于统计未读数量）
const getAllMessages = async () => {
  try {
    const params = {
      page_num: 1,
      page_size: 1000, // 获取足够多的数据来统计
      Message: '' // 获取全部消息
    };

    const response: any = await getMessageList(params);
    
    if (response.data && Array.isArray(response.data)) {
      allMessages.value = response.data;
    } else if (response.data?.messages) {
      allMessages.value = response.data.messages;
    } else if (response.data?.list) {
      allMessages.value = response.data.list;
    } else {
      allMessages.value = [];
    }
    
    console.log('全部消息统计:', {
      total: allMessages.value.length,
      allUnread: allUnreadCount.value,
      moneyUnread: moneyUnreadCount.value,
      secureUnread: secureUnreadCount.value,
      activeUnread: activeUnreadCount.value
    });
  } catch (error) {
    console.error('获取全部消息失败:', error);
    allMessages.value = [];
  }
};

// 获取消息列表（当前标签页）
const getDataList = async () => {
  loading.value = true;
  try {
    const params = {
      page_num: pagination.value.current,
      page_size: pagination.value.pageSize,
      Message: messageType.value
    };

    const response: any = await getMessageList(params);

    // 解析响应数据
    if (response.data && Array.isArray(response.data)) {
      billData.value = response.data;
      pagination.value.total = response.total || response.data.length;
    } else if (response.data?.messages) {
      billData.value = response.data.messages;
      pagination.value.total = response.data.total || 0;
    } else if (response.data?.list) {
      billData.value = response.data.list;
      pagination.value.total = response.data.total || 0;
    } else {
      billData.value = [];
      pagination.value.total = 0;
    }
    
    console.log('当前标签页消息:', {
      type: messageType.value,
      count: billData.value.length,
      data: billData.value
    });
    
  } catch (error) {
    console.error('获取消息列表失败:', error);
    billData.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 监听 Tab 切换
watch(activeKey, (newKey) => {
  messageType.value = keyToMessageType[newKey] || '';
  pagination.value.current = 1; // 切换标签页时回到第一页
  getDataList();
});

// 初始加载
onBeforeMount(() => {
  // 先获取所有消息用于统计
  getAllMessages();
  // 再获取当前标签页的消息
  getDataList();
});

// 可选：添加轮询更新未读数量
// 如果希望实时更新未读数量，可以添加轮询
// setInterval(() => {
//   getAllMessages();
// }, 30000); // 每30秒更新一次未读数量
</script>

<style scoped>
.bill-table {
  margin-top: 16px;
}

/* Tab标签样式 */
.tab-label {
  position: relative;
  display: inline-block;
  padding-right: 10px;
}

.tab-badge {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(50%, -50%);
}

/* 已读/未读标签样式 */
:deep(.status-read) {
  background-color: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
  font-weight: normal;
}

:deep(.status-unread) {
  background-color: #fff1f0;
  border-color: #ffa39e;
  color: #f5222d;
  font-weight: bold;
}

/* 消息标题样式 */
:deep(.unread-title) {
  font-weight: bold;
  color: #000000;
}

:deep(.read-title) {
  font-weight: normal;
  color: #666666;
}

/* 徽章样式优化 */
:deep(.ant-badge-count) {
  min-width: 18px;
  height: 18px;
  line-height: 18px;
  font-size: 11px;
  padding: 0 5px;
  box-shadow: 0 0 0 1px #fff;
}

/* 当前激活的Tab样式 */
:deep(.ant-tabs-tab-active .tab-label) {
  color: #1890ff;
}

:deep(.ant-tabs-tab:hover .tab-label) {
  color: #40a9ff;
}
</style>