<template>
	<view class="fee-statistics-page">
		<NavBar title="费用统计" bgColor="#ffffff" color="#000"></NavBar>
		<!-- 顶部背景 -->
		<view class="header-bg">
			<view class="total-title">总服务费 (元)</view>
			<view class="total-amount">{{ totalFee }}</view>
			<view class="date-picker-wrap">
				<picker mode="date" fields="month" @change="onDateChange">
					<view class="date-range">
						<text>{{ currentDateText }}</text>
						<uni-icons type="bottom" size="14" color="#fff"></uni-icons>
					</view>
				</picker>
			</view>
		</view>

		<!-- 统计卡片 -->
		<view class="stats-card">
			<view class="stats-item">
				<text class="stats-value">{{ totalCount }}</text>
				<text class="stats-label">单数</text>
			</view>
			<view class="stats-divider"></view>
			<view class="stats-item">
				<text class="stats-value">{{ maxFee }}</text>
				<text class="stats-label">最高单笔</text>
			</view>
			<view class="stats-divider"></view>
			<view class="stats-item">
				<text class="stats-value">{{ avgFee }}</text>
				<text class="stats-label">平均单笔</text>
			</view>
		</view>

		<!-- 订单明细 -->
		<view class="detail-section">
			<view class="section-header">
				<view class="header-line"></view>
				<text class="header-text">订单明细</text>
			</view>

			<view class="detail-list">
				<view class="detail-item" v-for="(item, index) in orderDetails" :key="index">
					<view class="detail-info">
						<view class="detail-title">{{ item.title }}</view>
						<view class="detail-time">{{ item.time }}</view>
					</view>
					<view class="detail-amount-wrap">
						<view class="detail-amount">+{{ item.amount }}</view>
						<view class="detail-no">{{ item.orderNo }}</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import NavBar from '@/components/nav-bar/index.vue'
import { listOnFeeStatistic } from '@/api/order/subOrder'
import { listAll } from '@/api/service/list'

const orderDetails = ref([])
const totalFee = ref('0.00')
const totalCount = ref(0)
const maxFee = ref('0.00')
const avgFee = ref('0.00')

const serviceMap = ref({})

const currentDateText = ref('本月')
const queryParams = ref({
	pageNum: 1,
	pageSize: 9999,
	'params[beginTime]': '',
	'params[endTime]': ''
})

const getList = async () => {
	try {
		uni.showLoading({ title: '加载中' })
		const res = await listOnFeeStatistic(queryParams.value)
		
		const list = res.rows || []
		let sum = 0
		let max = 0
		
		orderDetails.value = list.map(item => {
			// 后端金额是分，转化为元
			const amount = (item.orderCommission || 0) / 100
			sum += amount
			if (amount > max) {
				max = amount
			}
            
            // 组装标题 (优先团购套餐，否则通过serviceId获取服务名称)
            let finalTitle = item.groupPurchasePackageName || ''
            if (!finalTitle) {
                const sId = (item.service || item.serviceId || '').toString().trim()
                if (sId) {
                    finalTitle = serviceMap.value[sId] || '未知服务'
                }
            }

			return {
				title: finalTitle || '基础服务',
				time: item.createTime || '',
				amount: amount.toFixed(2),
				orderNo: item.code || ''
			}
		})
		
		totalCount.value = list.length
		totalFee.value = sum.toFixed(2)
		maxFee.value = max.toFixed(2)
		avgFee.value = list.length > 0 ? (sum / list.length).toFixed(2) : '0.00'
		
	} catch (e) {
		console.error(e)
	} finally {
		uni.hideLoading()
	}
}

const onDateChange = (e) => {
	const val = e.detail.value // "YYYY-MM"
	currentDateText.value = val
	// 简单的处理将月份转为当月起始和结束时间
	const date = new Date(val + '-01')
	const year = date.getFullYear()
	const month = date.getMonth()
	const lastDay = new Date(year, month + 1, 0).getDate()
	
	queryParams.value['params[beginTime]'] = `${val}-01 00:00:00`
	queryParams.value['params[endTime]'] = `${val}-${lastDay} 23:59:59`
	
	getList()
}

const getServices = async () => {
    try {
        const res = await listAll()
        const dataList = res.data || res.rows || (Array.isArray(res) ? res : [])
        if (Array.isArray(dataList)) {
            const tempMap = {}
            dataList.forEach(s => {
                if (s.id) {
                    tempMap[String(s.id).trim()] = s.name
                }
            })
            serviceMap.value = tempMap
        }
    } catch (e) {
        console.error('获取服务类型失败', e)
    }
}

onLoad(async () => {
	// 默认本月
	const now = new Date()
	const year = now.getFullYear()
	let month = now.getMonth() + 1
	if (month < 10) month = '0' + month
	
	const val = `${year}-${month}`
	currentDateText.value = val
	const lastDay = new Date(year, month, 0).getDate()
	
	queryParams.value['params[beginTime]'] = `${val}-01 00:00:00`
	queryParams.value['params[endTime]'] = `${val}-${lastDay} 23:59:59`
	
    uni.showLoading({ title: '加载中' })
    await getServices()
	getList()
})
</script>

<style lang="scss" scoped>
.fee-statistics-page {
	min-height: 100vh;
	background-color: #f8f9fb;
}

.header-bg {
	background: linear-gradient(180deg, #ff7b00 0%, #ff9500 100%);
	padding: 60rpx 40rpx 140rpx;
	text-align: center;
	color: #fff;
}

.total-title {
	font-size: 28rpx;
	opacity: 0.9;
	margin-bottom: 20rpx;
}

.total-amount {
	font-size: 80rpx;
	font-weight: 900;
	margin-bottom: 40rpx;
}

.date-picker-wrap {
	display: inline-block;
}

.date-range {
	background: rgba(255, 255, 255, 0.2);
	padding: 12rpx 32rpx;
	border-radius: 40rpx;
	font-size: 24rpx;
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.stats-card {
	background: #fff;
	margin: -80rpx 32rpx 40rpx;
	padding: 40rpx 0;
	border-radius: 32rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.05);
	position: relative;
	z-index: 2;
}

.stats-item {
	flex: 1;
	text-align: center;
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}

.stats-value {
	font-size: 36rpx;
	font-weight: 800;
	color: #1a1a1a;
}

.stats-label {
	font-size: 22rpx;
	color: #999;
}

.stats-divider {
	width: 2rpx;
	height: 60rpx;
	background: #f0f0f0;
}

.detail-section {
	padding: 0 32rpx;
}

.section-header {
	display: flex;
	align-items: center;
	gap: 12rpx;
	margin-bottom: 24rpx;
}

.header-line {
	width: 8rpx;
	height: 32rpx;
	background: #ff7b00;
	border-radius: 4rpx;
}

.header-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.detail-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.detail-item {
	background: #fff;
	padding: 32rpx;
	border-radius: 24rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.detail-info {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}

.detail-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

.detail-time {
	font-size: 24rpx;
	color: #999;
}

.detail-amount-wrap {
	text-align: right;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.detail-amount {
	font-size: 32rpx;
	font-weight: bold;
	color: #ff5252;
}

.detail-no {
	font-size: 22rpx;
	color: #ccc;
}
</style>
