This commit is contained in:
SunCheng
2026-02-09 19:25:51 +08:00
parent 63aaaf39c5
commit 3e18283e52
38 changed files with 6188 additions and 5342 deletions

View File

@@ -55,6 +55,12 @@
ref="messageViewRef"
:is-component="true"
/>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeNavTab"
@tab-click="handleNavTabClick"
/>
</div>
</template>
@@ -64,8 +70,17 @@ import { useRoute } from 'vue-router'
import TransactionsRecord from './TransactionsRecord.vue'
import EmailRecord from './EmailRecord.vue'
import MessageView from './MessageView.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
const route = useRoute()
// 底部导航栏
const activeNavTab = ref('balance')
const handleNavTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
const tabActive = ref(route.query.tab || 'balance')
// 监听路由参数变化,用于从 tabbar 点击时切换 tab

View File

@@ -497,6 +497,12 @@
@cancel="showDatePicker = false"
/>
</van-popup>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="navActiveTab"
@tab-click="handleNavTabClick"
/>
</div>
</template>
@@ -518,6 +524,14 @@ import BudgetEditPopup from '@/components/Budget/BudgetEditPopup.vue'
import SavingsConfigPopup from '@/components/Budget/SavingsConfigPopup.vue'
import BudgetChartAnalysis from '@/components/Budget/BudgetChartAnalysis.vue'
import PopupContainer from '@/components/PopupContainer.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
// 底部导航栏
const navActiveTab = ref('budget')
const handleNavTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
const activeTab = ref(BudgetCategory.Expense)
const selectedDate = ref(new Date())

View File

@@ -44,6 +44,12 @@
:transaction="currentTransaction"
@save="onDetailSave"
/>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
</div>
</template>
@@ -56,6 +62,14 @@ import TransactionList from '@/components/TransactionList.vue'
import TransactionDetail from '@/components/TransactionDetail.vue'
import SmartClassifyButton from '@/components/SmartClassifyButton.vue'
import PopupContainer from '@/components/PopupContainer.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
// 底部导航栏
const activeTab = ref('calendar')
const handleTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
const dailyStatistics = ref({})
const listVisible = ref(false)

View File

@@ -139,6 +139,12 @@
<!-- 底部安全距离 -->
<div style="height: calc(80px + env(safe-area-inset-bottom, 0px))" />
</div>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
</div>
</template>
@@ -151,10 +157,19 @@ import { useAuthStore } from '@/stores/auth'
import { useVersionStore } from '@/stores/version'
import { getVapidPublicKey, subscribe, testNotification } from '@/api/notification'
import { updateServiceWorker } from '@/registerServiceWorker'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
const router = useRouter()
const authStore = useAuthStore()
const versionStore = useVersionStore()
// 底部导航栏
const activeTab = ref('setting')
const handleTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
const fileInputRef = ref(null)
const currentType = ref('')
const notificationEnabled = ref(false)

View File

@@ -1,34 +1,14 @@
<template>
<div class="page-container-flex calendar-v2-wrapper">
<!-- 头部固定 -->
<header class="calendar-header">
<button
class="month-nav-btn"
aria-label="上一月"
@click="changeMonth(-1)"
>
<van-icon name="arrow-left" />
</button>
<div class="header-content">
<h1 class="header-title">
{{ currentMonth }}
</h1>
</div>
<button
class="month-nav-btn"
aria-label="下一月"
@click="changeMonth(1)"
>
<van-icon name="arrow" />
</button>
<button
class="notif-btn"
aria-label="通知"
@click="onNotificationClick"
>
<van-icon name="bell" />
</button>
</header>
<CalendarHeader
type="month"
:current-date="currentDate"
@prev="changeMonth(-1)"
@next="changeMonth(1)"
@jump="onDateJump"
@notification="onNotificationClick"
/>
<!-- 可滚动内容区域 -->
<div class="calendar-scroll-content">
@@ -73,17 +53,42 @@
@save="handleTransactionSave"
@delete="handleTransactionDelete"
/>
<!-- 日期选择器弹窗 -->
<van-popup
v-model:show="showDatePicker"
position="bottom"
round
>
<van-date-picker
v-model="pickerDate"
title="选择年月"
:min-date="new Date(2020, 0, 1)"
:max-date="new Date()"
:columns-type="['year', 'month']"
@confirm="onDatePickerConfirm"
@cancel="onDatePickerCancel"
/>
</van-popup>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import CalendarHeader from '@/components/DateSelectHeader.vue'
import CalendarModule from './modules/Calendar.vue'
import StatsModule from './modules/Stats.vue'
import TransactionListModule from './modules/TransactionList.vue'
import TransactionDetailSheet from '@/components/Transaction/TransactionDetailSheet.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
import { getTransactionDetail } from '@/api/transactionRecord'
// 定义组件名称keep-alive 需要通过 name 识别)
@@ -94,6 +99,13 @@ defineOptions({
// 路由
const router = useRouter()
// 底部导航栏
const activeTab = ref('calendar')
const handleTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
// 导航逻辑已在组件内部处理
}
// 下拉刷新状态
const refreshing = ref(false)
@@ -105,12 +117,9 @@ const selectedDate = ref(new Date())
const slideDirection = ref('slide-left')
const calendarKey = ref(0)
// 当前月份格式化(中文)
const currentMonth = computed(() => {
const year = currentDate.value.getFullYear()
const month = currentDate.value.getMonth() + 1
return `${year}${month}`
})
// 日期选择器相关
const showDatePicker = ref(false)
const pickerDate = ref(new Date())
// 格式化日期为 key (yyyy-MM-dd)
const formatDateKey = (date) => {
@@ -181,6 +190,38 @@ const onNotificationClick = () => {
router.push('/message')
}
// 点击日期标题,打开日期选择器
const onDateJump = () => {
pickerDate.value = new Date(currentDate.value)
showDatePicker.value = true
}
// 确认日期选择
const onDatePickerConfirm = ({ selectedValues }) => {
const [year, month] = selectedValues
const newDate = new Date(year, month - 1, 1)
// 检查是否超过当前月
const today = new Date()
if (newDate.getFullYear() > today.getFullYear() ||
(newDate.getFullYear() === today.getFullYear() && newDate.getMonth() > today.getMonth())) {
showToast('不能选择未来的月份')
showDatePicker.value = false
return
}
// 更新日期
currentDate.value = newDate
selectedDate.value = newDate
calendarKey.value += 1
showDatePicker.value = false
}
// 取消日期选择
const onDatePickerCancel = () => {
showDatePicker.value = false
}
// 点击 Smart 按钮 - 跳转到智能分类页面
const onSmartClick = () => {
router.push({
@@ -346,68 +387,6 @@ onBeforeUnmount(() => {
background-color: var(--bg-primary);
}
/* ========== 头部 ========== */
.calendar-header {
display: flex;
align-items: center;
justify-content: flex-start;
padding: 8px 24px;
gap: 8px;
background: transparent !important;
position: relative;
z-index: 1;
}
.header-content {
display: flex;
flex-direction: column;
gap: 4px;
}
.header-title {
font-family: var(--font-primary);
font-size: var(--font-2xl);
font-weight: var(--font-medium);
color: var(--text-primary);
margin: 0;
}
.notif-btn {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: var(--radius-full);
background-color: var(--bg-button);
border: none;
cursor: pointer;
transition: opacity 0.2s;
margin-left: auto;
}
.notif-btn:active {
opacity: 0.7;
}
.month-nav-btn {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 18px;
background-color: transparent;
border: none;
color: var(--text-secondary);
cursor: pointer;
transition: all 0.2s;
}
.month-nav-btn:active {
background-color: var(--bg-tertiary);
}
/* 底部安全距离 */
.bottom-spacer {
height: calc(60px + env(safe-area-inset-bottom, 0px));

View File

@@ -14,11 +14,19 @@
</div>
</template>
<template #right>
<van-icon
name="chat-o"
size="20"
@click="goToAnalysis"
/>
<div class="nav-right-buttons">
<van-icon
name="upgrade"
size="18"
style="margin-right: 12px;"
@click="goToStatisticsV2"
/>
<van-icon
name="chat-o"
size="20"
@click="goToAnalysis"
/>
</div>
</template>
</van-nav-bar>
@@ -310,6 +318,12 @@
:transaction="currentTransaction"
@save="onBillSave"
/>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
</div>
</template>
@@ -325,10 +339,18 @@ import TransactionList from '@/components/TransactionList.vue'
import TransactionDetail from '@/components/TransactionDetail.vue'
import SmartClassifyButton from '@/components/SmartClassifyButton.vue'
import PopupContainer from '@/components/PopupContainer.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
import { getCssVar } from '@/utils/theme'
const router = useRouter()
//
const activeTab = ref('statistics')
const handleTabClick = (item, index) => {
console.log('Tab clicked:', item.name, index)
//
}
//
const loading = ref(true)
const firstLoading = ref(true)
@@ -1063,6 +1085,11 @@ const goToAnalysis = () => {
router.push('/bill-analysis')
}
// V2
const goToStatisticsV2 = () => {
router.push('/statistics-v2')
}
//
const goToCategoryBills = (classify, type) => {
selectedClassify.value = classify || '未分类' // TODO
@@ -1338,6 +1365,12 @@ watch(dateSelectionMode, (newMode) => {
color: var(--van-text-color);
}
/* 导航栏右侧按钮组 */
.nav-right-buttons {
display: flex;
align-items: center;
}
/* 余额卡片 */
.balance-amount {
text-align: center;

View File

@@ -0,0 +1,407 @@
<template>
<!-- 支出分类统计 -->
<div
class="common-card"
style="padding-bottom: 10px;"
>
<div class="card-header">
<h3 class="card-title">
支出分类
</h3>
<van-tag
type="primary"
size="medium"
>
{{ expenseCategoriesView.length }}
</van-tag>
</div>
<!-- 环形图区域 -->
<div
v-if="expenseCategoriesView.length > 0"
class="chart-container"
>
<div class="ring-chart">
<div
ref="pieChartRef"
style="width: 100%; height: 100%"
/>
</div>
</div>
<!-- 分类列表 -->
<div class="category-list">
<div
v-for="category in expenseCategoriesSimpView"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 0)"
>
<div class="category-info">
<div
class="category-color"
:style="{ backgroundColor: category.color }"
/>
<div class="category-name-with-count">
<span class="category-name">{{ category.classify || '未分类' }}</span>
<span class="category-count">{{ category.count }}</span>
</div>
</div>
<div class="category-stats">
<div class="category-amount">
¥{{ formatMoney(category.amount) }}
</div>
<div class="category-percent">
{{ category.percent }}%
</div>
</div>
<van-icon
name="arrow"
class="category-arrow"
/>
</div>
<!-- 展开/收起按钮 -->
<div
v-if="expenseCategoriesView.length > 1"
class="expand-toggle"
@click="showAllExpense = !showAllExpense"
>
<van-icon :name="showAllExpense ? 'arrow-up' : 'arrow-down'" />
</div>
</div>
<ModernEmpty
v-if="!expenseCategoriesView || !expenseCategoriesView.length"
type="chart"
theme="blue"
title="暂无支出"
description="本期还没有支出记录"
size="small"
/>
</div>
</template>
<script setup>
import { ref, computed, onBeforeUnmount, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { getCssVar } from '@/utils/theme'
import ModernEmpty from '@/components/ModernEmpty.vue'
const props = defineProps({
categories: {
type: Array,
default: () => []
},
totalExpense: {
type: Number,
default: 0
},
colors: {
type: Array,
default: () => []
}
})
defineEmits(['category-click'])
const pieChartRef = ref(null)
let pieChartInstance = null
const showAllExpense = ref(false)
// 格式化金额
const formatMoney = (value) => {
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 计算属性
const expenseCategoriesView = computed(() => {
const list = [...props.categories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
const expenseCategoriesSimpView = computed(() => {
const list = expenseCategoriesView.value
if (showAllExpense.value) {
return list
}
// 只展示未分类
const unclassified = list.filter((c) => c.classify === '未分类' || !c.classify)
if (unclassified.length > 0) {
return [...unclassified]
}
return []
})
// 渲染饼图
const renderPieChart = () => {
if (!pieChartRef.value) {
return
}
if (expenseCategoriesView.value.length === 0) {
return
}
// 尝试获取DOM上的现有实例
const existingInstance = echarts.getInstanceByDom(pieChartRef.value)
if (pieChartInstance && pieChartInstance !== existingInstance) {
if (!pieChartInstance.isDisposed()) {
pieChartInstance.dispose()
}
pieChartInstance = null
}
if (pieChartInstance && pieChartInstance.getDom() !== pieChartRef.value) {
pieChartInstance.dispose()
pieChartInstance = null
}
if (!pieChartInstance && existingInstance) {
pieChartInstance = existingInstance
}
if (!pieChartInstance) {
pieChartInstance = echarts.init(pieChartRef.value)
}
// 使用 Top N + Other 的数据逻辑,确保图表不会太拥挤
const list = [...expenseCategoriesView.value]
let chartData = []
// 按照金额排序
list.sort((a, b) => b.amount - a.amount)
const MAX_SLICES = 8 // 最大显示扇区数,其余合并为"其他"
if (list.length > MAX_SLICES) {
const topList = list.slice(0, MAX_SLICES - 1)
const otherList = list.slice(MAX_SLICES - 1)
const otherAmount = otherList.reduce((sum, item) => sum + item.amount, 0)
chartData = topList.map((item, index) => ({
value: item.amount,
name: item.classify || '未分类',
itemStyle: { color: props.colors[index % props.colors.length] }
}))
chartData.push({
value: otherAmount,
name: '其他',
itemStyle: { color: getCssVar('--van-gray-6') } // 使用灰色表示其他
})
} else {
chartData = list.map((item, index) => ({
value: item.amount,
name: item.classify || '未分类',
itemStyle: { color: props.colors[index % props.colors.length] }
}))
}
const option = {
title: {
text: '¥' + formatMoney(props.totalExpense),
subtext: '总支出',
left: 'center',
top: 'center',
textStyle: {
color: getCssVar('--chart-text-muted'), // 适配深色模式
fontSize: 20,
fontWeight: 'bold'
},
subtextStyle: {
color: getCssVar('--chart-text-muted'),
fontSize: 13
}
},
tooltip: {
trigger: 'item',
formatter: (params) => {
return `${params.name}: ¥${formatMoney(params.value)} (${params.percent.toFixed(1)}%)`
}
},
series: [
{
name: '支出分类',
type: 'pie',
radius: ['50%', '80%'],
avoidLabelOverlap: true,
minAngle: 5, // 最小扇区角度,防止扇区太小看不见
itemStyle: {
borderRadius: 5,
borderColor: getCssVar('--van-background-2'),
borderWidth: 2
},
label: {
show: false
},
labelLine: {
show: false
},
data: chartData
}
]
}
pieChartInstance.setOption(option)
}
// 监听数据变化重新渲染图表
watch(() => [props.categories, props.totalExpense, props.colors], () => {
nextTick(() => {
renderPieChart()
})
}, { deep: true, immediate: true })
// 组件销毁时清理图表实例
onBeforeUnmount(() => {
if (pieChartInstance && !pieChartInstance.isDisposed()) {
pieChartInstance.dispose()
}
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
/* 环形图 */
.chart-container {
padding: 0;
}
.ring-chart {
position: relative;
width: 100%;
height: 200px;
margin: 0 auto;
}
/* 分类列表 */
.category-list {
padding: 0;
}
.category-item {
display: flex;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid var(--van-border-color);
transition: background-color 0.2s;
gap: 12px;
}
.category-item:last-child {
border-bottom: none;
}
.category-item.clickable {
cursor: pointer;
}
.category-item.clickable:active {
background-color: var(--van-background);
}
.category-info {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
min-width: 0;
}
.category-name-with-count {
display: flex;
align-items: center;
gap: 8px;
}
.category-color {
width: 12px;
height: 12px;
border-radius: 50%;
}
.category-name {
font-size: 14px;
color: var(--van-text-color);
}
.category-count {
font-size: 12px;
color: var(--van-text-color-3);
}
.category-stats {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.category-arrow {
margin-left: 8px;
color: var(--van-text-color-3);
font-size: 16px;
flex-shrink: 0;
}
.expand-toggle {
display: flex;
justify-content: center;
align-items: center;
padding-top: 0;
color: var(--van-text-color-3);
font-size: 20px;
cursor: pointer;
}
.expand-toggle:active {
opacity: 0.7;
}
.category-amount {
font-size: 15px;
font-weight: 600;
color: var(--van-text-color);
}
.category-percent {
font-size: 12px;
color: var(--van-text-color-3);
background: var(--van-background);
padding: 2px 8px;
border-radius: 10px;
}
</style>

View File

@@ -0,0 +1,272 @@
<template>
<!-- 收支和不计收支并列显示 -->
<div class="side-by-side-cards">
<!-- 收入分类统计 -->
<div class="common-card half-card">
<div class="card-header">
<h3 class="card-title">
收入
<span
class="income-text"
style="font-size: 13px; margin-left: 4px"
>
¥{{ formatMoney(totalIncome) }}
</span>
</h3>
<van-tag
type="success"
size="medium"
>
{{ incomeCategories.length }}
</van-tag>
</div>
<div
v-if="incomeCategories.length > 0"
class="category-list"
>
<div
v-for="category in incomeCategories"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 1)"
>
<div class="category-info">
<div class="category-color income-color" />
<span class="category-name text-ellipsis">{{ category.classify || '未分类' }}</span>
</div>
<div class="category-amount income-text">
¥{{ formatMoney(category.amount) }}
</div>
</div>
</div>
<ModernEmpty
v-else
type="finance"
theme="green"
title="暂无收入"
description="本期还没有收入记录"
size="small"
/>
</div>
<!-- 不计收支分类统计 -->
<div class="common-card half-card">
<div class="card-header">
<h3 class="card-title">
不计收支
</h3>
<van-tag
type="warning"
size="medium"
>
{{ noneCategories.length }}
</van-tag>
</div>
<div
v-if="noneCategories.length > 0"
class="category-list"
>
<div
v-for="category in noneCategories"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 2)"
>
<div class="category-info">
<div class="category-color none-color" />
<span class="category-name text-ellipsis">{{ category.classify || '未分类' }}</span>
</div>
<div class="category-amount none-text">
¥{{ formatMoney(category.amount) }}
</div>
</div>
</div>
<ModernEmpty
v-else
type="inbox"
theme="gray"
title="暂无数据"
description="本期没有不计收支记录"
size="small"
/>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue'
import ModernEmpty from '@/components/ModernEmpty.vue'
const props = defineProps({
incomeCategories: {
type: Array,
default: () => []
},
noneCategories: {
type: Array,
default: () => []
},
totalIncome: {
type: Number,
default: 0
}
})
defineEmits(['category-click'])
// 格式化金额
const formatMoney = (value) => {
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 处理未分类排序
const incomeCategories = computed(() => {
const list = [...props.incomeCategories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
const noneCategories = computed(() => {
const list = [...props.noneCategories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
/* 并列显示卡片 */
.side-by-side-cards {
display: flex;
gap: 12px;
margin: 0 12px 16px;
}
.side-by-side-cards .common-card {
margin: 0;
flex: 1;
min-width: 0; /* 允许内部元素缩小 */
padding: 12px;
}
.card-header {
margin-bottom: 0;
}
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 13px;
}
/* 分类列表 */
.category-list {
padding: 0;
}
.category-item {
display: flex;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid var(--van-border-color);
transition: background-color 0.2s;
gap: 12px;
}
.category-item:last-child {
border-bottom: none;
}
.category-item.clickable {
cursor: pointer;
}
.category-item.clickable:active {
background-color: var(--van-background);
}
.category-info {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
min-width: 0;
}
.category-color {
width: 12px;
height: 12px;
border-radius: 50%;
}
.category-name {
font-size: 14px;
color: var(--van-text-color);
}
.category-amount {
font-size: 15px;
font-weight: 600;
color: var(--van-text-color);
flex-shrink: 0;
}
.income-color {
background-color: var(--van-success-color);
}
.income-text {
color: var(--van-success-color);
}
/* 不计收支颜色 */
.none-color {
background-color: var(--van-gray-6);
}
.none-text {
color: var(--van-gray-6);
}
</style>

View File

@@ -0,0 +1,766 @@
<template>
<van-config-provider :theme="theme">
<div class="page-container-flex statistics-v2-wrapper">
<!-- 头部年月选择器 -->
<CalendarHeader
:type="currentPeriod"
:current-date="currentDate"
:show-notification="true"
@prev="handlePrevPeriod"
@next="handleNextPeriod"
@jump="showDatePicker = true"
@notification="goToStatisticsV1"
/>
<div>
<!-- 时间段选择器 -->
<TimePeriodTabs
:active-tab="currentPeriod"
@change="handlePeriodChange"
/>
</div>
<!-- 可滚动内容区域 -->
<div class="statistics-scroll-content">
<!-- 下拉刷新 -->
<van-pull-refresh
v-model="refreshing"
@refresh="onRefresh"
>
<!-- 加载状态 -->
<van-loading
v-if="loading"
vertical
style="padding: 100px 0"
>
加载统计数据中...
</van-loading>
<!-- 错误状态 -->
<div
v-else-if="hasError"
class="error-state"
>
<van-empty
image="error"
:description="errorMessage || '加载数据时出现错误'"
>
<van-button
type="primary"
size="small"
@click="retryLoad"
>
重试
</van-button>
</van-empty>
</div>
<!-- 统计内容 -->
<div
v-else
class="statistics-content"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<!-- 收支结余和趋势卡片合并 -->
<MonthlyExpenseCard
:amount="monthlyStats.totalExpense"
:income="monthlyStats.totalIncome"
:balance="monthlyStats.balance"
:trend-data="trendStats"
:period="currentPeriod"
:current-date="currentDate"
/>
<!-- 支出分类卡片 -->
<ExpenseCategoryCard
:categories="expenseCategories"
:total-expense="monthlyStats.totalExpense"
:colors="categoryColors"
@category-click="goToCategoryBills"
/>
<!-- 收入和不计收支分类卡片 -->
<IncomeNoneCategoryCard
:income-categories="incomeCategories"
:none-categories="noneCategories"
:total-income="monthlyStats.totalIncome"
@category-click="goToCategoryBills"
/>
</div>
</van-pull-refresh>
</div>
<!-- 日期选择器 -->
<van-popup
v-model:show="showDatePicker"
position="bottom"
:style="{ height: '50%' }"
>
<van-date-picker
v-model="selectedDate"
:type="datePickerType"
:min-date="minDate"
:max-date="maxDate"
@confirm="onDateConfirm"
@cancel="showDatePicker = false"
/>
</van-popup>
<!-- 液态玻璃底部导航栏 -->
<GlassBottomNav
v-model="activeTab"
@tab-click="handleTabClick"
/>
<!-- 分类账单弹窗 -->
<CategoryBillPopup
v-model="billPopupVisible"
:classify="selectedClassify"
:type="selectedType"
:year="currentDate.getFullYear()"
:month="currentPeriod === 'year' ? 0 : currentDate.getMonth() + 1"
@refresh="loadStatistics"
/>
</div>
</van-config-provider>
</template>
<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import CalendarHeader from '@/components/DateSelectHeader.vue'
import TimePeriodTabs from '@/components/TimePeriodTabs.vue'
import MonthlyExpenseCard from './modules/MonthlyExpenseCard.vue'
import ExpenseCategoryCard from './modules/ExpenseCategoryCard.vue'
import IncomeNoneCategoryCard from './modules/IncomeNoneCategoryCard.vue'
import CategoryBillPopup from '@/components/CategoryBillPopup.vue'
import GlassBottomNav from '@/components/GlassBottomNav.vue'
import { getMonthlyStatistics, getCategoryStatistics, getCategoryStatisticsByDateRange, getDailyStatistics, getTrendStatistics, getWeeklyStatistics, getRangeStatistics } from '@/api/statistics'
import { useMessageStore } from '@/stores/message'
import { getCssVar } from '@/utils/theme'
// 为组件缓存设置名称
defineOptions({
name: 'StatisticsV2View'
})
const router = useRouter()
const messageStore = useMessageStore()
// 主题
const theme = computed(() => messageStore.isDarkMode ? 'dark' : 'light')
// 底部导航栏
const activeTab = ref('statistics')
const handleTabClick = (_item, _index) => {
// 导航逻辑已在组件内部处理
}
// 状态管理
const loading = ref(false)
const refreshing = ref(false)
const showDatePicker = ref(false)
const errorMessage = ref('')
const hasError = ref(false)
// 分类账单弹窗状态
const billPopupVisible = ref(false)
const selectedClassify = ref('')
const selectedType = ref(0)
// 触摸滑动相关状态
const touchStartX = ref(0)
const touchStartY = ref(0)
const touchEndX = ref(0)
const touchEndY = ref(0)
// 时间段选择
const currentPeriod = ref('month')
const currentDate = ref(new Date())
const selectedDate = ref([])
const minDate = new Date(2020, 0, 1)
const maxDate = new Date()
// 统计数据
const monthlyStats = ref({
totalExpense: 0,
totalIncome: 0,
balance: 0,
expenseCount: 0,
incomeCount: 0
})
const trendStats = ref([])
const expenseCategories = ref([])
const incomeCategories = ref([])
const noneCategories = ref([])
// 颜色配置
const categoryColors = [
'#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
'#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9'
]
// 计算属性
const datePickerType = computed(() => {
switch (currentPeriod.value) {
case 'week':
case 'month':
return 'year-month'
case 'year':
return 'year'
default:
return 'year-month'
}
})
// 获取周的开始日期(周一)
const getWeekStartDate = (date) => {
const target = new Date(date.valueOf())
const dayNr = (date.getDay() + 6) % 7 // 周一为0周日为6
target.setDate(target.getDate() - dayNr)
target.setHours(0, 0, 0, 0)
return target
}
// 格式化日期为字符串
const formatDateToString = (date) => {
const year = date.getFullYear()
const month = (date.getMonth() + 1).toString().padStart(2, '0')
const day = date.getDate().toString().padStart(2, '0')
return `${year}-${month}-${day}`
}
// 加载统计数据
const loadStatistics = async () => {
if (loading.value && !refreshing.value) {
return // 防止重复加载
}
loading.value = !refreshing.value
try {
const year = currentDate.value.getFullYear()
const month = currentDate.value.getMonth() + 1
// 重置数据
monthlyStats.value = {
totalExpense: 0,
totalIncome: 0,
balance: 0,
expenseCount: 0,
incomeCount: 0
}
trendStats.value = []
expenseCategories.value = []
incomeCategories.value = []
noneCategories.value = []
// 根据时间段加载不同的数据
if (currentPeriod.value === 'month') {
await loadMonthlyData(year, month)
} else if (currentPeriod.value === 'year') {
await loadYearlyData(year)
} else if (currentPeriod.value === 'week') {
await loadWeeklyData()
}
// 加载分类统计
await loadCategoryStatistics(year, month)
} catch (error) {
console.error('加载统计数据失败:', error)
hasError.value = true
errorMessage.value = error.message || '网络连接异常,请检查网络后重试'
} finally {
loading.value = false
}
}
// 重试加载
const retryLoad = () => {
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
// 加载月度数据
const loadMonthlyData = async (year, month) => {
try {
// 月度统计
const monthlyResult = await getMonthlyStatistics({ year, month })
if (monthlyResult?.success && monthlyResult.data) {
monthlyStats.value = {
totalExpense: monthlyResult.data.totalExpense || 0,
totalIncome: monthlyResult.data.totalIncome || 0,
balance: (monthlyResult.data.totalIncome || 0) - (monthlyResult.data.totalExpense || 0),
expenseCount: monthlyResult.data.expenseCount || 0,
incomeCount: monthlyResult.data.incomeCount || 0
}
}
// 加载每日统计
const dailyResult = await getDailyStatistics({ year, month })
if (dailyResult?.success && dailyResult.data) {
trendStats.value = dailyResult.data.filter(item => item != null)
}
} catch (error) {
console.error('加载月度数据失败:', error)
}
}
// 加载年度数据
const loadYearlyData = async (year) => {
try {
// 年度统计 - 使用趋势接口获取12个月数据
const trendResult = await getTrendStatistics({ startYear: year, startMonth: 1, monthCount: 12 })
if (trendResult?.success && trendResult.data) {
// 计算年度汇总
const yearTotal = trendResult.data.reduce((acc, item) => {
const expense = item.expense || 0
const income = item.income || 0
return {
totalExpense: acc.totalExpense + expense,
totalIncome: acc.totalIncome + income,
balance: acc.balance + income - expense
}
}, { totalExpense: 0, totalIncome: 0, balance: 0 })
monthlyStats.value = {
...yearTotal,
expenseCount: 0,
incomeCount: 0
}
trendStats.value = trendResult.data.map(item => ({
date: `${item.year}-${item.month.toString().padStart(2, '0')}-01`,
amount: (item.income || 0) - (item.expense || 0),
count: 1
}))
}
} catch (error) {
console.error('加载年度数据失败:', error)
}
}
// 加载周度数据
const loadWeeklyData = async () => {
try {
// 周统计 - 计算当前周的开始和结束日期
const weekStart = getWeekStartDate(currentDate.value)
const weekEnd = new Date(weekStart)
weekEnd.setDate(weekStart.getDate() + 6)
// 获取周统计汇总
const weekSummaryResult = await getRangeStatistics({
startDate: formatDateToString(weekStart),
endDate: formatDateToString(weekEnd)
})
if (weekSummaryResult?.success && weekSummaryResult.data) {
monthlyStats.value = {
totalExpense: weekSummaryResult.data.totalExpense || 0,
totalIncome: weekSummaryResult.data.totalIncome || 0,
balance: (weekSummaryResult.data.totalIncome || 0) - (weekSummaryResult.data.totalExpense || 0),
expenseCount: weekSummaryResult.data.expenseCount || 0,
incomeCount: weekSummaryResult.data.incomeCount || 0
}
}
// 获取周内每日统计
const dailyResult = await getWeeklyStatistics({
startDate: formatDateToString(weekStart),
endDate: formatDateToString(weekEnd)
})
if (dailyResult?.success && dailyResult.data) {
// 转换数据格式以适配图表组件
trendStats.value = dailyResult.data.map(item => ({
date: item.date,
amount: (item.income || 0) - (item.expense || 0),
count: item.count || 0
}))
}
} catch (error) {
console.error('加载周度数据失败:', error)
}
}
// 加载分类统计
const loadCategoryStatistics = async (year, month) => {
try {
const categoryYear = year
const categoryMonth = month
// 对于周统计,使用日期范围进行分类统计
if (currentPeriod.value === 'week') {
const weekStart = getWeekStartDate(currentDate.value)
const weekEnd = new Date(weekStart)
weekEnd.setDate(weekStart.getDate() + 6)
weekEnd.setHours(23, 59, 59, 999)
const startDateStr = formatDateToString(weekStart)
const endDateStr = formatDateToString(weekEnd)
// 并发加载支出、收入和不计收支分类(使用日期范围)
const [expenseResult, incomeResult, noneResult] = await Promise.allSettled([
getCategoryStatisticsByDateRange({ startDate: startDateStr, endDate: endDateStr, type: 0 }),
getCategoryStatisticsByDateRange({ startDate: startDateStr, endDate: endDateStr, type: 1 }),
getCategoryStatisticsByDateRange({ startDate: startDateStr, endDate: endDateStr, type: 2 })
])
// 获取图表颜色配置
const getChartColors = () => [
getCssVar('--chart-color-1'),
getCssVar('--chart-color-2'),
getCssVar('--chart-color-3'),
getCssVar('--chart-color-4'),
getCssVar('--chart-color-5'),
getCssVar('--chart-color-6'),
getCssVar('--chart-color-7'),
getCssVar('--chart-color-8'),
getCssVar('--chart-color-9'),
getCssVar('--chart-color-10'),
getCssVar('--chart-color-11'),
getCssVar('--chart-color-12'),
getCssVar('--chart-color-13'),
getCssVar('--chart-color-14'),
getCssVar('--chart-color-15')
]
const currentColors = getChartColors()
// 处理支出分类结果
if (expenseResult.status === 'fulfilled' && expenseResult.value?.success && expenseResult.value.data) {
expenseCategories.value = expenseResult.value.data.map((item, index) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0,
color: currentColors[index % currentColors.length]
}))
}
// 处理收入分类结果
if (incomeResult.status === 'fulfilled' && incomeResult.value?.success && incomeResult.value.data) {
incomeCategories.value = incomeResult.value.data.map((item) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0
}))
}
// 处理不计收支分类结果
if (noneResult.status === 'fulfilled' && noneResult.value?.success && noneResult.value.data) {
noneCategories.value = noneResult.value.data.map((item) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0
}))
}
} else {
// 对于月度和年度统计,使用年月进行分类统计
// 并发加载支出、收入和不计收支分类
const [expenseResult, incomeResult, noneResult] = await Promise.allSettled([
getCategoryStatistics({ year: categoryYear, month: categoryMonth, type: 0 }),
getCategoryStatistics({ year: categoryYear, month: categoryMonth, type: 1 }),
getCategoryStatistics({ year: categoryYear, month: categoryMonth, type: 2 })
])
// 获取图表颜色配置
const getChartColors = () => [
getCssVar('--chart-color-1'),
getCssVar('--chart-color-2'),
getCssVar('--chart-color-3'),
getCssVar('--chart-color-4'),
getCssVar('--chart-color-5'),
getCssVar('--chart-color-6'),
getCssVar('--chart-color-7'),
getCssVar('--chart-color-8'),
getCssVar('--chart-color-9'),
getCssVar('--chart-color-10'),
getCssVar('--chart-color-11'),
getCssVar('--chart-color-12'),
getCssVar('--chart-color-13'),
getCssVar('--chart-color-14'),
getCssVar('--chart-color-15')
]
const currentColors = getChartColors()
// 处理支出分类结果
if (expenseResult.status === 'fulfilled' && expenseResult.value?.success && expenseResult.value.data) {
expenseCategories.value = expenseResult.value.data.map((item, index) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0,
color: currentColors[index % currentColors.length]
}))
}
// 处理收入分类结果
if (incomeResult.status === 'fulfilled' && incomeResult.value?.success && incomeResult.value.data) {
incomeCategories.value = incomeResult.value.data.map((item) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0
}))
}
// 处理不计收支分类结果
if (noneResult.status === 'fulfilled' && noneResult.value?.success && noneResult.value.data) {
noneCategories.value = noneResult.value.data.map((item) => ({
classify: item.classify,
amount: item.amount || 0,
count: item.count || 0,
percent: item.percent || 0
}))
}
}
} catch (error) {
console.error('加载分类统计失败:', error)
}
}
// 处理时间段切换
const handlePeriodChange = (period) => {
currentPeriod.value = period
// 清除错误状态
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
// 切换时间周期
const handlePrevPeriod = () => {
const newDate = new Date(currentDate.value)
switch (currentPeriod.value) {
case 'week':
newDate.setDate(newDate.getDate() - 7)
break
case 'month':
newDate.setMonth(newDate.getMonth() - 1)
break
case 'year':
newDate.setFullYear(newDate.getFullYear() - 1)
break
}
currentDate.value = newDate
// 清除错误状态
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
const handleNextPeriod = () => {
// 检查是否已经是最后一个周期(当前周期)
if (isLastPeriod()) {
return
}
const newDate = new Date(currentDate.value)
switch (currentPeriod.value) {
case 'week':
newDate.setDate(newDate.getDate() + 7)
break
case 'month':
newDate.setMonth(newDate.getMonth() + 1)
break
case 'year':
newDate.setFullYear(newDate.getFullYear() + 1)
break
}
currentDate.value = newDate
// 清除错误状态
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
// 判断是否是最后一个周期(不能再往后切换)
const isLastPeriod = () => {
const now = new Date()
const current = new Date(currentDate.value)
switch (currentPeriod.value) {
case 'week': {
// 获取当前周的开始日期和当前时间所在周的开始日期
const currentWeekStart = getWeekStartDate(current)
const nowWeekStart = getWeekStartDate(now)
return currentWeekStart >= nowWeekStart
}
case 'month': {
// 比较年月
return current.getFullYear() === now.getFullYear() &&
current.getMonth() === now.getMonth()
}
case 'year': {
// 比较年份
return current.getFullYear() === now.getFullYear()
}
default:
return false
}
}
// 触摸事件处理
const handleTouchStart = (e) => {
touchStartX.value = e.touches[0].clientX
touchStartY.value = e.touches[0].clientY
}
const handleTouchMove = (e) => {
touchEndX.value = e.touches[0].clientX
touchEndY.value = e.touches[0].clientY
}
const handleTouchEnd = () => {
const deltaX = touchEndX.value - touchStartX.value
const deltaY = touchEndY.value - touchStartY.value
// 判断是否是水平滑动(水平距离大于垂直距离)
if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
if (deltaX > 0) {
// 右滑 - 上一个周期
handlePrevPeriod()
} else {
// 左滑 - 下一个周期
handleNextPeriod()
}
}
// 重置触摸位置
touchStartX.value = 0
touchStartY.value = 0
touchEndX.value = 0
touchEndY.value = 0
}
// 下拉刷新
const onRefresh = async () => {
// 清除错误状态
hasError.value = false
errorMessage.value = ''
await loadStatistics()
refreshing.value = false
}
// 日期选择确认
const onDateConfirm = ({ selectedValues }) => {
if (currentPeriod.value === 'year') {
const [year] = selectedValues
currentDate.value = new Date(year, 0, 1)
} else {
const [year, month] = selectedValues
currentDate.value = new Date(year, month - 1, 1)
}
showDatePicker.value = false
// 清除错误状态
hasError.value = false
errorMessage.value = ''
loadStatistics()
}
// 跳转到分类账单
const goToCategoryBills = (classify, type) => {
selectedClassify.value = classify || ''
selectedType.value = type
billPopupVisible.value = true
}
// 切换到统计V1页面
const goToStatisticsV1 = () => {
router.push({ name: 'statistics' })
}
// 监听时间段变化,更新选中日期
watch(currentPeriod, () => {
if (currentPeriod.value === 'year') {
selectedDate.value = [currentDate.value.getFullYear()]
} else {
selectedDate.value = [
currentDate.value.getFullYear(),
currentDate.value.getMonth() + 1
]
}
})
// 初始化
onMounted(() => {
// 设置默认选中日期
selectedDate.value = [
currentDate.value.getFullYear(),
currentDate.value.getMonth() + 1
]
loadStatistics()
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
/* ========== 页面容器 ========== */
.statistics-v2-wrapper {
font-family: var(--font-primary);
color: var(--text-primary);
height: 100vh;
display: flex;
flex-direction: column;
}
.statistics-scroll-content {
flex: 1;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
overscroll-behavior: contain;
background-color: var(--bg-secondary);
/* 改善滚动性能 */
will-change: scroll-position;
/* 防止滚动卡顿 */
scroll-behavior: smooth;
}
.statistics-content {
padding: var(--spacing-md);
padding-bottom: calc(80px + env(safe-area-inset-bottom, 0px));
min-height: 100%;
/* 确保内容足够高以便滚动 */
display: flex;
flex-direction: column;
gap: var(--spacing-md);
}
.error-state {
padding: var(--spacing-3xl) var(--spacing-md);
text-align: center;
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
/* 在移动设备上优化滚动体验 */
@media (max-width: 768px) {
.statistics-scroll-content {
/* iOS Safari 优化 */
-webkit-overflow-scrolling: touch;
/* 防止橡皮筋效果 */
overscroll-behavior-y: contain;
}
.statistics-content {
padding: var(--spacing-sm);
padding-bottom: calc(90px + env(safe-area-inset-bottom, 0px));
}
}
</style>

View File

@@ -0,0 +1,361 @@
<template>
<div class="daily-trend-card common-card">
<div class="card-header">
<h3 class="card-title">
{{ chartTitle }} (收支)
</h3>
</div>
<div
ref="chartRef"
class="trend-chart"
/>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useMessageStore } from '@/stores/message'
const props = defineProps({
data: {
type: Array,
default: () => []
},
period: {
type: String,
default: 'month'
},
currentDate: {
type: Date,
required: true
}
})
const messageStore = useMessageStore()
const chartRef = ref()
let chartInstance = null
// 计算图表标题
const chartTitle = computed(() => {
switch (props.period) {
case 'week':
return '每日趋势'
case 'month':
return '每日趋势'
case 'year':
return '每月趋势'
default:
return '趋势'
}
})
// 获取月份天数
const getDaysInMonth = (year, month) => {
return new Date(year, month, 0).getDate()
}
// 初始化图表
const initChart = async () => {
await nextTick()
if (!chartRef.value) {
console.warn('图表容器未找到')
return
}
// 销毁已存在的图表实例
if (chartInstance) {
chartInstance.dispose()
chartInstance = null
}
try {
chartInstance = echarts.init(chartRef.value)
updateChart()
} catch (error) {
console.error('初始化图表失败:', error)
}
}
// 更新图表
const updateChart = () => {
if (!chartInstance) {
console.warn('图表实例不存在')
return
}
// 验证数据
if (!Array.isArray(props.data)) {
console.warn('图表数据格式错误')
return
}
// 根据时间段类型和数据来生成图表
let chartData = []
let xAxisLabels = []
try {
if (props.period === 'week') {
// 周统计:直接使用传入的数据,按日期排序
chartData = [...props.data].sort((a, b) => new Date(a.date) - new Date(b.date))
xAxisLabels = chartData.map(item => {
const date = new Date(item.date)
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
return weekDays[date.getDay()]
})
} else if (props.period === 'month') {
// 月统计:生成完整的月份数据
const currentDate = props.currentDate
const year = currentDate.getFullYear()
const month = currentDate.getMonth() + 1
const daysInMonth = getDaysInMonth(year, month)
const allDays = Array.from({ length: daysInMonth }, (_, i) => {
const day = i + 1
const paddedDay = day.toString().padStart(2, '0')
return `${year}-${month.toString().padStart(2, '0')}-${paddedDay}`
})
// 创建完整的数据映射
const dataMap = new Map()
props.data.forEach(item => {
if (item && item.date) {
dataMap.set(item.date, item)
}
})
// 生成完整的数据序列
chartData = allDays.map(date => {
const dayData = dataMap.get(date)
return {
date,
amount: dayData?.amount || 0,
count: dayData?.count || 0
}
})
xAxisLabels = chartData.map((_, index) => (index + 1).toString())
} else if (props.period === 'year') {
// 年统计:直接使用数据,显示月份标签
chartData = [...props.data]
.filter(item => item && item.date)
.sort((a, b) => new Date(a.date) - new Date(b.date))
xAxisLabels = chartData.map(item => {
const date = new Date(item.date)
return `${date.getMonth() + 1}`
})
}
// 如果没有有效数据,显示空图表
if (chartData.length === 0) {
const option = {
backgroundColor: 'transparent',
graphic: [{
type: 'text',
left: 'center',
top: 'middle',
style: {
text: '暂无数据',
fontSize: 16,
fill: messageStore.isDarkMode ? '#9CA3AF' : '#6B7280'
}
}]
}
chartInstance.setOption(option)
return
}
// 准备图表数据
const expenseData = chartData.map(item => {
const amount = item.amount || 0
return amount < 0 ? Math.abs(amount) : 0
})
const incomeData = chartData.map(item => {
const amount = item.amount || 0
return amount > 0 ? amount : 0
})
const isDark = messageStore.isDarkMode
const option = {
backgroundColor: 'transparent',
grid: {
top: 20,
left: 10,
right: 10,
bottom: 20,
containLabel: false
},
xAxis: {
type: 'category',
data: xAxisLabels,
show: false
},
yAxis: {
type: 'value',
show: false
},
series: [
// 支出线
{
name: '支出',
type: 'line',
data: expenseData,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#ff6b6b',
width: 2
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(255, 107, 107, 0.3)' },
{ offset: 1, color: 'rgba(255, 107, 107, 0.05)' }
]
}
}
},
// 收入线
{
name: '收入',
type: 'line',
data: incomeData,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#4ade80',
width: 2
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(74, 222, 128, 0.3)' },
{ offset: 1, color: 'rgba(74, 222, 128, 0.05)' }
]
}
}
}
],
tooltip: {
trigger: 'axis',
backgroundColor: isDark ? 'rgba(39, 39, 42, 0.95)' : 'rgba(255, 255, 255, 0.95)',
borderColor: isDark ? 'rgba(63, 63, 70, 0.8)' : 'rgba(229, 231, 235, 0.8)',
textStyle: {
color: isDark ? '#f4f4f5' : '#1a1a1a'
},
formatter: (params) => {
if (!params || params.length === 0 || !chartData[params[0].dataIndex]) {
return ''
}
const date = chartData[params[0].dataIndex].date
let content = ''
try {
if (props.period === 'week') {
const dateObj = new Date(date)
const month = dateObj.getMonth() + 1
const day = dateObj.getDate()
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
const weekDay = weekDays[dateObj.getDay()]
content = `${month}${day}日 (周${weekDay})<br/>`
} else if (props.period === 'month') {
const day = new Date(date).getDate()
content = `${props.currentDate.getMonth() + 1}${day}日<br/>`
} else if (props.period === 'year') {
const dateObj = new Date(date)
content = `${dateObj.getFullYear()}${dateObj.getMonth() + 1}月<br/>`
}
params.forEach((param) => {
if (param.value > 0) {
const color = param.seriesName === '支出' ? '#ff6b6b' : '#4ade80'
content += `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color}"></span>`
content += `${param.seriesName}: ¥${param.value.toFixed(2)}<br/>`
}
})
} catch (error) {
console.warn('格式化tooltip失败:', error)
content = '数据格式错误'
}
return content
}
}
}
chartInstance.setOption(option)
} catch (error) {
console.error('更新图表失败:', error)
}
}
// 监听数据变化
watch(() => props.data, () => {
if (chartInstance) {
updateChart()
}
}, { deep: true })
// 监听主题变化
watch(() => messageStore.isDarkMode, () => {
if (chartInstance) {
updateChart()
}
})
onMounted(() => {
initChart()
})
onBeforeUnmount(() => {
if (chartInstance) {
chartInstance.dispose()
}
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
.daily-trend-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
.trend-chart {
width: 100%;
height: 180px;
}
</style>

View File

@@ -0,0 +1,27 @@
<template>
<CategoryCard
title="支出分类"
:categories="categories"
:type="0"
tag-type="primary"
empty-description="本期暂无支出记录"
@category-click="handleCategoryClick"
/>
</template>
<script setup>
import CategoryCard from '@/components/Statistics/CategoryCard.vue'
defineProps({
categories: {
type: Array,
default: () => []
}
})
const emit = defineEmits(['category-click'])
const handleCategoryClick = (classify, type) => {
emit('category-click', classify, type)
}
</script>

View File

@@ -0,0 +1,407 @@
<template>
<!-- 支出分类统计 -->
<div
class="common-card"
style="padding-bottom: 10px;"
>
<div class="card-header">
<h3 class="card-title">
支出分类
</h3>
<van-tag
type="primary"
size="medium"
>
{{ expenseCategoriesView.length }}
</van-tag>
</div>
<!-- 环形图区域 -->
<div
v-if="expenseCategoriesView.length > 0"
class="chart-container"
>
<div class="ring-chart">
<div
ref="pieChartRef"
style="width: 100%; height: 100%"
/>
</div>
</div>
<!-- 分类列表 -->
<div class="category-list">
<div
v-for="category in expenseCategoriesSimpView"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 0)"
>
<div class="category-info">
<div
class="category-color"
:style="{ backgroundColor: category.color }"
/>
<div class="category-name-with-count">
<span class="category-name">{{ category.classify || '未分类' }}</span>
<span class="category-count">{{ category.count }}</span>
</div>
</div>
<div class="category-stats">
<div class="category-amount">
¥{{ formatMoney(category.amount) }}
</div>
<div class="category-percent">
{{ category.percent }}%
</div>
</div>
<van-icon
name="arrow"
class="category-arrow"
/>
</div>
<!-- 展开/收起按钮 -->
<div
v-if="expenseCategoriesView.length > 1"
class="expand-toggle"
@click="showAllExpense = !showAllExpense"
>
<van-icon :name="showAllExpense ? 'arrow-up' : 'arrow-down'" />
</div>
</div>
<ModernEmpty
v-if="!expenseCategoriesView || !expenseCategoriesView.length"
type="chart"
theme="blue"
title="暂无支出"
description="本期还没有支出记录"
size="small"
/>
</div>
</template>
<script setup>
import { ref, computed, onBeforeUnmount, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { getCssVar } from '@/utils/theme'
import ModernEmpty from '@/components/ModernEmpty.vue'
const props = defineProps({
categories: {
type: Array,
default: () => []
},
totalExpense: {
type: Number,
default: 0
},
colors: {
type: Array,
default: () => []
}
})
defineEmits(['category-click'])
const pieChartRef = ref(null)
let pieChartInstance = null
const showAllExpense = ref(false)
// 格式化金额
const formatMoney = (value) => {
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 计算属性
const expenseCategoriesView = computed(() => {
const list = [...props.categories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
const expenseCategoriesSimpView = computed(() => {
const list = expenseCategoriesView.value
if (showAllExpense.value) {
return list
}
// 只展示未分类
const unclassified = list.filter((c) => c.classify === '未分类' || !c.classify)
if (unclassified.length > 0) {
return [...unclassified]
}
return []
})
// 渲染饼图
const renderPieChart = () => {
if (!pieChartRef.value) {
return
}
if (expenseCategoriesView.value.length === 0) {
return
}
// 尝试获取DOM上的现有实例
const existingInstance = echarts.getInstanceByDom(pieChartRef.value)
if (pieChartInstance && pieChartInstance !== existingInstance) {
if (!pieChartInstance.isDisposed()) {
pieChartInstance.dispose()
}
pieChartInstance = null
}
if (pieChartInstance && pieChartInstance.getDom() !== pieChartRef.value) {
pieChartInstance.dispose()
pieChartInstance = null
}
if (!pieChartInstance && existingInstance) {
pieChartInstance = existingInstance
}
if (!pieChartInstance) {
pieChartInstance = echarts.init(pieChartRef.value)
}
// 使用 Top N + Other 的数据逻辑,确保图表不会太拥挤
const list = [...expenseCategoriesView.value]
let chartData = []
// 按照金额排序
list.sort((a, b) => b.amount - a.amount)
const MAX_SLICES = 8 // 最大显示扇区数,其余合并为"其他"
if (list.length > MAX_SLICES) {
const topList = list.slice(0, MAX_SLICES - 1)
const otherList = list.slice(MAX_SLICES - 1)
const otherAmount = otherList.reduce((sum, item) => sum + item.amount, 0)
chartData = topList.map((item, index) => ({
value: item.amount,
name: item.classify || '未分类',
itemStyle: { color: props.colors[index % props.colors.length] }
}))
chartData.push({
value: otherAmount,
name: '其他',
itemStyle: { color: getCssVar('--van-gray-6') } // 使用灰色表示其他
})
} else {
chartData = list.map((item, index) => ({
value: item.amount,
name: item.classify || '未分类',
itemStyle: { color: props.colors[index % props.colors.length] }
}))
}
const option = {
title: {
text: '¥' + formatMoney(props.totalExpense),
subtext: '总支出',
left: 'center',
top: 'center',
textStyle: {
color: getCssVar('--chart-text-muted'), // 适配深色模式
fontSize: 20,
fontWeight: 'bold'
},
subtextStyle: {
color: getCssVar('--chart-text-muted'),
fontSize: 13
}
},
tooltip: {
trigger: 'item',
formatter: (params) => {
return `${params.name}: ¥${formatMoney(params.value)} (${params.percent.toFixed(1)}%)`
}
},
series: [
{
name: '支出分类',
type: 'pie',
radius: ['50%', '80%'],
avoidLabelOverlap: true,
minAngle: 5, // 最小扇区角度,防止扇区太小看不见
itemStyle: {
borderRadius: 5,
borderColor: getCssVar('--van-background-2'),
borderWidth: 2
},
label: {
show: false
},
labelLine: {
show: false
},
data: chartData
}
]
}
pieChartInstance.setOption(option)
}
// 监听数据变化重新渲染图表
watch(() => [props.categories, props.totalExpense, props.colors], () => {
nextTick(() => {
renderPieChart()
})
}, { deep: true, immediate: true })
// 组件销毁时清理图表实例
onBeforeUnmount(() => {
if (pieChartInstance && !pieChartInstance.isDisposed()) {
pieChartInstance.dispose()
}
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
/* 环形图 */
.chart-container {
padding: 0;
}
.ring-chart {
position: relative;
width: 100%;
height: 200px;
margin: 0 auto;
}
/* 分类列表 */
.category-list {
padding: 0;
}
.category-item {
display: flex;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid var(--van-border-color);
transition: background-color 0.2s;
gap: 12px;
}
.category-item:last-child {
border-bottom: none;
}
.category-item.clickable {
cursor: pointer;
}
.category-item.clickable:active {
background-color: var(--van-background);
}
.category-info {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
min-width: 0;
}
.category-name-with-count {
display: flex;
align-items: center;
gap: 8px;
}
.category-color {
width: 12px;
height: 12px;
border-radius: 50%;
}
.category-name {
font-size: 14px;
color: var(--van-text-color);
}
.category-count {
font-size: 12px;
color: var(--van-text-color-3);
}
.category-stats {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.category-arrow {
margin-left: 8px;
color: var(--van-text-color-3);
font-size: 16px;
flex-shrink: 0;
}
.expand-toggle {
display: flex;
justify-content: center;
align-items: center;
padding-top: 0;
color: var(--van-text-color-3);
font-size: 20px;
cursor: pointer;
}
.expand-toggle:active {
opacity: 0.7;
}
.category-amount {
font-size: 15px;
font-weight: 600;
color: var(--van-text-color);
}
.category-percent {
font-size: 12px;
color: var(--van-text-color-3);
background: var(--van-background);
padding: 2px 8px;
border-radius: 10px;
}
</style>

View File

@@ -0,0 +1,93 @@
<template>
<div class="income-balance-card common-card">
<div class="stats-row">
<div class="stat-item">
<div class="stat-label">
本月收入
</div>
<div class="stat-amount income">
¥{{ formatMoney(income) }}
</div>
</div>
<div class="stat-item">
<div class="stat-label">
结余
</div>
<div
class="stat-amount"
:class="balanceClass"
>
¥{{ formatMoney(balance) }}
</div>
</div>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue'
import { formatMoney } from '@/utils/format'
const props = defineProps({
income: {
type: Number,
required: true
},
balance: {
type: Number,
required: true
}
})
const balanceClass = computed(() => ({
'positive': props.balance >= 0,
'negative': props.balance < 0
}))
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
.income-balance-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.stats-row {
display: flex;
gap: var(--spacing-3xl);
}
.stat-item {
flex: 1;
.stat-label {
font-size: var(--font-base);
color: var(--text-secondary);
margin-bottom: var(--spacing-md);
}
.stat-amount {
font-size: var(--font-xl);
font-weight: var(--font-semibold);
font-family: var(--font-display);
line-height: 1.2;
&.income {
color: var(--accent-success);
}
&.positive {
color: var(--accent-success);
}
&.negative {
color: var(--accent-danger);
}
}
}
</style>

View File

@@ -0,0 +1,27 @@
<template>
<CategoryCard
title="收入分类"
:categories="categories"
:type="1"
tag-type="success"
empty-description="本期暂无收入记录"
@category-click="handleCategoryClick"
/>
</template>
<script setup>
import CategoryCard from '@/components/Statistics/CategoryCard.vue'
defineProps({
categories: {
type: Array,
default: () => []
}
})
const emit = defineEmits(['category-click'])
const handleCategoryClick = (classify, type) => {
emit('category-click', classify, type)
}
</script>

View File

@@ -0,0 +1,272 @@
<template>
<!-- 收支和不计收支并列显示 -->
<div class="side-by-side-cards">
<!-- 收入分类统计 -->
<div class="common-card half-card">
<div class="card-header">
<h3 class="card-title">
收入
<span
class="income-text"
style="font-size: 13px; margin-left: 4px"
>
¥{{ formatMoney(totalIncome) }}
</span>
</h3>
<van-tag
type="success"
size="medium"
>
{{ incomeCategories.length }}
</van-tag>
</div>
<div
v-if="incomeCategories.length > 0"
class="category-list"
>
<div
v-for="category in incomeCategories"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 1)"
>
<div class="category-info">
<div class="category-color income-color" />
<span class="category-name text-ellipsis">{{ category.classify || '未分类' }}</span>
</div>
<div class="category-amount income-text">
¥{{ formatMoney(category.amount) }}
</div>
</div>
</div>
<ModernEmpty
v-else
type="finance"
theme="green"
title="暂无收入"
description="本期还没有收入记录"
size="small"
/>
</div>
<!-- 不计收支分类统计 -->
<div class="common-card half-card">
<div class="card-header">
<h3 class="card-title">
不计收支
</h3>
<van-tag
type="warning"
size="medium"
>
{{ noneCategories.length }}
</van-tag>
</div>
<div
v-if="noneCategories.length > 0"
class="category-list"
>
<div
v-for="category in noneCategories"
:key="category.classify"
class="category-item clickable"
@click="$emit('category-click', category.classify, 2)"
>
<div class="category-info">
<div class="category-color none-color" />
<span class="category-name text-ellipsis">{{ category.classify || '未分类' }}</span>
</div>
<div class="category-amount none-text">
¥{{ formatMoney(category.amount) }}
</div>
</div>
</div>
<ModernEmpty
v-else
type="inbox"
theme="gray"
title="暂无数据"
description="本期没有不计收支记录"
size="small"
/>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue'
import ModernEmpty from '@/components/ModernEmpty.vue'
const props = defineProps({
incomeCategories: {
type: Array,
default: () => []
},
noneCategories: {
type: Array,
default: () => []
},
totalIncome: {
type: Number,
default: 0
}
})
defineEmits(['category-click'])
// 格式化金额
const formatMoney = (value) => {
if (!value && value !== 0) {
return '0'
}
return Number(value)
.toFixed(0)
.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
// 处理未分类排序
const incomeCategories = computed(() => {
const list = [...props.incomeCategories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
const noneCategories = computed(() => {
const list = [...props.noneCategories]
const unclassifiedIndex = list.findIndex((c) => !c.classify)
if (unclassifiedIndex !== -1) {
const [unclassified] = list.splice(unclassifiedIndex, 1)
list.unshift(unclassified)
}
return list
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--spacing-lg);
}
.card-title {
font-size: var(--font-lg);
font-weight: var(--font-semibold);
color: var(--text-primary);
margin: 0;
}
/* 并列显示卡片 */
.side-by-side-cards {
display: flex;
gap: 12px;
margin: 0 12px 16px;
}
.side-by-side-cards .common-card {
margin: 0;
flex: 1;
min-width: 0; /* 允许内部元素缩小 */
padding: 12px;
}
.card-header {
margin-bottom: 0;
}
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 13px;
}
/* 分类列表 */
.category-list {
padding: 0;
}
.category-item {
display: flex;
align-items: center;
padding: 12px 0;
border-bottom: 1px solid var(--van-border-color);
transition: background-color 0.2s;
gap: 12px;
}
.category-item:last-child {
border-bottom: none;
}
.category-item.clickable {
cursor: pointer;
}
.category-item.clickable:active {
background-color: var(--van-background);
}
.category-info {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
min-width: 0;
}
.category-color {
width: 12px;
height: 12px;
border-radius: 50%;
}
.category-name {
font-size: 14px;
color: var(--van-text-color);
}
.category-amount {
font-size: 15px;
font-weight: 600;
color: var(--van-text-color);
flex-shrink: 0;
}
.income-color {
background-color: var(--van-success-color);
}
.income-text {
color: var(--van-success-color);
}
/* 不计收支颜色 */
.none-color {
background-color: var(--van-gray-6);
}
.none-text {
color: var(--van-gray-6);
}
</style>

View File

@@ -0,0 +1,504 @@
<template>
<div class="monthly-expense-card common-card">
<!-- 收支结余一行展示 -->
<div class="stats-row">
<div class="stat-item expense">
<div class="stat-label">
支出
</div>
<div class="stat-amount">
¥{{ formatMoney(amount) }}
</div>
</div>
<div class="stat-item income">
<div class="stat-label">
收入
</div>
<div class="stat-amount">
¥{{ formatMoney(income) }}
</div>
</div>
<div class="stat-item balance">
<div class="stat-label">
结余
</div>
<div
class="stat-amount"
:class="balanceClass"
>
¥{{ formatMoney(balance) }}
</div>
</div>
</div>
<!-- 趋势图 -->
<div class="trend-section">
<div
ref="chartRef"
class="trend-chart"
/>
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { formatMoney } from '@/utils/format'
import { useMessageStore } from '@/stores/message'
const props = defineProps({
amount: {
type: Number,
required: true
},
income: {
type: Number,
default: 0
},
balance: {
type: Number,
default: 0
},
trendData: {
type: Array,
default: () => []
},
period: {
type: String,
default: 'month'
},
currentDate: {
type: Date,
required: true
}
})
const messageStore = useMessageStore()
const chartRef = ref()
let chartInstance = null
// 计算结余样式类
const balanceClass = computed(() => ({
'positive': props.balance >= 0,
'negative': props.balance < 0
}))
// 计算图表标题
const chartTitle = computed(() => {
switch (props.period) {
case 'week':
return '每日趋势'
case 'month':
return '每日趋势'
case 'year':
return '每月趋势'
default:
return '趋势'
}
})
// 获取月份天数
const getDaysInMonth = (year, month) => {
return new Date(year, month, 0).getDate()
}
// 初始化图表
const initChart = async () => {
await nextTick()
if (!chartRef.value) {
console.warn('图表容器未找到')
return
}
// 销毁已存在的图表实例
if (chartInstance) {
chartInstance.dispose()
chartInstance = null
}
try {
chartInstance = echarts.init(chartRef.value)
updateChart()
} catch (error) {
console.error('初始化图表失败:', error)
}
}
// 更新图表
const updateChart = () => {
if (!chartInstance) {
console.warn('图表实例不存在')
return
}
// 验证数据
if (!Array.isArray(props.trendData)) {
console.warn('图表数据格式错误')
return
}
// 根据时间段类型和数据来生成图表
let chartData = []
let xAxisLabels = []
try {
if (props.period === 'week') {
// 周统计:直接使用传入的数据,按日期排序
chartData = [...props.trendData].sort((a, b) => new Date(a.date) - new Date(b.date))
xAxisLabels = chartData.map(item => {
const date = new Date(item.date)
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
return weekDays[date.getDay()]
})
} else if (props.period === 'month') {
// 月统计:生成完整的月份数据
const currentDate = props.currentDate
const year = currentDate.getFullYear()
const month = currentDate.getMonth() + 1
const daysInMonth = getDaysInMonth(year, month)
const allDays = Array.from({ length: daysInMonth }, (_, i) => {
const day = i + 1
const paddedDay = day.toString().padStart(2, '0')
return `${year}-${month.toString().padStart(2, '0')}-${paddedDay}`
})
// 创建完整的数据映射
const dataMap = new Map()
props.trendData.forEach(item => {
if (item && item.date) {
dataMap.set(item.date, item)
}
})
// 生成完整的数据序列
chartData = allDays.map(date => {
const dayData = dataMap.get(date)
return {
date,
expense: dayData?.expense || 0,
income: dayData?.income || 0,
count: dayData?.count || 0
}
})
xAxisLabels = chartData.map((_, index) => (index + 1).toString())
} else if (props.period === 'year') {
// 年统计:直接使用数据,显示月份标签
chartData = [...props.trendData]
.filter(item => item && item.date)
.sort((a, b) => new Date(a.date) - new Date(b.date))
xAxisLabels = chartData.map(item => {
const date = new Date(item.date)
return `${date.getMonth() + 1}`
})
}
// 如果没有有效数据,显示空图表
if (chartData.length === 0) {
const option = {
backgroundColor: 'transparent',
graphic: [{
type: 'text',
left: 'center',
top: 'middle',
style: {
text: '暂无数据',
fontSize: 16,
fill: messageStore.isDarkMode ? '#9CA3AF' : '#6B7280'
}
}]
}
chartInstance.setOption(option)
return
}
// 准备图表数据 - 计算累计值
let cumulativeExpense = 0
let cumulativeIncome = 0
const expenseData = []
const incomeData = []
chartData.forEach(item => {
// 支持两种数据格式1) expense/income字段 2) amount字段兼容旧数据
let expense = 0
let income = 0
if (item.expense !== undefined || item.income !== undefined) {
expense = item.expense || 0
income = item.income || 0
} else {
const amount = item.amount || 0
if (amount < 0) {
expense = Math.abs(amount)
} else {
income = amount
}
}
// 累加计算
cumulativeExpense += expense
cumulativeIncome += income
expenseData.push(cumulativeExpense)
incomeData.push(cumulativeIncome)
})
const isDark = messageStore.isDarkMode
const option = {
backgroundColor: 'transparent',
grid: {
top: 20,
left: 10,
right: 10,
bottom: 20,
containLabel: false
},
xAxis: {
type: 'category',
data: xAxisLabels,
show: false
},
yAxis: {
type: 'value',
show: false
},
series: [
// 支出线
{
name: '支出',
type: 'line',
data: expenseData,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#ff6b6b',
width: 2
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(255, 107, 107, 0.3)' },
{ offset: 1, color: 'rgba(255, 107, 107, 0.05)' }
]
}
}
},
// 收入线
{
name: '收入',
type: 'line',
data: incomeData,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#4ade80',
width: 2
},
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(74, 222, 128, 0.3)' },
{ offset: 1, color: 'rgba(74, 222, 128, 0.05)' }
]
}
}
}
],
tooltip: {
trigger: 'axis',
backgroundColor: isDark ? 'rgba(39, 39, 42, 0.95)' : 'rgba(255, 255, 255, 0.95)',
borderColor: isDark ? 'rgba(63, 63, 70, 0.8)' : 'rgba(229, 231, 235, 0.8)',
textStyle: {
color: isDark ? '#f4f4f5' : '#1a1a1a'
},
formatter: (params) => {
if (!params || params.length === 0 || !chartData[params[0].dataIndex]) {
return ''
}
const dataIndex = params[0].dataIndex
const date = chartData[dataIndex].date
const item = chartData[dataIndex]
let content = ''
try {
if (props.period === 'week') {
const dateObj = new Date(date)
const month = dateObj.getMonth() + 1
const day = dateObj.getDate()
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
const weekDay = weekDays[dateObj.getDay()]
content = `${month}${day}日 (周${weekDay})<br/>`
} else if (props.period === 'month') {
const day = new Date(date).getDate()
content = `${props.currentDate.getMonth() + 1}${day}日<br/>`
} else if (props.period === 'year') {
const dateObj = new Date(date)
content = `${dateObj.getFullYear()}${dateObj.getMonth() + 1}月<br/>`
}
// 计算当日值
let dailyExpense = 0
let dailyIncome = 0
if (item.expense !== undefined || item.income !== undefined) {
dailyExpense = item.expense || 0
dailyIncome = item.income || 0
} else {
const amount = item.amount || 0
if (amount < 0) {
dailyExpense = Math.abs(amount)
} else {
dailyIncome = amount
}
}
// 显示累计值和当日值
params.forEach((param) => {
const color = param.seriesName === '支出' ? '#ff6b6b' : '#4ade80'
const cumulativeValue = param.value
const dailyValue = param.seriesName === '支出' ? dailyExpense : dailyIncome
content += `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color}"></span>`
content += `${param.seriesName}累计: ¥${cumulativeValue.toFixed(2)}`
if (dailyValue > 0) {
content += ` (当日: ¥${dailyValue.toFixed(2)})`
}
content += '<br/>'
})
} catch (error) {
console.warn('格式化tooltip失败:', error)
content = '数据格式错误'
}
return content
}
}
}
chartInstance.setOption(option)
} catch (error) {
console.error('更新图表失败:', error)
}
}
// 监听数据变化
watch(() => props.trendData, () => {
if (chartInstance) {
updateChart()
}
}, { deep: true })
// 监听主题变化
watch(() => messageStore.isDarkMode, () => {
if (chartInstance) {
updateChart()
}
})
onMounted(() => {
initChart()
})
onBeforeUnmount(() => {
if (chartInstance) {
chartInstance.dispose()
}
})
</script>
<style scoped lang="scss">
@import '@/assets/theme.css';
// 通用卡片样式
.common-card {
background: var(--bg-primary);
border-radius: var(--radius-lg);
padding: var(--spacing-xl);
margin-bottom: var(--spacing-xl);
box-shadow: var(--shadow-sm);
}
.monthly-expense-card {
display: flex;
flex-direction: column;
gap: var(--spacing-lg);
}
// 收支结余一行展示
.stats-row {
display: flex;
justify-content: space-between;
gap: var(--spacing-md);
padding-bottom: var(--spacing-md);
border-bottom: 1px solid var(--border-color);
}
.stat-item {
flex: 1;
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
text-align: center;
.stat-label {
color: var(--text-secondary);
font-family: var(--font-primary);
font-size: var(--font-sm);
font-weight: var(--font-medium);
}
.stat-amount {
font-family: var(--font-display);
font-size: var(--font-xl);
font-weight: var(--font-bold);
}
&.expense .stat-amount {
color: var(--accent-danger);
}
&.income .stat-amount {
color: var(--accent-success);
}
&.balance .stat-amount {
color: var(--accent-primary);
&.positive {
color: var(--accent-success);
}
&.negative {
color: var(--accent-danger);
}
}
}
// 趋势图部分
.trend-section {
display: flex;
flex-direction: column;
gap: var(--spacing-md);
}
.trend-chart {
width: 100%;
height: 180px;
}
</style>