<template>
	<view class="page">
		<view class="header">
			<view class="search-bar">
				<FaIcon name="magnifying-glass" color="#ffffff" :size="16" />
				<text class="search-text">搜索功能、数据...</text>
			</view>
		</view>

		<view class="main-scroll">
			<view class="stats-grid">
				<view class="stat-card" v-for="item in stats" :key="item.label">
					<text class="stat-label">{{ item.label }}</text>
					<text class="stat-value">{{ item.value }}</text>
					<view class="stat-trend" :class="item.up ? 'up' : 'down'">
						<FaIcon :name="item.up ? 'arrow-trend-up' : 'arrow-trend-down'" :color="item.up ? '#3c9cff' : '#909399'" :size="12" />
						<text>{{ item.trend }}</text>
					</view>
				</view>
			</view>

			<view class="section">
				<view class="section-header">
					<text class="section-title">快捷入口</text>
				</view>
				<view class="quick-card">
					<view
						class="quick-item"
						v-for="item in quickActions"
						:key="item.name"
						@tap="onQuickTap(item)"
					>
						<view class="quick-icon">
							<FaIcon :name="item.icon" color="#3c9cff" :size="20" />
						</view>
						<text class="quick-name">{{ item.name }}</text>
					</view>
				</view>
			</view>

			<view class="section">
				<view class="section-header">
					<text class="section-title">最近动态</text>
				</view>
				<view class="activity-card">
					<view v-if="activities.length === 0" class="activity-empty">
						<text class="activity-empty-text">暂无动态</text>
					</view>
					<view class="activity-item" v-for="(item, index) in activities" :key="index" @tap="onActivityTap(item)">
						<view class="activity-dot" :class="item.type" />
						<view class="activity-body">
							<text class="activity-title">{{ item.title }}</text>
							<text class="activity-time">{{ item.time }}</text>
						</view>
						<FaIcon name="chevron-right" color="#c0c4cc" :size="12" />
					</view>
				</view>
			</view>

			<view class="bottom-space" />
		</view>

		<AppTabbar current="dashboard" />
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getUser, isLoggedIn } from '@/utils/auth.js'
import { fetchNotes } from '@/api/note.js'
import { fetchSchedules } from '@/api/schedule.js'
import { request } from '@/api/request.js'
import AppTabbar from '@/components/AppTabbar.vue'

const user = ref(null)

const noteCount = ref(0)
const scheduleCount = ref(0)
const schedulePending = ref(0)

const stats = computed(() => [
	{ label: '记事本', value: String(noteCount.value), trend: '条笔记', up: true },
	{ label: '日程提醒', value: String(scheduleCount.value), trend: '条日程', up: true },
	{ label: '待办事项', value: String(schedulePending.value), trend: '项待办', up: schedulePending.value > 0 },
	{ label: '活跃天数', value: '1', trend: '今天', up: true }
])

const quickActions = ref([
	{ name: '记事本', icon: 'note-sticky', route: '/pages/tools/notepad/index' },
	{ name: '日程提醒', icon: 'calendar-days', route: '/pages/tools/schedule/index' },
	{ name: '新建笔记', icon: 'pen-to-square', route: '/pages/tools/notepad/edit' },
	{ name: '新建日程', icon: 'clock', route: '/pages/tools/schedule/edit' }
])

const activities = ref([])

function formatTime(ts) {
	if (!ts) return ''
	const now = Date.now()
	const diff = now - ts
	const minute = 60 * 1000
	const hour = 60 * minute
	const day = 24 * hour
	if (diff < minute) return '刚刚'
	if (diff < hour) return `${Math.floor(diff / minute)} 分钟前`
	if (diff < day) return `${Math.floor(diff / hour)} 小时前`
	if (diff < 7 * day) return `${Math.floor(diff / day)} 天前`
	const d = new Date(ts)
	return `${d.getMonth() + 1}/${d.getDate()}`
}

function formatTimeStr(dateStr) {
	if (!dateStr) return ''
	const ts = new Date(dateStr.replace(' ', 'T')).getTime()
	return formatTime(ts)
}

async function loadDashboard() {
	try {
		const [noteRes, schedRes, actRes] = await Promise.all([
			fetchNotes({ keyword: '' }).catch(() => ({ list: [], total: 0 })),
			fetchSchedules({ keyword: '', status: 'all' }).catch(() => ({ list: [], total: 0 })),
			request({ url: '/app/activity/list', data: { limit: 8 } }).catch(() => [])
		])

		noteCount.value = noteRes.total || 0
		scheduleCount.value = schedRes.total || 0
		schedulePending.value = (schedRes.list || []).filter(s => !s.completed).length

		const actList = Array.isArray(actRes) ? actRes : (actRes?.list || actRes || [])

		activities.value = actList.map(item => ({
			type: item.target_type || 'other',
			title: item.title || `${item.target_type} ${item.action}`,
			time: formatTimeStr(item.created_at),
			route: item.target_type === 'note' ? '/pages/tools/notepad/index' : '/pages/tools/schedule/index'
		})).slice(0, 5)
	} catch (e) {
		console.error('loadDashboard error:', e)
	}
}

onMounted(() => {
	if (!isLoggedIn()) {
		uni.reLaunch({ url: '/pages/login/login' })
		return
	}
	user.value = getUser()
	loadDashboard()
})

onShow(() => {
	if (isLoggedIn()) loadDashboard()
})

function onQuickTap(item) {
	if (item.route) {
		uni.navigateTo({ url: item.route })
	} else {
		uni.showToast({ title: item.name, icon: 'none' })
	}
}

function onActivityTap(item) {
	if (item.route) {
		uni.navigateTo({ url: item.route })
	}
}
</script>

<style lang="scss" scoped>
@import '@/src/styles/page-common.scss';

.page {
	@include page-shell;
}

.header {
	flex-shrink: 0;
	padding: calc(var(--status-bar-height, 44px) + 20rpx) $page-padding-x 20rpx;
	background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
	box-shadow: 0 4rpx 16rpx rgba(79, 172, 254, 0.15);
	position: relative;
}

.search-bar {
	display: flex;
	align-items: center;
	gap: 16rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: $radius-full;
	padding: 16rpx 24rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.search-text {
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.7);
}

.main-scroll {
	@include scroll-body;
}

.stats-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 20rpx;
	margin-bottom: 32rpx;
}

.stat-card {
	@include card;
	padding: 28rpx 24rpx;
}

.stat-label {
	display: block;
	font-size: 24rpx;
	color: $color-text-muted;
}

.stat-value {
	display: block;
	font-size: 40rpx;
	font-weight: 600;
	color: $color-text;
	margin-top: 8rpx;
}

.stat-trend {
	display: inline-flex;
	align-items: center;
	gap: 6rpx;
	margin-top: 16rpx;
	padding: 4rpx 12rpx;
	border-radius: $radius-sm;
	font-size: 22rpx;

	&.up {
		background: $color-primary-bg;
		color: $color-primary;
	}

	&.down {
		background: $color-divider;
		color: $color-text-muted;
	}
}

.section {
	margin-bottom: 32rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.section-title {
	@include section-title;
}

.section-more {
	font-size: 26rpx;
	color: $color-primary;
}

.quick-card {
	@include card;
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	padding: 32rpx 16rpx;
}

.quick-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 12rpx;

	&:active {
		opacity: 0.7;
	}
}

.quick-icon {
	width: 88rpx;
	height: 88rpx;
	border-radius: 12rpx;
	background: linear-gradient(135deg, rgba(79, 172, 254, 0.15) 0%, rgba(0, 242, 254, 0.15) 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.quick-name {
	font-size: 24rpx;
	color: $color-text-secondary;
}

.activity-card {
	@include card;
	overflow: hidden;
}

.activity-empty {
	padding: 48rpx 0;
	text-align: center;
}

.activity-empty-text {
	font-size: 26rpx;
	color: $color-text-muted;
}

.activity-item {
	display: flex;
	align-items: center;
	padding: 28rpx 24rpx;
	gap: 16rpx;

	& + & {
		border-top: 1rpx solid $color-divider;
	}

	&:active {
		background: $color-bg-page;
	}
}

.activity-dot {
	width: 16rpx;
	height: 16rpx;
	border-radius: 50%;
	flex-shrink: 0;
	background: #909399;

	&.notebook {
		background: #67c23a;
	}

	&.schedule {
		background: $color-primary;
	}

	&.erp {
		background: #e6a23c;
	}

	&.file {
		background: #f56c6c;
	}
}

.activity-body {
	flex: 1;
	min-width: 0;
}

.activity-title {
	display: block;
	font-size: 28rpx;
	color: $color-text;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.activity-time {
	display: block;
	font-size: 24rpx;
	color: $color-text-muted;
	margin-top: 6rpx;
}

.bottom-space {
	height: 24rpx;
}
</style>
