<template>
	<view class="page">
		<view class="warpbox">
			<!-- 顶部筛选区域 -->
			<view class="header-section">
				<view class="page-title"></view>
				<view class="filter-box">
					<picker mode="date" fields="month" :value="selectedMonth" @change="onMonthChange">
						<view class="date-picker-trigger">
							<text class="date-text">{{ selectedMonthText }}</text>
							<u-icon name="arrow-down" size="14" color="#666"></u-icon>
						</view>
					</picker>
					<picker mode="selector" :range="storeOptions" range-key="fullName" :value="storeIndex" @change="onStoreChange">
						<view class="store-picker-trigger">
							<text class="store-text">{{ currentStoreName || '请选择门店' }}</text>
							<u-icon name="arrow-down" size="14" color="#666"></u-icon>
						</view>
					</picker>
					<!-- 截图按钮 -->
					<!-- #ifdef H5 -->
					<view class="screenshot-btn" v-if="showScreenshotBtn" @click="saveScreenshot" :class="{ loading: screenshotLoading }">
						<u-icon name="photo" size="18" color="#409EFF"></u-icon>
						<text class="screenshot-text">截图</text>
					</view>
					<!-- #endif -->
				</view>
			</view>

			<!-- 门店信息卡片 -->
			<!-- <view class="warpboxss store-info-section" v-if="currentStoreName">
				<view class="store-info-card">
					<view class="store-avatar">
						<u-icon name="home" size="32" color="#fff"></u-icon>
					</view>
					<view class="store-details">
						<view class="store-name">{{ currentStoreName }}</view>
						<view class="store-meta">
							<text v-if="currentStoreCode">编码: {{ currentStoreCode }}</text>
							<text v-if="currentStoreAddress">{{ currentStoreAddress }}</text>
						</view>
					</view>
				</view>
			</view> -->

			<!-- 核心KPI指标 -->
			<view class="kpi-section" v-if="storeData">
				<!-- 上方4个指标 -->
				<view class="glass-card billing-card">
					<view class="billing-main" v-for="(kpi, index) in kpiListTop.slice(0, 2)" :key="index">
						<view class="stat-content">
							<view class="label-row">
								<view class="stat-icon-small" :class="kpi.type">
									<u-icon :name="kpi.icon || 'chart'" :size="20" color="#fff"></u-icon>
								</view>
								<view class="card-label">{{ kpi.label }}</view>
							</view>
							<view class="billing-value">
								<text class="currency" v-if="kpi.isMoney">￥</text>
								<text class="value">{{ kpi.isMoney ? formatMoney(kpi.value) : (kpi.isPercent ? parseFloat(kpi.value || 0).toFixed(2) : formatNumber(kpi.value)) }}</text>
								<text class="unit" v-if="kpi.isPercent">%</text>
							</view>
						</view>
					</view>
					<view class="billing-footer">
						<view class="count-item" v-for="(kpi, index) in kpiListTop.slice(2, 4)" :key="index">
							<view class="count-icon" :class="kpi.type">
								<u-icon :name="kpi.icon || 'chart'" :size="20" color="#fff"></u-icon>
							</view>
							<text class="count-text">
								<text class="count-value">{{ kpi.label  +' '}}{{ kpi.isPercent ? parseFloat(kpi.value || 0).toFixed(2) + '%' : formatNumber(kpi.value) }}</text>
							</text>
						</view>
					</view>
				</view>
				<!-- 下方3个指标 -->
				<view class="kpi-grid-bottom">
					<view class="kpi-card" v-for="(kpi, index) in kpiListBottom" :key="index">
						<view class="kpi-header">
							<view class="kpi-icon-square" :class="kpi.type">
								<u-icon :name="kpi.icon || 'chart'" :size="16" color="#fff"></u-icon>
							</view>
							<text class="kpi-label">{{ kpi.label }}</text>
						</view>
						<view class="kpi-value-group">
							<text class="value">
								<text class="currency" v-if="kpi.isMoney">￥</text>
								{{ kpi.isMoney ? formatMoney(kpi.value) : (kpi.isPercent ? parseFloat(kpi.value || 0).toFixed(2) : formatNumber(kpi.value)) }}
							</text>
							<text class="unit" v-if="kpi.isPercent">%</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 近12个月业绩趋势 -->
			<view class="warpboxss trend-section" v-if="monthlyTrendData.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>近12个月业绩趋势</view>
				</view>
				<view class="chart-wrapper trend-chart-box">
					<qiun-data-charts 
						type="line"
						:opts="trendChartOpts"
						:chartData="trendChartData"
						:ontouch="true"
						:inScrollView="true"
						:pageScrollTop="pageScrollTop"
						background="rgba(255, 255, 255, 0.8)"
						:canvas2d="true"
					/>
				</view>
			</view>

			<!-- 品项分类占比 -->
			<view class="warpboxss category-section" v-if="categoryData.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>品项分类占比</view>
				</view>
				<view class="category-chart-container">
					<view class="category-chart-wrapper">
						<qiun-data-charts 
							type="pie"
							:opts="categoryChartOpts"
							:chartData="categoryChartData"
							:ontouch="true"
							:inScrollView="true"
							:pageScrollTop="pageScrollTop"
							:canvas2d="true"
						/>
					</view>
					<view class="category-legend">
						<view class="legend-item" v-for="(item, index) in categoryData" :key="index">
							<view class="legend-dot" :style="{ backgroundColor: item.CategoryName === '生美' ? '#A8D5E2' : item.CategoryName === '医美' ? '#B8E6B8' : item.CategoryName === '科美' ? '#FFD4A3' : item.CategoryName === '产品' ? '#E6C1E6' : item.CategoryName === '教育' ? '#F5DEB3' : '#DDA0DD' }"></view>
							<text class="legend-name">{{ item.CategoryName || '其他' }}</text>
							<text class="legend-value">￥{{ formatMoney(item.ConsumeAmount) }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 业绩对比分析 -->
			<view class="warpboxss compare-section" v-if="monthlyTrendData.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>业绩对比分析</view>
				</view>
				<view class="chart-wrapper">
					<qiun-data-charts 
						type="column"
						:opts="compareChartOpts"
						:chartData="compareChartData"
						:ontouch="true"
						:inScrollView="true"
						:pageScrollTop="pageScrollTop"
						background="rgba(255, 255, 255, 0.8)"
						:canvas2d="true"
					/>
				</view>
			</view>

			<!-- 各分类业绩堆叠对比 -->
			<view class="warpboxss stacked-section" v-if="categoryMonthlyData.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>各分类业绩堆叠对比</view>
				</view>
				<view class="chart-wrapper">
					<qiun-data-charts 
						type="column"
						:opts="stackedChartOpts"
						:chartData="stackedChartData"
						:ontouch="true"
						:inScrollView="true"
						:pageScrollTop="pageScrollTop"
						background="rgba(255, 255, 255, 0.8)"
						:canvas2d="true"
					/>
				</view>
			</view>

			<!-- 拓客转化漏斗 -->
			<view class="warpboxss funnel-section" v-if="funnelData">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>拓客转化漏斗</view>
				</view>
				<view class="chart-wrapper">
					<qiun-data-charts 
						type="funnel"
						:opts="funnelChartOpts"
						:chartData="funnelChartData"
						:ontouch="true"
						:inScrollView="true"
						:pageScrollTop="pageScrollTop"
						:canvas2d="true"
					/>
				</view>
			</view>

			<!-- 客单价与项目数关系分析 -->
			<view class="warpboxss scatter-section" v-if="scatterData.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>客单价与项目数关系分析</view>
				</view>
				<view class="chart-wrapper scatter-chart-box">
					<qiun-data-charts 
						type="scatter"
						:opts="scatterChartOpts"
						:chartData="scatterChartData"
						:ontouch="true"
						:inScrollView="true"
						:pageScrollTop="pageScrollTop"
						background="rgba(255, 255, 255, 0.8)"
						:canvas2d="true"
					/>
				</view>
				<view class="scatter-legend">
					<view class="legend-note">
						<text class="legend-dot" style="background-color: #409EFF;"></text>
						<text class="legend-text">气泡大小表示会员数量</text>
					</view>
				</view>
			</view>

			<!-- 一周运营热力图 -->
			<view class="warpboxss heatmap-section" v-if="heatmapData.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>一周运营热力图</view>
				</view>
				<view class="heatmap-grid">
					<!-- 时间轴标签行 -->
					<view class="heatmap-row heatmap-time-header">
						<view class="heatmap-day"></view>
						<view class="heatmap-times">
							<view 
								class="heatmap-time-label" 
								v-for="(hour, hourIndex) in heatmapHours" 
								:key="hourIndex"
							>
								{{ hour }}
							</view>
						</view>
					</view>
					<!-- 数据行 -->
					<view class="heatmap-row" v-for="(day, dayIndex) in ['周一', '周二', '周三', '周四', '周五', '周六', '周日']" :key="dayIndex">
						<view class="heatmap-day">{{ day }}</view>
						<view class="heatmap-times">
							<view 
								class="heatmap-cell" 
								v-for="(cell, hourIndex) in heatmapMatrix[dayIndex]" 
								:key="hourIndex"
								:style="{ backgroundColor: cell.color, color: cell.textColor }"
								:class="{ 'has-data': cell.value > 0 }"
							>
								{{ cell.value > 0 ? formatNumber(cell.value, 0) : '' }}
							</view>
						</view>
					</view>
				</view>
				<view class="heatmap-legend">
					<view class="legend-item">
						<view class="legend-color" style="background-color: #f5f5f5;"></view>
						<text class="legend-text">无数据</text>
					</view>
					<view class="legend-item">
						<view class="legend-color" style="background-color: #dbeafe;"></view>
						<text class="legend-text">较少</text>
					</view>
					<view class="legend-item">
						<view class="legend-color" style="background-color: #93c5fd;"></view>
						<text class="legend-text">中等</text>
					</view>
					<view class="legend-item">
						<view class="legend-color" style="background-color: #60a5fa;"></view>
						<text class="legend-text">较多</text>
					</view>
					<view class="legend-item">
						<view class="legend-color" style="background-color: #3b82f6;"></view>
						<text class="legend-text">很多</text>
					</view>
					<view class="legend-item">
						<view class="legend-color" style="background-color: #1e40af;"></view>
						<text class="legend-text">最多</text>
					</view>
				</view>
			</view>

			<!-- 品项开单排行 -->
			<view class="warpboxss item-ranking-section" v-if="topBillingItems.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>品项开单排行（Top 10）</view>
				</view>
				<view class="rank-list-modern">
					<view class="rank-item" v-for="(item, index) in topBillingItems.slice(0, 10)" :key="index">
						<view class="rank-idx" :class="index < 3 ? 'top-3' : ''">
							<image v-if="index === 0" src="/static/rank/no1.png" class="medal-icon"></image>
							<image v-else-if="index === 1" src="/static/rank/no2.png" class="medal-icon"></image>
							<image v-else-if="index === 2" src="/static/rank/no3.png" class="medal-icon"></image>
							<text v-else>{{ index + 1 }}</text>
						</view>
						<view class="rank-info">
							<view class="info-main">
								<text class="name">{{ item.itemName || '未知品项' }}</text>
								<text class="value">￥{{ formatMoney(item.billingAmount) }}</text>
							</view>
							<view class="progress-bg">
								<view class="progress-bar" :style="{ width: (topBillingItems.length > 0 ? (item.billingAmount / (topBillingItems[0].billingAmount || 1) * 100) : 0) + '%' }"></view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 健康师业绩排行 -->
			<view class="warpboxss coach-section" v-if="healthCoachRanking.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>健康师业绩排行（Top 10）</view>
				</view>
				<view class="rank-list-modern">
					<view class="rank-item" v-for="(item, index) in healthCoachRanking.slice(0, 10)" :key="index">
						<view class="rank-idx" :class="index === 0 ? 'rank-1' : (index === 1 ? 'rank-2' : (index === 2 ? 'rank-3' : ''))">
							<text>{{ index + 1 }}</text>
						</view>
						<view class="rank-avatar">
							<text>{{ item.name ? item.name.substring(0, 1) : '无' }}</text>
						</view>
						<view class="rank-info">
							<view class="info-main">
								<text class="name">{{ item.name || '未知' }}</text>
								<view class="performance-values">
									<text class="perf-item">开单: ￥{{ formatMoney(item.billingPerformance) }}</text>
									<text class="perf-item">消耗: ￥{{ formatMoney(item.consumePerformance) }}</text>
									<text class="perf-item">净业绩: ￥{{ formatMoney(item.totalPerformance) }}</text>
								</view>
							</view>
							<view class="progress-bg">
								<view class="progress-bar green" :style="{ width: (healthCoachRanking.length > 0 ? (item.totalPerformance / (healthCoachRanking[0].totalPerformance || 1) * 100) : 0) + '%' }"></view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 消耗品项排行 -->
			<view class="warpboxss consume-item-section" v-if="topConsumeItems.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>消耗品项排行（Top 10）</view>
				</view>
				<view class="item-grid">
					<view class="item-card" v-for="(item, index) in topConsumeItems.slice(0, 10)" :key="index">
						<view class="item-rank-badge" :class="'rank-' + (index + 1)">{{ index + 1 }}</view>
						<view class="item-name">{{ item.itemName || '未知品项' }}</view>
						<view class="item-val">￥{{ formatMoney(item.consumeAmount) }}</view>
						<view class="item-process">
							<view class="bar" :style="{ width: (topConsumeItems.length > 0 ? (item.consumeAmount / (topConsumeItems[0].consumeAmount || 1) * 100) : 0) + '%' }"></view>
						</view>
					</view>
				</view>
			</view>

			<!-- 业绩概览 -->
			<view class="warpboxss metrics-section" v-if="performanceList.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>业绩概览</view>
				</view>
				<view class="metrics-grid">
					<view class="metric-item" v-for="(item, index) in performanceList" :key="index">
						<view class="metric-label">{{ item.label }}</view>
						<view class="metric-value">{{ item.value }}</view>
					</view>
				</view>
			</view>

			<!-- 运营指标 -->
			<view class="warpboxss metrics-section" v-if="operationList.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>运营指标</view>
				</view>
				<view class="metrics-grid">
					<view class="metric-item" v-for="(item, index) in operationList" :key="index">
						<view class="metric-label">{{ item.label }}</view>
						<view class="metric-value">{{ item.value }}</view>
					</view>
				</view>
			</view>

			<!-- 会员分析 -->
			<view class="warpboxss metrics-section" v-if="memberList.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>会员分析</view>
				</view>
				<view class="metrics-grid">
					<view class="metric-item" v-for="(item, index) in memberList" :key="index">
						<view class="metric-label">{{ item.label }}</view>
						<view class="metric-value">{{ item.value }}</view>
						<view class="metric-rate" v-if="item.rate">{{ item.rate }}</view>
					</view>
				</view>
			</view>

			<!-- 目标完成度 -->
			<view class="warpboxss gauge-section" v-if="storeData && storeData.Performance">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>目标完成度</view>
				</view>
				<view class="gauge-container">
					<view class="gauge-circle">
						<view class="gauge-progress" :style="{ 
							background: `conic-gradient(${gaugeColor} ${completionRate * 3.6}deg, #f0f0f0 ${completionRate * 3.6}deg)` 
						}">
							<view class="gauge-inner">
								<view class="gauge-value-text">{{ completionRateText }}%</view>
								<view class="gauge-label">完成率</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 门店排名对比 -->
			<view class="warpboxss comparison-section" v-if="comparison.totalStoreCount > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>门店排名对比</view>
				</view>
				<view class="comparison-content">
					<view class="ranking-item">
						<view class="ranking-label">业绩排名</view>
						<view class="ranking-value">
							<text class="rank-number">{{ comparison.performanceRanking }}</text>
							<text class="rank-total">/ {{ formatNumber(comparison.totalStoreCount, 0) }}</text>
						</view>
						<view class="ranking-badge" :class="rankingClass">
							{{ rankingText }}
						</view>
					</view>
					<view class="comparison-stats">
						<view class="stat-row">
							<text class="stat-label">同类型门店平均业绩</text>
							<text class="stat-value">¥{{ formatMoney(comparison.avgPerformanceSameType) }}</text>
						</view>
						<view class="stat-row">
							<text class="stat-label">同类型门店数</text>
							<text class="stat-value">{{ formatNumber(comparison.sameTypeStoreCount, 0) }}家</text>
						</view>
						<view class="stat-row">
							<text class="stat-label">同组织门店平均业绩</text>
							<text class="stat-value">¥{{ formatMoney(comparison.avgPerformanceSameOrg) }}</text>
						</view>
						<view class="stat-row">
							<text class="stat-label">同组织门店数</text>
							<text class="stat-value">{{ formatNumber(comparison.sameOrgStoreCount, 0) }}家</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 本月经营提示 -->
			<view class="warpboxss tips-section" v-if="operationTips.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>本月经营提示</view>
				</view>
				<view class="tips-list">
					<view class="tip-item" v-for="(tip, index) in operationTips" :key="index" :class="tip.type">
						<text>{{ tip.text }}</text>
					</view>
				</view>
			</view>

			<!-- 快速数据洞察 -->
			<view class="warpboxss insight-section" v-if="dataInsights.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>快速数据洞察</view>
				</view>
				<view class="insight-list">
					<view class="insight-item" v-for="(insight, index) in dataInsights" :key="index">
						<view class="insight-header">
							<text class="insight-title">{{ insight.title }}</text>
							<text class="insight-tag" :class="insight.tag === '优秀' || insight.tag === '热门' || insight.tag === '重点' ? 'tag-highlight' : ''">{{ insight.tag }}</text>
						</view>
						<view class="insight-value">{{ insight.value }}</view>
						<view class="insight-desc">{{ insight.desc }}</view>
					</view>
				</view>
			</view>

			<!-- 本月关键指标 -->
			<view class="warpboxss key-metrics-section" v-if="keyMetrics.length > 0">
				<view class="warpboxs-small-title">
					<view><text class="warpboxs-small-title-line"></text>本月关键指标</view>
				</view>
				<view class="key-metrics-list">
					<view class="key-metric-item" v-for="(metric, index) in keyMetrics" :key="index">
						<view class="metric-header">
							<text class="metric-label">{{ metric.label }}</text>
							<text class="metric-value">{{ metric.value }}%</text>
						</view>
						<view class="progress-wrapper">
							<view class="progress-bar" :style="{ width: metric.value + '%', backgroundColor: metric.color }"></view>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部安全区域 -->
			<view style="height: 150rpx;"></view>
		</view>
	</view>
</template>

<script>
import uCharts from '@qiun/ucharts'
import storeDashboardAPI from '@/apis/modules/store-dashboard.js'
import storeAPI from '@/apis/modules/store.js'

// uCharts 图表工具类
const ChartUtil = {
	// 格式化数字为万单位（用于图表显示）
	formatChartValue(val) {
		if (val === null || val === undefined || isNaN(val)) return '0.00'
		const numVal = typeof val === 'string' ? parseFloat(val) : val
		if (isNaN(numVal)) return '0.00'
		if (numVal >= 10000) {
			return (numVal / 10000).toFixed(2) + '万'
		}
		return numVal.toFixed(2)
	},
	// 绘制折线图
	drawLineChart(vueInstance, canvasId, categories, series, options = {}) {
		if (!categories || categories.length === 0 || !series || series.length === 0) {
			return
		}
		
		const chartData = {
			categories: categories,
			series: series.map((s, index) => ({
				name: s.name || `系列${index + 1}`,
				data: s.data,
				color: s.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C'][index],
				textStyle: {
					show: false
				},
				label: {
					show: false
				}
			}))
		}
		
		const opts = {
			type: 'line',
			fontSize: 10,
			dataLabel: false,
			dataPointShape: false,
			disableLabel: true,
			disableLabel: true,
			legend: {
				show: false
			},
			xAxis: {
				disableGrid: false,
				itemCount: categories.length > 12 ? 12 : categories.length,
				rotateLabel: true,
				rotateAngle: 45,
				marginTop: 5
			},
			yAxis: {
				gridType: 'dash',
				dashLength: 2,
				format: (val) => {
					const numVal = typeof val === 'string' ? parseFloat(val) : val
					if (isNaN(numVal)) return '0.00'
					if (numVal >= 10000) {
						return (numVal / 10000).toFixed(2) + '万'
					}
					return numVal.toFixed(2)
				}
			},
			extra: {
				line: {
					type: 'curve',
					width: 2,
					activeType: 'none',
					disableLabel: true,
					labelShow: false
				},
				tooltip: {
					showBox: true,
					showArrow: true,
					showCategory: true,
					format: (item, category) => {
						return category + '\n' + item.name + ': ' + ChartUtil.formatChartValue(item.data)
					}
				}
			}
		}
		
		const query = uni.createSelectorQuery().in(vueInstance)
		query.select(`#${canvasId}`).boundingClientRect((rect) => {
			if (!rect || !rect.width || !rect.height) {
				console.warn(`图表容器 ${canvasId} 尺寸获取失败`, rect)
				return
			}
			const ctx = uni.createCanvasContext(canvasId, vueInstance)
			const systemInfo = uni.getSystemInfoSync()
			const pixelRatio = systemInfo.pixelRatio || 1
			const chartWidth = Math.floor(uni.upx2px(rect.width) * pixelRatio) || options.width || 700
			const chartHeight = Math.floor(uni.upx2px(rect.height) * pixelRatio) || options.height || 400
			const chart = new uCharts({
				type: 'line',
				context: ctx,
				width: chartWidth,
				height: chartHeight,
				categories: chartData.categories,
				series: chartData.series,
				animation: true,
				background: 'none',
				color: chartData.series.map(s => s.color),
				padding: [20, 10, 10, 10],
				enableScroll: false,
				legend: opts.legend,
				xAxis: opts.xAxis,
				yAxis: opts.yAxis,
				extra: opts.extra
			})
		}).exec()
	},
	
	// 绘制柱状图
	drawColumnChart(vueInstance, canvasId, categories, series, options = {}) {
		if (!categories || categories.length === 0 || !series || series.length === 0) {
			return
		}
		
		const chartData = {
			categories: categories,
			series: series.map((s, index) => ({
				name: s.name || `系列${index + 1}`,
				data: s.data,
				color: s.color || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C'][index]
			}))
		}
		
		// 如果提供了自定义 Y 轴格式化函数，使用它；否则使用默认的万单位格式化
		const yAxisFormat = options.yAxisFormat || ((val) => {
			return val >= 10000 ? (val / 10000).toFixed(2) + '万' : val.toFixed(2)
		})
		
		const opts = {
			type: 'column',
			fontSize: 10,
			dataLabel: false,
			legend: {
				show: false
			},
			xAxis: {
				disableGrid: false,
				itemCount: categories.length > 12 ? 12 : categories.length
			},
			yAxis: {
				gridType: 'dash',
				dashLength: 2,
				format: yAxisFormat
			},
			extra: {
				column: {
					type: 'group',
					width: 0.6,
					activeBgColor: '#000000',
					activeBgOpacity: 0.08
				},
				tooltip: {
					showBox: true,
					showArrow: true,
					showCategory: true,
					format: (item, category) => {
						return category + '\n' + item.name + ': ' + ChartUtil.formatChartValue(item.data)
					}
				}
			}
		}
		
		const query = uni.createSelectorQuery().in(vueInstance)
		query.select(`#${canvasId}`).boundingClientRect((rect) => {
			if (!rect || !rect.width || !rect.height) {
				console.warn(`图表容器 ${canvasId} 尺寸获取失败`, rect)
				return
			}
			const ctx = uni.createCanvasContext(canvasId, vueInstance)
			const systemInfo = uni.getSystemInfoSync()
			const pixelRatio = systemInfo.pixelRatio || 1
			const chartWidth = Math.floor(uni.upx2px(rect.width) * pixelRatio) || options.width || 700
			const chartHeight = Math.floor(uni.upx2px(rect.height) * pixelRatio) || options.height || 400
			const chart = new uCharts({
				type: 'column',
				context: ctx,
				width: chartWidth,
				height: chartHeight,
				categories: chartData.categories,
				series: chartData.series,
				animation: true,
				background: 'none',
				color: chartData.series.map(s => s.color),
				padding: [20, 10, 0, 10],
				enableScroll: false,
				legend: opts.legend,
				xAxis: opts.xAxis,
				yAxis: opts.yAxis,
				extra: opts.extra
			})
		}).exec()
	},
	
	// 绘制饼图
	drawPieChart(vueInstance, canvasId, data, options = {}) {
		if (!data || data.length === 0) {
			return
		}
		
		const chartData = {
			series: [{
				data: data.map(item => ({
					name: item.name,
					value: item.value,
					color: item.color
				}))
			}]
		}
		
		const opts = {
			type: 'pie',
			fontSize: 10,
			dataLabel: true,
			legend: {
				show: false
			},
			extra: {
				pie: {
					activeOpacity: 0.5,
					activeRadius: 10,
					offsetAngle: 0,
					labelWidth: 15,
					border: true,
					borderWidth: 3,
					borderColor: '#FFFFFF',
					ringWidth: 30
				},
				tooltip: {
					showBox: true,
					showArrow: true,
					format: (item) => {
						return item.name + ': ' + ChartUtil.formatChartValue(item.data)
					}
				}
			}
		}
		
		const query = uni.createSelectorQuery().in(vueInstance)
		query.select(`#${canvasId}`).boundingClientRect((rect) => {
			if (!rect || !rect.width || !rect.height) {
				console.warn(`图表容器 ${canvasId} 尺寸获取失败`, rect)
				return
			}
			const ctx = uni.createCanvasContext(canvasId, vueInstance)
			const systemInfo = uni.getSystemInfoSync()
			const pixelRatio = systemInfo.pixelRatio || 1
			const chartWidth = Math.floor(uni.upx2px(rect.width) * pixelRatio) || options.width || 400
			const chartHeight = Math.floor(uni.upx2px(rect.height) * pixelRatio) || options.height || 400
			const chart = new uCharts({
				type: 'pie',
				context: ctx,
				width: chartWidth,
				height: chartHeight,
				series: chartData.series,
				animation: true,
				background: 'none',
				color: chartData.series[0].data.map(d => d.color),
				padding: 0,
				enableScroll: false,
				legend: opts.legend,
				extra: opts.extra
			})
		}).exec()
	},
	
	// 绘制漏斗图
	drawFunnelChart(vueInstance, canvasId, data, options = {}) {
		if (!data || data.length === 0) {
			return
		}
		
		const sortedData = [...data].sort((a, b) => (b.value || 0) - (a.value || 0))
		
		const chartData = {
			series: [{
				data: sortedData.map(item => {
					const value = Number(item.value) || 0
					return {
						name: item.name || '',
						centerText: ChartUtil.formatChartValue(value),
						value: value
					}
				})
			}]
		}
		
		const opts = {
			type: 'funnel',
			fontSize: 10,
			dataLabel: true,
			padding: [15, 15, 0, 15],
			enableScroll: false,
			color: sortedData.map(item => item.color),
			extra: {
				funnel: {
					activeOpacity: 0.3,
					activeWidth: 10,
					border: true,
					borderWidth: 2,
					borderColor: '#FFFFFF',
					fillOpacity: 1,
					labelAlign: 'right'
				},
				tooltip: {
					showBox: true,
					showArrow: true,
					format: (item) => {
						return item.name + ': ' + ChartUtil.formatChartValue(item.data)
					}
				}
			}
		}
		
		const query = uni.createSelectorQuery().in(vueInstance)
		query.select(`#${canvasId}`).boundingClientRect((rect) => {
			if (!rect || !rect.width || !rect.height) {
				console.warn(`图表容器 ${canvasId} 尺寸获取失败`, rect)
				return
			}
			const ctx = uni.createCanvasContext(canvasId, vueInstance)
			const systemInfo = uni.getSystemInfoSync()
			const pixelRatio = systemInfo.pixelRatio || 1
			const chartWidth = Math.floor(uni.upx2px(rect.width) * pixelRatio) || options.width || 700
			const chartHeight = Math.floor(uni.upx2px(rect.height) * pixelRatio) || options.height || 500
			const chart = new uCharts({
				type: 'funnel',
				context: ctx,
				width: chartWidth,
				height: chartHeight,
				series: chartData.series,
				animation: true,
				background: 'none',
				color: opts.color,
				padding: opts.padding,
				enableScroll: opts.enableScroll,
				extra: opts.extra
			})
		}).exec()
	},
	
	// 绘制仪表盘
	drawGaugeChart(vueInstance, canvasId, data, options = {}) {
		if (!data || data.length === 0) {
			return
		}
		
		// uCharts 仪表盘图表需要 categories（刻度标签对象数组）和 series（数据）
		const categories = [
			{ value: 0, text: '0' },
			{ value: 20, text: '20' },
			{ value: 40, text: '40' },
			{ value: 60, text: '60' },
			{ value: 80, text: '80' },
			{ value: 100, text: '100' }
		]
		const firstItem = data[0]
		const value = Number(firstItem.value) || 0
		
		const chartData = {
			categories: categories,
			series: [{
				name: firstItem.name || '完成率',
				data: [value],
				color: firstItem.color || '#409EFF'
			}]
		}
		
		const opts = {
			type: 'gauge',
			fontSize: 10,
			dataLabel: true,
			padding: [15, 15, 0, 15],
			enableScroll: false,
			color: [firstItem.color || '#409EFF'],
			extra: {
				gauge: {
					startAngle: 0,
					endAngle: 360,
					startRadius: 0,
					endRadius: 100,
					labelOffset: 10,
					ringWidth: 20,
					splitLine: {
						show: true,
						lineLength: 10,
						lineStyle: {
							width: 2,
							color: '#E0E0E0'
						}
					},
					pointer: {
						show: true,
						length: 80,
						width: 6
					}
				},
				tooltip: {
					showBox: true,
					showArrow: true
				}
			}
		}
		
		const query = uni.createSelectorQuery().in(vueInstance)
		query.select(`#${canvasId}`).boundingClientRect((rect) => {
			if (!rect || !rect.width || !rect.height) {
				console.warn(`图表容器 ${canvasId} 尺寸获取失败`, rect)
				return
			}
			const ctx = uni.createCanvasContext(canvasId, vueInstance)
			const systemInfo = uni.getSystemInfoSync()
			const pixelRatio = systemInfo.pixelRatio || 1
			const chartWidth = Math.floor(uni.upx2px(rect.width) * pixelRatio) || options.width || 400
			const chartHeight = Math.floor(uni.upx2px(rect.height) * pixelRatio) || options.height || 300
			const chart = new uCharts({
				type: 'gauge',
				context: ctx,
				width: chartWidth,
				height: chartHeight,
				categories: chartData.categories,
				series: chartData.series,
				animation: true,
				background: 'none',
				color: opts.color,
				padding: opts.padding,
				enableScroll: opts.enableScroll,
				extra: opts.extra
			})
		}).exec()
	}
}

export default {
	data() {
		return {
			loading: false,
			screenshotLoading: false, // 截图加载状态
			showScreenshotBtn: true, // 是否显示截图按钮
			selectedMonth: '',
			storeIndex: -1,
			storeOptions: [],
			currentStoreName: '',
			currentStoreCode: '',
			currentStoreAddress: '',
			selectedStoreId: '',
			pageScrollTop: 0, // 页面滚动位置
			
			// 门店统计数据
			storeData: null,
			monthlyTrendData: [],
			categoryData: [],
			categoryMonthlyData: [],
			funnelData: null,
			scatterData: [],
			heatmapData: [],
			topBillingItems: [],
			topConsumeItems: [],
			healthCoachRanking: [],
			comparison: {
				performanceRanking: 0,
				totalStoreCount: 0,
				avgPerformanceSameType: 0,
				sameTypeStoreCount: 0,
				avgPerformanceSameOrg: 0,
				sameOrgStoreCount: 0
			},
			// 业绩概览、运营指标、会员分析
			performanceList: [],
			operationList: [],
			memberList: [],
			// 本月经营提示、快速数据洞察、本月关键指标
			operationTips: [],
			dataInsights: [],
			keyMetrics: [],
			// 会员分析数据
			memberAnalysisData: null,
			// 趋势图表数据
			trendChartData: {},
			trendChartOpts: {
				color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
				padding: [15, 10, 0, 15],
				enableScroll: true,
				dataLabel: false,
				dataPointShape: true,
				legend: {},
				xAxis: {
					disableGrid: true,
					scrollShow: true,
					itemCount: 4
				},
				yAxis: {
					gridType: "dash",
					dashLength: 2,
					format: (val) => {
						const numVal = typeof val === 'string' ? parseFloat(val) : val
						if (isNaN(numVal)) return '0.00'
						if (numVal >= 10000) {
							return (numVal / 10000).toFixed(2) + '万'
						}
						return numVal.toFixed(2)
					}
				},
				extra: {
					line: {
						type: "straight",
						width: 2,
						activeType: "hollow"
					},
					tooltip: {
						showBox: true,
						showArrow: true,
						showCategory: true,
						format: (item, category) => {
							return category + '\n' + item.name + ': ' + ChartUtil.formatChartValue(item.data)
						}
					}
				}
			},
			// 品项分类占比图表数据
			categoryChartData: {},
			categoryChartOpts: {
				color: ["#A8D5E2", "#B8E6B8", "#FFD4A3", "#E6C1E6", "#F5DEB3", "#DDA0DD"],
				padding: [15, 15, 0, 15],
				dataLabel: false,
				legend: {
					show: false
				},
				extra: {
					pie: {
						activeOpacity: 0.5,
						activeRadius: 10,
						offsetAngle: 0,
						labelWidth: 15,
						border: true,
						borderWidth: 3,
						borderColor: '#FFFFFF',
						ringWidth: 30
					},
					tooltip: {
						showBox: true,
						showArrow: true,
						format: (item) => {
							return item.name + ': ' + ChartUtil.formatChartValue(item.data)
						}
					}
				}
			},
			// 业绩对比分析图表数据
			compareChartData: {},
			compareChartOpts: {
				color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
				padding: [15, 15, 0, 5],
				touchMoveLimit: 24,
				enableScroll: true,
				dataLabel: false,
				legend: {},
				xAxis: {
					disableGrid: true,
					scrollShow: true,
					itemCount: 4
				},
				yAxis: {
					data: [
						{
							min: 0
						}
					],
					format: (val) => {
						const numVal = typeof val === 'string' ? parseFloat(val) : val
						if (isNaN(numVal)) return '0.00万'
						return numVal.toFixed(2) + '万'
					}
				},
				extra: {
					column: {
						type: "group",
						width: 30,
						activeBgColor: "#000000",
						activeBgOpacity: 0.08
					},
					tooltip: {
						showBox: true,
						showArrow: true,
						showCategory: true,
						format: (item, category) => {
							const numVal = typeof item.data === 'string' ? parseFloat(item.data) : item.data
							const formattedVal = isNaN(numVal) ? '0.00' : numVal.toFixed(2)
							return category + '\n' + item.name + ': ' + formattedVal + '万'
						}
					}
				}
			},
			// 各分类业绩堆叠对比图表数据
			stackedChartData: {},
			stackedChartOpts: {
				color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
				padding: [15, 15, 0, 5],
				touchMoveLimit: 24,
				enableScroll: true,
				dataLabel: false,
				legend: {},
				xAxis: {
					disableGrid: true,
					scrollShow: true,
					itemCount: 4
				},
				yAxis: {
					data: [
						{
							min: 0
						}
					],
					format: (val) => {
						const numVal = typeof val === 'string' ? parseFloat(val) : val
						if (isNaN(numVal)) return '0.00万'
						return numVal.toFixed(2) + '万'
					}
				},
				extra: {
					column: {
						type: "group",
						width: 30,
						activeBgColor: "#000000",
						activeBgOpacity: 0.08
					},
					tooltip: {
						showBox: true,
						showArrow: true,
						showCategory: true,
						format: (item, category) => {
							const numVal = typeof item.data === 'string' ? parseFloat(item.data) : item.data
							const formattedVal = isNaN(numVal) ? '0.00' : numVal.toFixed(2)
							return category + '\n' + item.name + ': ' + formattedVal + '万'
						}
					}
				}
			},
			// 拓客转化漏斗图表数据
			funnelChartData: {},
			funnelChartOpts: {
				color: ["#409EFF", "#67C23A", "#E6A23C", "#909399"],
				padding: [15, 15, 0, 15],
				dataLabel: false,
				extra: {
					funnel: {
						activeOpacity: 0.3,
						activeWidth: 10,
						border: true,
						borderWidth: 2,
						borderColor: '#FFFFFF',
						fillOpacity: 1,
						labelAlign: 'right'
					},
					tooltip: {
						showBox: true,
						showArrow: true,
						format: (item) => {
							return item.name + ': ' + ChartUtil.formatChartValue(item.data)
						}
					}
				}
			},
			// 客单价与项目数关系散点图数据
			scatterChartData: {},
			scatterChartOpts: {
				color: ["#409EFF"],
				padding: [15, 25, 15, 15],
				enableScroll: false,
				dataLabel: false,
				dataPointShape: true,
				legend: {
					show: false
				},
				xAxis: {
					disableGrid: false,
					name: '客单价(元)',
					nameLocation: 'middle',
					nameGap: 30,
					format: (val) => {
						const numVal = typeof val === 'string' ? parseFloat(val) : val
						if (isNaN(numVal)) return '0'
						if (numVal >= 10000) {
							return (numVal / 10000).toFixed(1) + '万'
						}
						return numVal.toFixed(0)
					}
				},
				yAxis: {
					gridType: 'dash',
					dashLength: 2,
					name: '项目数',
					nameLocation: 'middle',
					nameGap: 50,
					format: (val) => {
						const numVal = typeof val === 'string' ? parseFloat(val) : val
						if (isNaN(numVal)) return '0'
						return numVal.toFixed(1)
					}
				},
				extra: {
					scatter: {
						activeType: 'hollow',
						pointShape: 'circle',
						pointSize: 10,
						activeBgColor: '#000000',
						activeBgOpacity: 0.15,
						activeRadius: 15
					},
					tooltip: {
						showBox: true,
						showArrow: true,
						showCategory: false,
						format: (item, category) => {
							if (!item || !item.data) return ''
							const data = item.data
							// 数据格式：[x, y, size, memberCount]
							const price = typeof data[0] === 'number' ? data[0] : parseFloat(data[0]) || 0
							const project = typeof data[1] === 'number' ? data[1] : parseFloat(data[1]) || 0
							const member = data.length > 3 ? (typeof data[3] === 'number' ? data[3] : parseFloat(data[3]) || 0) : 0
							return `客单价: ¥${ChartUtil.formatChartValue(price)}<br/>项目数: ${project.toFixed(2)}<br/>会员数: ${member}`
						}
					}
				}
			}
		}
	},
	computed: {
		selectedMonthText() {
			if (!this.selectedMonth) return '请选择月份'
			const date = new Date(this.selectedMonth)
			return `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(2, '0')}月`
		},
		// 热力图小时数组
		heatmapHours() {
			return Array.from({ length: 13 }, (_, i) => i + 9) // 9:00-21:00
		},
		// 热力图数据矩阵（预处理）
		heatmapMatrix() {
			if (!this.heatmapData || this.heatmapData.length === 0) {
				return Array(7).fill(null).map(() => Array(13).fill({ value: 0, color: '#f5f5f5', textColor: '#999' }))
			}
			const matrix = []
			const maxValue = Math.max(...this.heatmapData.map(d => d.CustomerFlow || 0), 1)
			for (let dayIndex = 0; dayIndex < 7; dayIndex++) {
				const row = []
				for (let hourIndex = 0; hourIndex < 13; hourIndex++) {
					const hour = hourIndex + 9
					const item = this.heatmapData.find(d => {
						// DayOfWeek: 0=周日, 1=周一, ..., 6=周六
						// 转换为数组索引: 0=周一, 1=周二, ..., 6=周日
						let day = d.DayOfWeek === 0 ? 6 : d.DayOfWeek - 1
						
						// 从 TimeSlot 中提取小时数（如 "18:00" -> 18）
						let dataHour = null
						if (d.Hour !== undefined && d.Hour !== null) {
							dataHour = d.Hour
						} else if (d.TimeSlot) {
							// 从 "18:00" 格式中提取小时
							const timeMatch = d.TimeSlot.match(/^(\d+):/)
							if (timeMatch) {
								dataHour = parseInt(timeMatch[1], 10)
							}
						}
						
						return day === dayIndex && dataHour === hour
					})
					if (item) {
						const value = item.CustomerFlow || 0
						const intensity = value / maxValue
						// 使用更明显的颜色渐变，增加更多级别
						let color = '#f5f5f5'
						let textColor = '#999'
						if (intensity > 0.8) {
							color = '#1e40af' // 深蓝色 - 最高
							textColor = '#fff'
						} else if (intensity > 0.6) {
							color = '#3b82f6' // 蓝色 - 高
							textColor = '#fff'
						} else if (intensity > 0.4) {
							color = '#60a5fa' // 浅蓝色 - 中高
							textColor = '#fff'
						} else if (intensity > 0.2) {
							color = '#93c5fd' // 更浅蓝色 - 中
							textColor = '#333'
						} else if (intensity > 0) {
							color = '#dbeafe' // 很浅蓝色 - 低
							textColor = '#666'
						}
						row.push({ value: value, color: color, textColor: textColor })
					} else {
						row.push({ value: 0, color: '#f5f5f5', textColor: '#999' })
					}
				}
				matrix.push(row)
			}
			return matrix
		},
		// 排名等级类名
		rankingClass() {
			if (this.comparison.totalStoreCount <= 0) return 'normal'
			const percentage = this.comparison.performanceRanking / this.comparison.totalStoreCount
			return percentage <= 0.2 ? 'excellent' : (percentage <= 0.5 ? 'good' : 'normal')
		},
		// 排名文本
		rankingText() {
			if (this.comparison.totalStoreCount <= 0) return '一般'
			const percentage = this.comparison.performanceRanking / this.comparison.totalStoreCount
			return percentage <= 0.2 ? '优秀' : (percentage <= 0.5 ? '良好' : '一般')
		},
		// 完成率数值
		completionRate() {
			if (!this.storeData || !this.storeData.Performance) return 0
			return this.storeData.Performance.CompletionRate || 0
		},
		// 完成率文本
		completionRateText() {
			return this.completionRate.toFixed(2)
		},
		// 完成率颜色
		gaugeColor() {
			const rate = this.completionRate
			return rate >= 100 ? '#67C23A' : rate >= 80 ? '#409EFF' : '#F56C6C'
		},
		// 核心KPI列表
		kpiList() {
			if (!this.storeData || !this.storeData.Performance) {
				return []
			}
			const perf = this.storeData.Performance
			return [
				{
					key: 'billing',
					label: '开单业绩',
					value: perf.BillingPerformance || 0,
					type: 'green',
					isMoney: true,
					icon: 'grid'
				},
				{
					key: 'consume',
					label: '消耗业绩',
					value: perf.ConsumePerformance || 0,
					type: 'light-blue',
					isMoney: true,
					icon: 'star'
				},
				{
					key: 'completion',
					label: '完成率',
					value: perf.CompletionRate || 0,
					type: 'purple',
					isPercent: true,
					icon: 'checkmark-circle'
				},
				{
					key: 'net',
					label: '净业绩',
					value: perf.NetPerformance || 0,
					type: 'orange',
					isMoney: true,
					icon: 'red-packet'
				},
				{
					key: 'billingCount',
					label: '开单次数',
					value: perf.BillingCount || 0,
					type: 'pink',
					icon: 'list'
				},
				{
					key: 'consumeCount',
					label: '消耗次数',
					value: perf.ConsumeCount || 0,
					type: 'red',
					icon: 'list'
				},
				{
					key: 'avgBilling',
					label: '平均开单',
					value: perf.AvgBillingAmount || 0,
					type: 'light-blue',
					isMoney: true,
					icon: 'list'
				}
			]
		},
		kpiListTop() {
			return this.kpiList.slice(0, 4)
		},
		kpiListBottom() {
			return this.kpiList.slice(4, 7)
		}
	},
	// 组件挂载时调用（作为组件使用时）
	mounted() {
		// this.init()
	},
	onPullDownRefresh() {
		this.loadDashboardData().finally(() => {
			uni.stopPullDownRefresh()
		})
	},
	onPageScroll(e) {
		this.pageScrollTop = e.scrollTop || 0
	},
	methods: {
		// 初始化方法（供父组件调用）
		init() {
			// 默认选择当前月份
			const now = new Date()
			this.selectedMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
			console.log('init', this.selectedMonth)
			this.loadStoreOptions()
		},
		// 月份选择变化
		onMonthChange(e) {
			this.selectedMonth = e.detail.value
			
			// 如果是管理角色，需要重新加载门店列表（因为接口参数包含月份）
			const userInfo = uni.getStorageSync('userInfo') || {}
			const roleId = userInfo.roleId || ''
			const roleIds = roleId ? roleId.split(',').map(id => id.trim()) : []
			const MANAGER_ROLE_IDS = ['781416469245199621', '781416598681421061']
			const isManager = roleIds.some(id => MANAGER_ROLE_IDS.includes(id))
			
			if (isManager) {
				// 重新加载管理门店列表
				const newuserInfo = uni.getStorageSync('newuserInfo') || {}
				this.loadManagedStores(newuserInfo)
			} else if (this.selectedStoreId) {
				// 其他角色，只重新加载数据
				this.loadDashboardData()
			}
		},
		// 门店选择变化
		onStoreChange(e) {
			this.storeIndex = e.detail.value
			const store = this.storeOptions[this.storeIndex]
			if (store) {
				this.selectedStoreId = store.id
				this.currentStoreName = store.fullName || store.dm || ''
				this.currentStoreCode = store.enCode || store.bm || ''
				this.currentStoreAddress = store.address || ''
				this.loadDashboardData()
			}
		},
		// 加载门店选项
		async loadStoreOptions() {
			try {
				const menuData = uni.getStorageSync('appMenuData') || []
				if (Array.isArray(menuData) && menuData.length > 0) {
					const rootNode = menuData.find(item => item.fullName == 'app门店数据开关按钮')
					// console.error(rootNode)
					if (rootNode) {
						// 如果有这个菜单项，直接获取所有门店
						await this.loadAllStores()
						return
					}
				}
				console.error('--------------------------')
				// 获取当前登录用户信息
				const userInfo = uni.getStorageSync('userInfo') || {}
				const newuserInfo = uni.getStorageSync('newuserInfo') || {}
				const roleId = newuserInfo.roleId || ''
				
				// 角色ID定义
				const MANAGER_ROLE_IDS = ['781416469245199621', '781416598681421061'] // 需要调用接口获取管理门店的角色
				const STORE_MANAGER_ROLE_IDS = [
					'781417228800099589', // 主管
					'781417320726660357', // 店长
					'781417422358840581', // 店助主任
					'781417515006821637', // 店助
					'781417581809501445'  // 主任
				]
				const TOP_MANAGER_ROLE_IDS = [
					'781400531129074949', // 董事长
					'781416313842042117'  // 总裁
				]
				
				// 解析角色ID（可能是逗号分隔的字符串）
				const roleIds = roleId ? roleId.split(',').map(id => id.trim()) : []
				
				// 判断用户角色类型
				const isManager = roleIds.some(id => MANAGER_ROLE_IDS.includes(id))
				const isStoreManager = roleIds.some(id => STORE_MANAGER_ROLE_IDS.includes(id))
				const isTopManager = roleIds.some(id => TOP_MANAGER_ROLE_IDS.includes(id))
		
				
				// 根据角色加载门店列表
				if (isTopManager) {
					// 角色是董事长或总裁，可以筛选所有门店
					console.error('董事长或总裁')
					await this.loadAllStores()
				} else if (isManager) {
					// 角色是 781416469245199621 或 781416598681421061，调用接口获取管理门店
					console.error('科总经理')
					await this.loadManagedStores(newuserInfo)
				} else if (isStoreManager) {
					// 角色是主管、店长、店助主任、店助、主任，默认获取自己的门店
					console.error('店长')
					await this.loadUserStore(newuserInfo)
				} else {
					// 其他角色，使用原有逻辑
					// await this.loadAllStores()
					await this.loadUserStore(newuserInfo)
				}
			} catch (error) {
				console.error('获取门店列表失败:', error)
				uni.showToast({
					title: '获取门店列表失败',
					icon: 'none'
				})
			}
		},
		
		// 加载管理门店（通过接口获取）
		async loadManagedStores(userInfo) {
			console.error('loadManagedStores')
			try {
				// 获取当前月份（格式：yyyyMM）
				const month = this.selectedMonth ? this.selectedMonth.replace('-', '') : 
					`${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}`
				
				// 获取用户的组织ID（从本地缓存的 userInfo 中获取）
				const localUserInfo = uni.getStorageSync('userInfo') || {}
				const organizeId = localUserInfo.organizeId || ''
				if (!organizeId) {
					console.warn('用户组织ID为空，无法获取管理门店')
					await this.loadAllStores()
					return
				}
				
				// 调用接口获取管理门店
				const res = await storeAPI.getManagedStores({
					month: month,
					organizationType: '事业部',
					departmentId: organizeId
				})
				
				if (res.code === 200 && res.data && Array.isArray(res.data)) {
					// 转换数据格式：从 [{ StoreId, StoreName }] 转换为 [{ id, fullName, dm }]
					this.storeOptions = res.data.map(store => ({
						id: store.StoreId,
						fullName: store.StoreName,
						dm: store.StoreName,
						enCode: '',
						bm: '',
						address: ''
					}))
					
					// 默认选中第一个门店
					if (this.storeOptions.length > 0) {
						this.selectStore(0)
					}
				} else {
					console.warn('获取管理门店失败，使用全部门店')
					await this.loadAllStores()
				}
			} catch (error) {
				console.error('获取管理门店失败:', error)
				// 失败时回退到加载全部门店
				await this.loadAllStores()
			}
		},
		
		// 加载用户自己的门店
		async loadUserStore(userInfo) {
			try {
				// 先获取全部门店列表
				const res = await storeAPI.getStoreSelector()
				if (res.code === 200 && res.data) {
					const allStores = res.data.list || []
					
					// 获取用户的门店信息（从本地存储获取 newuserInfo）
					const newuserInfo = uni.getStorageSync('newuserInfo') || {}
					const userStoreId = userInfo.mdid || newuserInfo.mdid
					const userStoreName = userInfo.mdmc || newuserInfo.mdmc || ''
					
					if (userStoreId || userStoreName) {
						// 在门店列表中查找匹配的门店
						const matchedStore = allStores.find(store => {
							if (userStoreId && store.id === userStoreId) {
								return true
							}
							if (userStoreName) {
								const storeName = store.fullName || store.dm || ''
								return storeName === userStoreName || storeName.includes(userStoreName) || userStoreName.includes(storeName)
							}
							return false
						})
						
						if (matchedStore) {
							// 只显示用户自己的门店
							this.storeOptions = [matchedStore]
							this.selectStore(0)
							return
						}
					}
					
					// 如果没有找到用户门店，使用全部门店
					this.storeOptions = allStores
					if (this.storeOptions.length === 1) {
						this.selectStore(0)
					}
				}
			} catch (error) {
				console.error('加载用户门店失败:', error)
				await this.loadAllStores()
			}
		},
		
		// 加载全部门店
		async loadAllStores() {
		
			try {
				const res = await storeAPI.getStoreSelector()
				if (res.code === 200 && res.data) {
					this.storeOptions = res.data.list || []
					// 获取当前登录用户信息
					const newuserInfo = uni.getStorageSync('newuserInfo') || {}
					if (newuserInfo && this.storeOptions.length > 0) {
						// 使用 newuserInfo 中的门店信息
						const userStoreId = newuserInfo.mdid
						const userStoreName = newuserInfo.mdmc || ''
						
						if (userStoreId || userStoreName) {
							// 在门店列表中查找匹配的门店（优先通过ID匹配，其次通过名称匹配）
							const matchedStoreIndex = this.storeOptions.findIndex(store => {
								if (userStoreId && store.id === userStoreId) {
									return true
								}
								if (userStoreName) {
									const storeName = store.fullName || store.dm || ''
									return storeName === userStoreName || storeName.includes(userStoreName) || userStoreName.includes(storeName)
								}
								return false
							})
							
							if (matchedStoreIndex >= 0) {
								// 找到匹配的门店，默认选中
								this.selectStore(matchedStoreIndex)
								console.log('找到匹配的门店', matchedStoreIndex)
								return
							} else {
								this.selectStore(0)
								console.log('没有找到匹配的门店')
							}
						} else {
							this.selectStore(0)
							console.log('没有找到匹配的门店')
						}
					}
					
					// 如果没有找到用户门店或只有一个门店，默认选中第一个
					if (this.storeOptions.length === 1) {
						this.selectStore(0)
					}
				}
			} catch (error) {
				console.error('获取门店列表失败:', error)
				uni.showToast({
					title: '获取门店列表失败',
					icon: 'none'
				})
			}
		},
		
		// 选中门店（统一方法）
		selectStore(index) {
			if (index >= 0 && index < this.storeOptions.length) {
				this.storeIndex = index
				const store = this.storeOptions[index]
				this.selectedStoreId = store.id
				this.currentStoreName = store.fullName || store.dm || ''
				this.currentStoreCode = store.enCode || store.bm || ''
				this.currentStoreAddress = store.address || ''
				this.loadDashboardData()
			}
		},
		// 加载驾驶舱数据
		async loadDashboardData() {
			if (!this.selectedStoreId || !this.selectedMonth) {
				return
			}

			this.loading = true
			try {
				// 将月份格式从 yyyy-MM 转换为 yyyyMM
				const statisticsMonth = this.selectedMonth.replace('-', '')

				// 并行加载所有数据
				const [
					statisticsRes,
					trendRes,
					itemRes,
					memberRes,
					coachRes,
					comparisonRes,
					categoryMonthlyRes,
					funnelRes,
					scatterRes,
					heatmapRes
				] = await Promise.all([
					storeDashboardAPI.getStoreDashboardStatistics({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					}),
					storeDashboardAPI.getStoreMonthlyTrend({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					}),
					storeDashboardAPI.getStoreItemAnalysis({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					}),
					storeDashboardAPI.getStoreMemberAnalysis({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					}),
					storeDashboardAPI.getStoreHealthCoachAnalysis({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					}),
					storeDashboardAPI.getStoreComparisonAnalysis({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					}),
					storeDashboardAPI.getCategoryMonthlyPerformance({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					}),
					storeDashboardAPI.getMemberConversionFunnel({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					}),
					storeDashboardAPI.getCustomerPriceProjectRelation({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					}),
					storeDashboardAPI.getWeeklyHeatmap({
						storeId: this.selectedStoreId,
						statisticsMonth: statisticsMonth
					})
				])

				// 处理统计数据
				if (statisticsRes.code === 200 && statisticsRes.data) {
					this.storeData = {
						Performance: {
							BillingPerformance: statisticsRes.data.BillingPerformance || 0,
							ConsumePerformance: statisticsRes.data.ConsumePerformance || 0,
							CompletionRate: statisticsRes.data.CompletionRate || 0,
							NetPerformance: statisticsRes.data.NetPerformance || 0,
							BillingCount: statisticsRes.data.BillingCount || 0,
							ConsumeCount: statisticsRes.data.ConsumeCount || 0,
							AvgBillingAmount: statisticsRes.data.AvgBillingAmount || 0,
							AvgConsumeAmount: statisticsRes.data.AvgConsumeAmount || 0,
							RefundAmount: statisticsRes.data.RefundAmount || 0,
							RefundCount: statisticsRes.data.RefundCount || 0,
							RemainingRightsAmount: statisticsRes.data.RemainingRightsAmount || 0,
							TargetPerformance: statisticsRes.data.TargetPerformance || 0
						},
						Operation: {
							HeadCount: statisticsRes.data.HeadCount || 0,
							PersonCount: statisticsRes.data.PersonCount || 0,
							ProjectCount: statisticsRes.data.ProjectCount || 0,
							AvgAmountPerPerson: statisticsRes.data.AvgAmountPerPerson || 0,
							AvgAmountPerProject: statisticsRes.data.AvgAmountPerProject || 0,
							AvgProjectPerHead: statisticsRes.data.AvgProjectPerHead || 0
						}
					}
					// 更新显示数据
					this.updateDisplayData()
				}

				// 处理趋势数据
				if (trendRes.code === 200 && trendRes.data && trendRes.data.length > 0) {
					this.monthlyTrendData = trendRes.data
					this.$nextTick(() => {
						this.drawTrendChart()
						this.drawCompareChart()
					})
				}

				// 处理品项分析数据
				if (itemRes.code === 200 && itemRes.data) {
					if (itemRes.data.CategoryRatios) {
						this.categoryData = itemRes.data.CategoryRatios
						this.$nextTick(() => {
							this.drawCategoryChart()
						})
					}
					if (itemRes.data.TopBillingItems) {
						this.topBillingItems = itemRes.data.TopBillingItems.map(item => ({
							itemName: item.ItemName || '未知品项',
							billingAmount: item.BillingAmount || 0,
							billingCount: item.BillingCount || 0,
							category: item.Category || '其他'
						}))
					}
					if (itemRes.data.TopConsumeItems) {
						this.topConsumeItems = itemRes.data.TopConsumeItems.map(item => ({
							itemName: item.ItemName || '未知品项',
							consumeAmount: item.ConsumeAmount || 0,
							category: item.Category || '其他'
						}))
					}
				}

				// 处理健康师排行数据
				if (coachRes.code === 200 && coachRes.data && coachRes.data.length > 0) {
					this.healthCoachRanking = coachRes.data.map(item => ({
						name: item.HealthCoachName || '未知',
						billingPerformance: item.BillingPerformance || 0,
						consumePerformance: item.ConsumePerformance || 0,
						totalPerformance: item.NetPerformance || 0
					}))
				}

				// 处理排名对比数据
				if (comparisonRes.code === 200 && comparisonRes.data) {
					this.comparison = {
						performanceRanking: comparisonRes.data.PerformanceRanking || 0,
						totalStoreCount: comparisonRes.data.TotalStoreCount || 0,
						avgPerformanceSameType: comparisonRes.data.AvgPerformanceSameType || 0,
						sameTypeStoreCount: comparisonRes.data.SameTypeStoreCount || 0,
						avgPerformanceSameOrg: comparisonRes.data.AvgPerformanceSameOrg || 0,
						sameOrgStoreCount: comparisonRes.data.SameOrgStoreCount || 0
					}
				}

				// 处理各分类月度业绩数据
				if (categoryMonthlyRes.code === 200 && categoryMonthlyRes.data && categoryMonthlyRes.data.length > 0) {
					this.categoryMonthlyData = categoryMonthlyRes.data
					this.$nextTick(() => {
						this.drawStackedChart()
					})
				}

				// 处理转化漏斗数据
				if (funnelRes.code === 200 && funnelRes.data) {
					this.funnelData = {
						ExpansionCount: funnelRes.data.ExpansionCount || 0,
						InviteCount: funnelRes.data.InviteCount || 0,
						AppointmentCount: funnelRes.data.AppointmentCount || 0,
						BillingCount: funnelRes.data.BillingCount || 0
					}
					this.$nextTick(() => {
						this.drawFunnelChart()
					})
				}

				// 处理客单价与项目数关系数据
				if (scatterRes.code === 200 && scatterRes.data && scatterRes.data.length > 0) {
					this.scatterData = scatterRes.data
					this.$nextTick(() => {
						this.drawScatterChart()
					})
				}

				// 处理热力图数据
				if (heatmapRes.code === 200 && heatmapRes.data && heatmapRes.data.length > 0) {
					this.heatmapData = heatmapRes.data
				}

				// 处理会员分析数据
				if (memberRes.code === 200 && memberRes.data) {
					this.memberAnalysisData = memberRes.data
					this.updateMemberList(memberRes.data)
				} else {
					this.memberAnalysisData = null
					this.updateMemberList(null)
				}

				// 数据加载完成后，更新快速数据洞察、本月关键指标、本月经营提示
				this.updateDataInsights()
				this.updateKeyMetrics()
				this.updateOperationTips()

			} catch (error) {
				console.error('加载数据失败:', error)
				uni.showToast({
					title: '加载数据失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		// 绘制趋势图表
		drawTrendChart() {
			if (!this.monthlyTrendData || this.monthlyTrendData.length === 0) {
				this.trendChartData = {}
				return
			}
			
			// 使用全部数据
			const months = this.monthlyTrendData.map(item => {
				const month = item.Month || ''
				if (month.length === 6) {
					return month.substring(0, 4) + '-' + month.substring(4, 6)
				}
				return month
			})
			
			const series = [
				{
					name: '开单业绩',
					data: this.monthlyTrendData.map(item => item.BillingPerformance || 0)
				},
				{
					name: '消耗业绩',
					data: this.monthlyTrendData.map(item => item.ConsumePerformance || 0)
				},
				{
					name: '净业绩',
					data: this.monthlyTrendData.map(item => item.NetPerformance || 0)
				}
			]
			
			// 更新图表数据
			this.trendChartData = {
				categories: months,
				series: series
			}
		},
		// 绘制对比图表
		drawCompareChart() {
			if (!this.monthlyTrendData || this.monthlyTrendData.length === 0) {
				this.compareChartData = {}
				return
			}
			
			// 使用全部数据
			const months = this.monthlyTrendData.map(item => {
				const month = item.Month || ''
				if (month.length === 6) {
					const monthNum = parseInt(month.substring(4, 6))
					return monthNum + '月'
				}
				return month
			})
			
			const series = [
				{
					name: '开单业绩',
					data: this.monthlyTrendData.map(item => parseFloat(((item.BillingPerformance || 0) / 10000).toFixed(2)))
				},
				{
					name: '消耗业绩',
					data: this.monthlyTrendData.map(item => parseFloat(((item.ConsumePerformance || 0) / 10000).toFixed(2)))
				}
			]
			
			// 更新图表数据
			this.compareChartData = {
				categories: months,
				series: series
			}
		},
		// 绘制分类占比图表
		drawCategoryChart() {
			if (!this.categoryData || this.categoryData.length === 0) {
				this.categoryChartData = {}
				return
			}
			
			const data = this.categoryData.map(item => {
				const categoryName = item.CategoryName || '其他'
				const color = categoryName === '生美' ? '#A8D5E2' : categoryName === '医美' ? '#B8E6B8' : categoryName === '科美' ? '#FFD4A3' : categoryName === '产品' ? '#E6C1E6' : categoryName === '教育' ? '#F5DEB3' : '#DDA0DD'
				return {
					name: categoryName,
					value: item.ConsumeAmount || 0,
					color: color
				}
			})
			
			// 更新图表数据
			this.categoryChartData = {
				series: [{
					data: data
				}]
			}
		},
		// 绘制堆叠图表
		drawStackedChart() {
			if (!this.categoryMonthlyData || this.categoryMonthlyData.length === 0) {
				this.stackedChartData = {}
				return
			}
			
			// 使用全部数据
			const months = this.categoryMonthlyData.map(item => {
				const month = item.Month || ''
				if (month.length === 6) {
					const monthNum = parseInt(month.substring(4, 6))
					return monthNum + '月'
				}
				return month
			})
			
			const series = [
				{
					name: '生美',
					data: this.categoryMonthlyData.map(item => parseFloat(((item.BeautyPerformance || 0) / 10000).toFixed(2)))
				},
				{
					name: '医美',
					data: this.categoryMonthlyData.map(item => parseFloat(((item.MedicalPerformance || 0) / 10000).toFixed(2)))
				},
				{
					name: '科美',
					data: this.categoryMonthlyData.map(item => parseFloat(((item.TechPerformance || 0) / 10000).toFixed(2)))
				},
				{
					name: '产品',
					data: this.categoryMonthlyData.map(item => parseFloat(((item.ProductPerformance || 0) / 10000).toFixed(2)))
				}
			]
			
			// 更新图表数据
			this.stackedChartData = {
				categories: months,
				series: series
			}
		},
		// 绘制漏斗图
		drawFunnelChart() {
			if (!this.funnelData) {
				this.funnelChartData = {}
				return
			}
			
			const funnelData = [
				{ value: this.funnelData.ExpansionCount || 0, name: '拓客', color: '#409EFF' },
				{ value: this.funnelData.InviteCount || 0, name: '邀约', color: '#67C23A' },
				{ value: this.funnelData.AppointmentCount || 0, name: '预约', color: '#E6A23C' },
				{ value: this.funnelData.BillingCount || 0, name: '开单', color: '#909399' }
			]
			
			// 更新图表数据
			this.funnelChartData = {
				series: [{
					data: funnelData.map(item => ({
						name: item.name,
						value: item.value,
						color: item.color
					}))
				}]
			}
		},
		// 绘制散点图
		drawScatterChart() {
			if (!this.scatterData || this.scatterData.length === 0) {
				this.scatterChartData = {}
				return
			}
			
			// 计算最大会员数，用于动态调整点的大小
			const maxMemberCount = Math.max(...this.scatterData.map(d => d.MemberCount || 0), 1)
			
			// uCharts散点图数据格式：可以是数组 [x, y, size] 或对象 {x, y, value}
			// 为了tooltip能正确显示，我们使用数组格式，并在第4个位置保存会员数
			const scatterSeries = [{
				name: '会员分布',
				data: this.scatterData.map((item) => {
					const memberCount = item.MemberCount || 0
					const price = item.AvgAmountPerPerson || 0
					const project = item.AvgProjectPerPerson || 0
					// 根据会员数计算点的大小，范围在 10-30 之间
					const pointSize = memberCount > 0 
						? Math.min(30, Math.max(10, 10 + (memberCount / maxMemberCount) * 20))
						: 10
					// 返回数组格式：[x, y, size, memberCount]
					// uCharts会使用前3个值，第4个值用于tooltip
					return [price, project, pointSize, memberCount]
				})
			}]
			
			// 更新图表数据
			this.scatterChartData = {
				series: scatterSeries
			}
		},
		// 获取KPI图标名称
		getKpiIconName(key) {
			const iconMap = {
				billing: 'grid',
				consume: 'star',
				completion: 'checkmark-circle',
				net: 'red-packet',
				billingCount: 'list',
				consumeCount: 'list',
				avgBilling: 'coin'
			}
			return iconMap[key] || 'chart'
		},
		// 格式化数字（默认保留两位小数，超过万显示为万单位）
		formatNumber(num, decimals = 2) {
			if (num === null || num === undefined) return '0.00'
			if (typeof num === 'string') num = parseFloat(num)
			if (isNaN(num)) return '0.00'
			if (num >= 10000) {
				return (num / 10000).toFixed(decimals) + '万'
			}
			return num.toFixed(decimals)
		},
		// 格式化金额
		formatMoney(amount) {
			if (amount === null || amount === undefined) return '0.00'
			if (typeof amount === 'string') amount = parseFloat(amount)
			if (isNaN(amount)) return '0.00'
			if (amount >= 10000) {
				return (amount / 10000).toFixed(2) + '万'
			}
			return amount.toFixed(2)
		},
		// 更新显示数据
		updateDisplayData() {
			if (!this.storeData || !this.storeData.Performance || !this.storeData.Operation) {
				this.updatePerformanceList(null)
				this.updateOperationList(null)
				return
			}
			const perf = this.storeData.Performance
			const oper = this.storeData.Operation
			this.updatePerformanceList(perf)
			this.updateOperationList(oper)
		},
		// 更新业绩概览列表
		updatePerformanceList(perf) {
			if (!perf) {
				this.performanceList = [
					{ label: '开单次数', value: '0' },
					{ label: '消耗次数', value: '0' },
					{ label: '退卡次数', value: '0' },
					{ label: '平均开单金额', value: '￥0' },
					{ label: '平均消耗金额', value: '￥0' },
					{ label: '剩余权益', value: '￥0' },
					{ label: '目标业绩', value: '￥0' },
					{ label: '退卡金额', value: '￥0' }
				]
				return
			}
			this.performanceList = [
				{ label: '开单次数', value: this.formatNumber(perf.BillingCount) },
				{ label: '消耗次数', value: this.formatNumber(perf.ConsumeCount) },
				{ label: '退卡次数', value: this.formatNumber(perf.RefundCount) },
				{ label: '平均开单金额', value: '￥' + this.formatMoney(perf.AvgBillingAmount) },
				{ label: '平均消耗金额', value: '￥' + this.formatMoney(perf.AvgConsumeAmount) },
				{ label: '剩余权益', value: '￥' + this.formatMoney(perf.RemainingRightsAmount) },
				{ label: '目标业绩', value: '￥' + this.formatMoney(perf.TargetPerformance) },
				{ label: '退卡金额', value: '￥' + this.formatMoney(perf.RefundAmount) }
			]
		},
		// 更新运营指标列表
		updateOperationList(oper) {
			if (!oper) {
				this.operationList = [
					{ label: '人头数', value: '0' },
					{ label: '人次', value: '0' },
					{ label: '项目数', value: '0' },
					{ label: '客单价', value: '￥0' },
					{ label: '项目单价', value: '￥0' },
					{ label: '人均项目数', value: '0' }
				]
				return
			}
			this.operationList = [
				{ label: '人头数', value: this.formatNumber(oper.HeadCount) },
				{ label: '人次', value: this.formatNumber(oper.PersonCount) },
				{ label: '项目数', value: this.formatNumber(oper.ProjectCount) },
				{ label: '客单价', value: '￥' + this.formatMoney(oper.AvgAmountPerPerson) },
				{ label: '项目单价', value: '￥' + this.formatMoney(oper.AvgAmountPerProject) },
				{ label: '人均项目数', value: this.formatNumber(oper.AvgProjectPerHead, 2) }
			]
		},
		// 更新会员分析列表
		updateMemberList(memberData) {
			if (!memberData) {
				this.memberList = [
					{ label: '总会员数', value: '0', rate: '' },
					{ label: '本月新增', value: '0', rate: '' },
					{ label: '活跃会员', value: '0', rate: '0%' },
					{ label: '沉睡会员', value: '0', rate: '0%' },
					{ label: '生美会员', value: '0', rate: '' },
					{ label: '医美会员', value: '0', rate: '' },
					{ label: '科美会员', value: '0', rate: '' },
					{ label: '教育会员', value: '0', rate: '' }
				]
				return
			}
			const totalMembers = memberData.TotalMembers || 0
			const activeRate = memberData.ActiveMemberRate || 0
			const sleepRate = memberData.SleepMemberRate || 0
			this.memberList = [
				{ label: '总会员数', value: this.formatNumber(totalMembers), rate: '' },
				{ label: '本月新增', value: this.formatNumber(memberData.NewMembersThisMonth || 0), rate: '' },
				{ label: '活跃会员', value: this.formatNumber(memberData.ActiveMembers || 0), rate: activeRate.toFixed(1) + '%' },
				{ label: '沉睡会员', value: this.formatNumber(memberData.SleepMembers || 0), rate: sleepRate.toFixed(1) + '%' },
				{ label: '生美会员', value: this.formatNumber(memberData.BeautyMembers || 0), rate: '' },
				{ label: '医美会员', value: this.formatNumber(memberData.MedicalMembers || 0), rate: '' },
				{ label: '科美会员', value: this.formatNumber(memberData.TechMembers || 0), rate: '' },
				{ label: '教育会员', value: this.formatNumber(memberData.EducationMembers || 0), rate: '' }
			]
		},
		// 更新快速数据洞察
		updateDataInsights() {
			if (!this.storeData || !this.storeData.Operation || !this.heatmapData || this.heatmapData.length === 0) {
				this.dataInsights = [
					{ title: '最佳营业时段', tag: '暂无', value: '暂无数据', desc: '暂无数据' },
					{ title: '高价值会员', tag: '暂无', value: '0人', desc: '暂无数据' },
					{ title: '项目转化率', tag: '暂无', value: '0%', desc: '暂无数据' },
					{ title: '复购周期', tag: '暂无', value: '暂无', desc: '暂无数据' }
				]
				return
			}
			const oper = this.storeData.Operation || {}
			let bestHour = 0
			let maxPersonCount = 0
			this.heatmapData.forEach(item => {
				if ((item.CustomerFlow || 0) > maxPersonCount) {
					maxPersonCount = item.CustomerFlow || 0
					bestHour = item.Hour || 0
				}
			})
			const bestTimeRange = bestHour >= 0 && maxPersonCount > 0
				? `${String(bestHour).padStart(2, '0')}:00-${String(bestHour + 1).padStart(2, '0')}:00`
				: '暂无数据'
			const highValueMemberCount = oper.AvgAmountPerPerson > 1000
				? Math.round(oper.HeadCount * 0.3)
				: 0
			const conversionRate = this.funnelData && this.funnelData.ExpansionCount > 0
				? ((this.funnelData.BillingCount / this.funnelData.ExpansionCount) * 100).toFixed(1)
				: '0.0'
			const avgProjectPerHead = oper.AvgProjectPerHead || 0
			const repurchaseCycle = avgProjectPerHead > 0
				? Math.round(30 / avgProjectPerHead) + '天'
				: '暂无'
			this.dataInsights = [
				{ title: '最佳营业时段', tag: maxPersonCount > 0 ? '热门' : '暂无', value: bestTimeRange, desc: maxPersonCount > 0 ? `此时段客流量最高(${this.formatNumber(maxPersonCount, 0)}人次)` : '暂无数据' },
				{ title: '高价值会员', tag: highValueMemberCount > 0 ? '重点' : '暂无', value: highValueMemberCount > 0 ? `${this.formatNumber(highValueMemberCount, 0)}人` : '0人', desc: highValueMemberCount > 0 ? `单次消费超过¥1000` : '暂无数据' },
				{ title: '项目转化率', tag: parseFloat(conversionRate) > 50 ? '优秀' : parseFloat(conversionRate) > 30 ? '良好' : '待提升', value: conversionRate + '%', desc: `拓客转化为开单的比例` },
				{ title: '复购周期', tag: repurchaseCycle !== '暂无' ? '正常' : '暂无', value: repurchaseCycle, desc: repurchaseCycle !== '暂无' ? `会员平均复购间隔` : '暂无数据' }
			]
		},
		// 更新本月关键指标
		updateKeyMetrics() {
			if (!this.storeData || !this.storeData.Performance) {
				this.keyMetrics = [
					{ label: '目标完成度', value: 0, color: '#67C23A' },
					{ label: '会员活跃度', value: 0, color: '#409EFF' },
					{ label: '项目满意度', value: 0, color: '#E6A23C' },
					{ label: '员工效率', value: 0, color: '#F56C6C' }
				]
				return
			}
			const perf = this.storeData.Performance
			const oper = this.storeData.Operation || {}
			const completionRate = perf.TargetPerformance > 0
				? Math.min(100, parseFloat((perf.ConsumePerformance / perf.TargetPerformance * 100).toFixed(1)))
				: 0
			const activeMember = this.memberList && this.memberList.length > 0
				? this.memberList.find(m => m.label === '活跃会员')
				: null
			const activeMemberRate = activeMember && activeMember.rate
				? parseFloat(activeMember.rate)
				: 0
			const refundRate = perf.BillingPerformance > 0
				? (perf.RefundAmount / perf.BillingPerformance * 100)
				: 0
			const satisfactionRate = Math.max(0, Math.min(100, parseFloat((100 - refundRate * 10).toFixed(1))))
			const avgProjectPerHead = oper.AvgProjectPerHead || 0
			const efficiencyRate = Math.min(100, parseFloat((avgProjectPerHead * 10).toFixed(1)))
			this.keyMetrics = [
				{ label: '目标完成度', value: completionRate, color: completionRate >= 100 ? '#67C23A' : completionRate >= 80 ? '#E6A23C' : '#F56C6C' },
				{ label: '会员活跃度', value: activeMemberRate, color: activeMemberRate >= 60 ? '#67C23A' : activeMemberRate >= 40 ? '#409EFF' : '#909399' },
				{ label: '项目满意度', value: satisfactionRate, color: satisfactionRate >= 90 ? '#67C23A' : satisfactionRate >= 70 ? '#E6A23C' : '#F56C6C' },
				{ label: '员工效率', value: efficiencyRate, color: efficiencyRate >= 80 ? '#67C23A' : efficiencyRate >= 60 ? '#409EFF' : '#F56C6C' }
			]
		},
		// 更新本月经营提示
		updateOperationTips() {
			if (!this.storeData || !this.storeData.Performance) {
				this.operationTips = []
				return
			}
			const perf = this.storeData.Performance
			const oper = this.storeData.Operation || {}
			const tips = []
			const completionRate = perf.TargetPerformance > 0
				? (perf.ConsumePerformance / perf.TargetPerformance * 100)
				: 0
			if (completionRate >= 100) {
				tips.push({ type: 'success', text: `本月业绩完成度${completionRate.toFixed(1)}%,超额完成目标` })
			} else if (completionRate >= 80) {
				tips.push({ type: 'success', text: `本月业绩完成度${completionRate.toFixed(1)}%,保持当前节奏` })
			} else if (completionRate >= 60) {
				tips.push({ type: 'warning', text: `本月业绩完成度${completionRate.toFixed(1)}%,需加快进度` })
			} else {
				tips.push({ type: 'danger', text: `本月业绩完成度${completionRate.toFixed(1)}%,严重滞后` })
			}
			const sleepMember = this.memberList && this.memberList.length > 0
				? this.memberList.find(m => m.label === '沉睡会员')
				: null
			if (sleepMember && parseFloat(sleepMember.rate || '0') > 20) {
				tips.push({ type: 'warning', text: `沉睡会员占比${sleepMember.rate},建议加强会员唤醒` })
			}
			if (oper.AvgAmountPerPerson > 0) {
				const avgPrice = oper.AvgAmountPerPerson
				if (avgPrice < 300) {
					tips.push({ type: 'info', text: `客单价${this.formatMoney(avgPrice)},可通过项目组合提升` })
				} else if (avgPrice > 800) {
					tips.push({ type: 'success', text: `客单价${this.formatMoney(avgPrice)},表现优秀` })
				}
			}
			if (perf.RefundAmount > 0 && perf.BillingPerformance > 0) {
				const refundRate = (perf.RefundAmount / perf.BillingPerformance * 100)
				if (refundRate > 5) {
					tips.push({ type: 'warning', text: `退卡金额${this.formatMoney(perf.RefundAmount)},退卡率${refundRate.toFixed(1)}%` })
				}
			}
			if (tips.length < 4 && oper.HeadCount > 0) {
				tips.push({ type: 'info', text: `本月服务${this.formatNumber(oper.HeadCount, 0)}位会员,${this.formatNumber(oper.PersonCount, 0)}人次` })
			}
			this.operationTips = tips.slice(0, 4)
		},
		// 保存截图
		async saveScreenshot() {
			// 隐藏截图按钮
			this.showScreenshotBtn = false
			// 显示加载提示
			uni.showLoading({
				title: '截图中'
			})
			this.screenshotLoading = true
			try {
				// #ifdef H5
				await this.saveScreenshotH5()
				// #endif
				
				// #ifdef MP-WEIXIN
				await this.saveScreenshotMiniProgram()
				// #endif
				
				// #ifndef H5 || MP-WEIXIN
				await this.saveScreenshotFallback()
				// #endif
			} catch (error) {
				console.error('截图生成失败:', error)
				uni.showToast({
					title: '截图生成失败: ' + (error.message || '未知错误'),
					icon: 'none',
					duration: 3000
				})
			} finally {
				this.screenshotLoading = false
				// 隐藏加载提示
				uni.hideLoading()
				// 恢复显示截图按钮
				this.showScreenshotBtn = true
			}
		},
		// H5平台截图
		async saveScreenshotH5() {
			try {
				const html2canvas = await import('html2canvas')
				let element = document.querySelector('.warpbox')
				if (!element) element = document.querySelector('.page')
				if (!element) throw new Error('未找到要截图的内容')
				
				await new Promise(resolve => setTimeout(resolve, 1000))
				window.scrollTo(0, 0)
				await new Promise(resolve => setTimeout(resolve, 500))
				
				const originalBg = element.style.background
				element.style.background = '#ffffff'
				await new Promise(resolve => setTimeout(resolve, 200))
				
				const options = {
					allowTaint: true,
					useCORS: true,
					scale: 2.0,
					backgroundColor: '#ffffff',
					logging: false,
					imageTimeout: 30000,
					scrollX: 0,
					scrollY: 0,
					onclone: function(clonedDoc) {
						clonedDoc.body.style.backgroundColor = '#ffffff'
						clonedDoc.documentElement.style.backgroundColor = '#ffffff'
					}
				}
				
				let canvas
				try {
					canvas = await html2canvas.default(element, options)
				} catch (firstError) {
					console.warn('第一次截图失败，尝试备选方案:', firstError)
					canvas = await html2canvas.default(element, {
						allowTaint: true,
						useCORS: true,
						scale: 2.0,
						backgroundColor: '#ffffff',
						logging: false,
						imageTimeout: 30000
					})
				}
				
				const dataUrl = canvas.toDataURL('image/png', 1.0)
				const link = document.createElement('a')
				const fileName = `门店数据_${this.currentStoreName || '未选择'}_${this.selectedMonth}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.png`
				link.download = fileName
				link.href = dataUrl
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
				element.style.background = originalBg
				
				uni.showToast({
					title: '截图保存成功',
					icon: 'success',
					duration: 2000
				})
			} catch (error) {
				console.error('H5截图失败:', error)
				throw error
			}
		},
		// 微信小程序截图
		async saveScreenshotMiniProgram() {
			try {
				uni.canvasToTempFilePath({
					canvasId: 'screenshot-canvas',
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '截图已保存到相册',
									icon: 'success',
									duration: 2000
								})
							},
							fail: (err) => {
								console.error('保存到相册失败:', err)
								uni.previewImage({
									urls: [res.tempFilePath],
									current: res.tempFilePath
								})
							}
						})
					},
					fail: (err) => {
						console.error('导出图片失败:', err)
						throw new Error('导出图片失败')
					}
				}, this)
			} catch (error) {
				console.error('小程序截图失败:', error)
				throw error
			}
		},
		// 兜底截图方案
		async saveScreenshotFallback() {
			await new Promise(resolve => setTimeout(resolve, 2000))
			uni.showToast({
				title: '截图功能暂不支持当前平台',
				icon: 'none',
				duration: 2000
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
	background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
	padding-bottom: 40rpx;
	font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Helvetica Neue", Arial, sans-serif;
}

.warpbox {
	padding: 0 30rpx;
	padding-top: 20rpx;
}

/* 顶部区域 */
.header-section {
	margin-bottom: 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 10rpx;
	
	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #1f2937;
	}
	
	.filter-box {
		display: flex;
		align-items: center;
		gap: 12rpx;
		
		.date-picker-trigger,
		.store-picker-trigger {
			display: flex;
			align-items: center;
			background: rgba(255, 255, 255, 0.6);
			backdrop-filter: blur(10px);
			padding: 8rpx 16rpx;
			border-radius: 30rpx;
			border: 1px solid rgba(255, 255, 255, 0.8);
			
			.date-text,
			.store-text {
				font-size: 24rpx;
				color: #333;
				margin-right: 6rpx;
			}
		}
		
		.screenshot-btn {
			display: flex;
			align-items: center;
			gap: 8rpx;
			padding: 8rpx 16rpx;
			background: rgba(64, 158, 255, 0.1);
			border-radius: 20rpx;
			transition: all 0.3s;
			
			&:active {
				background: rgba(64, 158, 255, 0.2);
				transform: scale(0.95);
			}
			
			&.loading {
				opacity: 0.6;
			}
			
			.screenshot-text {
				font-size: 24rpx;
				color: #409EFF;
			}
		}
	}
}

/* 卡片容器通用样式 */
.warpboxss {
	background: rgba(255, 255, 255, 0.8);
	backdrop-filter: blur(20px) saturate(180%);
	-webkit-backdrop-filter: blur(20px) saturate(180%);
	padding: 20rpx;
	border-radius: 20rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08), 0 0 0 1px rgba(255, 255, 255, 0.8) inset;
	margin-bottom: 20rpx;
	transition: all 0.3s ease;
	
	&:active {
		transform: scale(0.99);
	}
}

.warpboxs-small-title {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 28rpx;
	font-weight: 600;
	color: #1f2937;
	margin-bottom: 16rpx;
	
	view:first-child {
		display: flex;
		align-items: center;
	}

	.warpboxs-small-title-line {
		background: linear-gradient(180deg, #43a047 0%, #66bb6a 100%);
		height: 26rpx;
		width: 10rpx;
		margin-right: 12rpx;
		border-radius: 18rpx;
		box-shadow:
			0 2rpx 8rpx rgba(67, 160, 71, 0.4),
			0 0 12rpx rgba(67, 160, 71, 0.3),
			inset 0 1rpx 2rpx rgba(255, 255, 255, 0.3);
	}
}

/* 门店信息卡片 */
.store-info-section {
	.store-info-card {
		display: flex;
		align-items: center;
		gap: 20rpx;
		
		.store-avatar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 20rpx;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.store-details {
			flex: 1;
			
			.store-name {
				font-size: 32rpx;
				font-weight: 600;
				color: #303133;
				margin-bottom: 8rpx;
			}
			
			.store-meta {
				display: flex;
				flex-direction: column;
				gap: 4rpx;
				font-size: 24rpx;
				color: #606266;
			}
		}
	}
}

/* KPI 核心指标 */
.kpi-section {
	margin-bottom: 20rpx;
}

.billing-card {
	width: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
	padding: 24rpx;
	background: rgba(255, 255, 255, 0.7);
	backdrop-filter: blur(20px) saturate(180%);
	-webkit-backdrop-filter: blur(20px) saturate(180%);
	border-radius: 24rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08), 0 0 0 1px rgba(255, 255, 255, 0.8) inset;
	margin-bottom: 16rpx;
	box-sizing: border-box;
}

.billing-main {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	justify-content: center;
	flex: 1;
	width: 100%;
	padding: 0 8rpx;
	margin-bottom: 30rpx;
}

.billing-card .stat-content {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	width: 100%;
	gap: 10rpx;
}

.billing-card .label-row {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	width: 100%;
	gap: 8rpx;
}

.billing-card .card-label {
	font-size: 24rpx;
	font-weight: 500;
	color: #666;
}

.billing-card .stat-icon-small {
	width: 48rpx;
	height: 48rpx;
	border-radius: 12rpx;
	margin-right: 8rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
	
	&.green { background: #4caf50; }
	&.red { background: #f44336; }
	&.light-blue { background: #42a5f5; }
	&.purple { background: #9c27b0; }
	&.orange { background: #ff9800; }
	&.pink { background: #e91e63; }
}

.billing-value {
	font-size: 38rpx;
	font-weight: bold;
	color: #1f2937;
	line-height: 1.1;
	text-align: center;
	width: 100%;
	padding: 0 30rpx;
	box-sizing: border-box;
	display: flex;
	align-items: baseline;
	justify-content: center;
	
	.currency {
		font-size: 24rpx;
		margin-right: 4rpx;
	}
	
	.value {
		font-size: 38rpx;
	}
	
	.unit {
		font-size: 24rpx;
		color: #666;
		margin-left: 4rpx;
	}
}

.billing-footer {
	display: flex;
	justify-content: space-around;
	width: 100%;
	padding-top: 30rpx;
	border-top: 1px solid rgba(0, 0, 0, 0.05);
	margin-top: auto;
}

.count-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.count-icon {
	width: 36rpx;
	height: 36rpx;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
	
	&.green { background: #4caf50; }
	&.red { background: #f44336; }
	&.light-blue { background: #42a5f5; }
	&.purple { background: #9c27b0; }
	&.orange { background: #ff9800; }
	&.pink { background: #e91e63; }
}

.count-text {
	font-size: 26rpx;
	color: #666666;
	line-height: 1.5;
	display: flex;
	align-items: baseline;
	
	.count-value {
		font-size: 26rpx;
		font-weight: 500;
	}
}

.kpi-grid-bottom {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 16rpx;
}

.kpi-card {
	background: rgba(255, 255, 255, 0.8);
	backdrop-filter: blur(20px) saturate(180%);
	-webkit-backdrop-filter: blur(20px) saturate(180%);
	border-radius: 24rpx;
	padding: 24rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08), 0 0 0 1px rgba(255, 255, 255, 0.8) inset;
	
	.kpi-header {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
		
		.kpi-icon-square {
			width: 50rpx;
			height: 50rpx;
			border-radius: 10rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 12rpx;
			flex-shrink: 0;
			
			&.green { background: #4caf50; }
			&.red { background: #f44336; }
			&.light-blue { background: #42a5f5; }
			&.purple { background: #9c27b0; }
			&.orange { background: #ff9800; }
			&.pink { background: #e91e63; }
		}
		
		.kpi-label {
			font-size: 24rpx;
			color: #666;
		}
	}
	
	.kpi-value-group {
		display: flex;
		align-items: baseline;
		
		.currency { 
			font-size: 24rpx; 
			color: #333; 
			margin-right: 4rpx; 
		}
		.value { 
			font-size: 36rpx; 
			font-weight: bold; 
			color: #333; 
			letter-spacing: -1rpx; 
			flex: 1;
			text-align: center;
		}
		.unit { 
			font-size: 24rpx; 
			color: #666; 
			margin-left: 4rpx; 
		}
	}
}

/* 图表区域 */
.chart-wrapper {
	width: 100%;
	height: 400rpx;
	position: static;
	/* #ifdef MP-WEIXIN */
	z-index: 1;
	/* #endif */
}

.trend-chart-box {
	width: 100%;
	height: 400rpx;
}

.trend-chart-canvas,
.compare-chart-canvas,
.stacked-chart-canvas,
.funnel-chart-canvas {
	width: 100%;
	height: 100%;
}

.trend-legend-modern {
	display: flex;
	justify-content: center;
	margin-top: 16rpx;
	gap: 20rpx;
	
	.legend-item {
		display: flex;
		align-items: center;
		font-size: 22rpx;
		color: #666;
		
		.dot {
			width: 10rpx;
			height: 10rpx;
			border-radius: 50%;
			margin-right: 6rpx;
			
			&.revenue { background: #409EFF; }
			&.consume { background: #67C23A; }
			&.net { background: #E6A23C; }
		}
	}
}

/* 分类占比图表 */
.category-chart-container {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.category-chart-wrapper {
	width: 100%;
	height: 480rpx;
	margin-bottom: 16rpx;
	position: static;
	/* #ifdef MP-WEIXIN */
	z-index: 1;
	/* #endif */
}

.category-chart-canvas {
	width: 100%;
	height: 100%;
}

.category-legend {
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	gap: 16rpx;
	padding: 16rpx;
	width: 100%;
}

.category-legend .legend-item {
	display: flex;
	align-items: center;
	gap: 6rpx;
	padding: 6rpx 12rpx;
	background: #fff;
	border-radius: 8rpx;
}

.category-legend .legend-dot {
	width: 20rpx;
	height: 20rpx;
	border-radius: 50%;
}

.category-legend .legend-name {
	font-size: 22rpx;
	color: #666;
	margin-right: 6rpx;
}

.category-legend .legend-value {
	font-size: 22rpx;
	color: #333;
	font-weight: bold;
}

/* 排行榜 */
.rank-list-modern {
	.rank-item {
		display: flex;
		align-items: center;
		padding: 18rpx 0;
		
		.rank-idx {
			width: 50rpx;
			font-size: 26rpx;
			font-weight: bold;
			color: #999;
			text-align: center;
			margin-right: 16rpx;
			
			&.rank-1 { 
				color: #FFD700; 
				font-size: 30rpx; 
				text-shadow: 0 2rpx 4rpx rgba(255, 215, 0, 0.3);
			}
			
			&.rank-2 { 
				color: #C0C0C0; 
				font-size: 30rpx; 
				text-shadow: 0 2rpx 4rpx rgba(192, 192, 192, 0.3);
			}
			
			&.rank-3 { 
				color: #CD7F32; 
				font-size: 30rpx; 
				text-shadow: 0 2rpx 4rpx rgba(205, 127, 50, 0.3);
			}
			
			&.top-3 { color: #43a047; font-size: 30rpx; }
			
			.medal-icon { 
				width: 40rpx; 
				height: 40rpx; 
			}
		}
		
		.rank-avatar {
			width: 56rpx;
			height: 56rpx;
			background: #e8f5e9;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 16rpx;
			color: #43a047;
			font-weight: bold;
			font-size: 24rpx;
		}
		
		.rank-info {
			flex: 1;
			
			.info-main {
				display: flex;
				flex-direction: column;
				margin-bottom: 10rpx;
				
				.name { 
					font-size: 26rpx; 
					font-weight: 500; 
					color: #333; 
					margin-bottom: 8rpx;
				}
				
				.performance-values {
					display: flex;
					flex-direction: column;
					gap: 4rpx;
					
					.perf-item {
						font-size: 22rpx;
						color: #666;
					}
				}
				
				.value { font-size: 26rpx; font-weight: bold; color: #43a047; }
			}
			
			.progress-bg {
				height: 6rpx;
				background: #f5f5f5;
				border-radius: 3rpx;
				overflow: hidden;
				
				.progress-bar {
					height: 100%;
					background: linear-gradient(90deg, #66bb6a 0%, #43a047 100%);
					border-radius: 3rpx;
					
					&.green { background: linear-gradient(90deg, #66bb6a 0%, #43a047 100%); }
				}
			}
		}
	}
}

/* 品项排行 */
.item-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 16rpx;
	
	.item-card {
		background: #fff;
		border-radius: 12rpx;
		padding: 16rpx;
		position: relative;
		overflow: hidden;
		
		.item-rank-badge {
			position: absolute;
			top: 0;
			left: 0;
			padding: 3rpx 10rpx;
			background: #f0f0f0;
			color: #999;
			font-size: 18rpx;
			border-bottom-right-radius: 12rpx;
			
			&.rank-1 { background: #ffe0b2; color: #ef6c00; }
			&.rank-2 { background: #e0f2f1; color: #00897b; }
			&.rank-3 { background: #e3f2fd; color: #1e88e5; }
		}
		
		.item-name { 
			font-size: 24rpx; 
			color: #333; 
			margin-top: 20rpx; 
			margin-bottom: 6rpx; 
			white-space: nowrap; 
			overflow: hidden; 
			text-overflow: ellipsis; 
			font-weight: 500; 
		}
		.item-val { 
			font-size: 24rpx; 
			color: #43a047; 
			font-weight: bold; 
			margin-bottom: 10rpx; 
		}
		.item-process { 
			width: 100%; 
			height: 4rpx; 
			background: #f0f0f0; 
			border-radius: 2rpx; 
			.bar { 
				height: 100%; 
				background: #43a047; 
				border-radius: 2rpx; 
			} 
		}
	}
}

/* 热力图 */
.heatmap-grid {
	.heatmap-row {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
		
		&.heatmap-time-header {
			margin-bottom: 12rpx;
			padding-bottom: 8rpx;
			border-bottom: 1px solid rgba(0, 0, 0, 0.08);
		}
		
		.heatmap-day {
			width: 80rpx;
			font-size: 22rpx;
			color: #666;
			text-align: center;
			font-weight: 500;
		}
		
		.heatmap-times {
			flex: 1;
			display: flex;
			gap: 4rpx;
			
			.heatmap-time-label {
				flex: 1;
				font-size: 20rpx;
				color: #666;
				text-align: center;
				font-weight: 500;
			}
			
			.heatmap-cell {
				flex: 1;
				height: 44rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 18rpx;
				font-weight: 500;
				border-radius: 6rpx;
				border: 1px solid rgba(0, 0, 0, 0.05);
				transition: all 0.2s ease;
				
				&.has-data {
					box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
				}
			}
		}
	}
}

.heatmap-legend {
	display: flex;
	justify-content: center;
	align-items: center;
	flex-wrap: wrap;
	gap: 16rpx;
	margin-top: 20rpx;
	padding-top: 20rpx;
	border-top: 1px solid rgba(0, 0, 0, 0.05);
	
	.legend-item {
		display: flex;
		align-items: center;
		gap: 6rpx;
		
		.legend-color {
			width: 24rpx;
			height: 24rpx;
			border-radius: 4rpx;
			border: 1px solid rgba(0, 0, 0, 0.1);
		}
		
		.legend-text {
			font-size: 20rpx;
			color: #666;
		}
	}
}

/* 排名对比 */
.comparison-content {
	.ranking-item {
		text-align: center;
		padding: 16rpx 0;
		
		.ranking-label {
			font-size: 24rpx;
			color: #909399;
			margin-bottom: 12rpx;
		}
		
		.ranking-value {
			margin-bottom: 12rpx;
			
			.rank-number {
				font-size: 48rpx;
				font-weight: 700;
				color: #409EFF;
			}
			
			.rank-total {
				font-size: 24rpx;
				color: #909399;
				margin-left: 4rpx;
			}
		}
		
		.ranking-badge {
			display: inline-block;
			padding: 8rpx 24rpx;
			border-radius: 20rpx;
			font-size: 24rpx;
			font-weight: 600;
			
			&.excellent {
				background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
				color: #fff;
			}
			
			&.good {
				background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
				color: #fff;
			}
			
			&.normal {
				background: #f4f4f5;
				color: #909399;
			}
		}
	}
	
	.comparison-stats {
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1px dashed #ebeef5;
		
		.stat-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 12rpx 0;
			font-size: 24rpx;
			
			.stat-label {
				color: #606266;
			}
			
			.stat-value {
				font-weight: 600;
				color: #303133;
			}
		}
	}
}

/* 散点图 */
.scatter-chart-box {
	width: 100%;
	height: 500rpx;
	position: static;
	/* #ifdef MP-WEIXIN */
	z-index: 1;
	/* #endif */
}

.scatter-legend {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 16rpx;
	padding-top: 16rpx;
	border-top: 1px solid rgba(0, 0, 0, 0.05);
	
	.legend-note {
		display: flex;
		align-items: center;
		gap: 8rpx;
		
		.legend-dot {
			width: 16rpx;
			height: 16rpx;
			border-radius: 50%;
			background-color: #409EFF;
		}
		
		.legend-text {
			font-size: 22rpx;
			color: #666;
		}
	}
}

/* 指标卡片 */
.metrics-section {
	.metrics-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 16rpx;
		
		.metric-item {
			background: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			min-height: 120rpx;
			
			.metric-label {
				font-size: 22rpx;
				color: #666;
				margin-bottom: 8rpx;
			}
			
			.metric-value {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.metric-rate {
				font-size: 20rpx;
				color: #999;
				margin-top: 4rpx;
			}
		}
	}
}

/* 目标完成度 */
.gauge-section {
	.gauge-container {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
		
		.gauge-circle {
			width: 300rpx;
			height: 300rpx;
			position: relative;
			
			.gauge-progress {
				width: 100%;
				height: 100%;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
				
				.gauge-inner {
					width: 240rpx;
					height: 240rpx;
					background: #fff;
					border-radius: 50%;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					
					.gauge-value-text {
						font-size: 56rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 8rpx;
					}
					
					.gauge-label {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
		}
	}
}

/* 经营提示 */
.tips-section {
	.tips-list {
		.tip-item {
			background: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 12rpx;
			font-size: 24rpx;
			line-height: 1.6;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			&.success {
				background: #f0f9ff;
				color: #67C23A;
				border-left: 4rpx solid #67C23A;
			}
			
			&.warning {
				background: #fdf6ec;
				color: #E6A23C;
				border-left: 4rpx solid #E6A23C;
			}
			
			&.danger {
				background: #fef0f0;
				color: #F56C6C;
				border-left: 4rpx solid #F56C6C;
			}
			
			&.info {
				background: #f4f4f5;
				color: #909399;
				border-left: 4rpx solid #909399;
			}
		}
	}
}

/* 快速数据洞察 */
.insight-section {
	.insight-list {
		.insight-item {
			background: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 16rpx;
			border-left: 4rpx solid #409EFF;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.insight-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 12rpx;
				
				.insight-title {
					font-size: 26rpx;
					font-weight: 600;
					color: #333;
				}
				
				.insight-tag {
					font-size: 20rpx;
					padding: 4rpx 12rpx;
					border-radius: 8rpx;
					background: #f0f0f0;
					color: #666;
					
					&.tag-highlight {
						background: #409EFF;
						color: #fff;
					}
				}
			}
			
			.insight-value {
				font-size: 36rpx;
				font-weight: bold;
				color: #409EFF;
				margin-bottom: 8rpx;
			}
			
			.insight-desc {
				font-size: 22rpx;
				color: #999;
				line-height: 1.5;
			}
		}
	}
}

/* 关键指标 */
.key-metrics-section {
	.key-metrics-list {
		.key-metric-item {
			background: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 16rpx;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.metric-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 12rpx;
				
				.metric-label {
					font-size: 24rpx;
					color: #666;
				}
				
				.metric-value {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
				}
			}
			
			.progress-wrapper {
				height: 16rpx;
				background: #f0f0f0;
				border-radius: 8rpx;
				overflow: hidden;
				
				.progress-bar {
					height: 100%;
					border-radius: 8rpx;
					transition: width 0.3s;
				}
			}
		}
	}
}
</style>

