<template>
    <div class="report-dashboard">
        <!-- 页面标题和筛选区域 -->
        <div class="dashboard-header">
            <div class="header-title">
                <h1>📊 业务报表中心</h1>
                <p class="subtitle">实时数据监控 · 业绩分析 · 决策支持</p>
            </div>
            <div class="header-filters">
                <el-card class="filter-card">
                    <div class="filter-row">
                        <div class="filter-item">
                            <label>统计月份：</label>
                            <el-date-picker v-model="selectedMonth" type="month" placeholder="选择月份" format="yyyy年MM月"
                                value-format="yyyyMM" @change="onMonthChange" class="month-picker" />
                        </div>
                        <div class="filter-item">
                            <label>时间范围：</label>
                            <el-date-picker v-model="dateRange" type="monthrange" range-separator="至"
                                start-placeholder="开始月份" end-placeholder="结束月份" format="yyyy年MM月" value-format="yyyyMM"
                                @change="onDateRangeChange" class="range-picker" />
                        </div>
                        <div class="filter-item">
                            <el-button type="primary" @click="refreshData" :loading="loading">
                                <i class="el-icon-refresh"></i> 刷新数据
                            </el-button>
                            <el-button type="success" @click="exportData">
                                <i class="el-icon-download"></i> 导出报表
                            </el-button>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>

        <!-- 仪表盘概览 -->
        <div class="dashboard-overview">
            <el-row :gutter="20">
                <el-col :span="6" v-for="(item, index) in overviewCards" :key="index">
                    <el-card class="overview-card" :class="`card-${index + 1}`">
                        <div class="card-content">
                            <div class="card-icon">
                                <i :class="item.icon"></i>
                            </div>
                            <div class="card-info">
                                <div class="card-title">{{ item.title }}</div>
                                <div class="card-value">{{ formatNumber(item.value) }}</div>
                                <div class="card-unit">{{ item.unit }}</div>
                                <div class="card-trend" :class="item.trend > 0 ? 'trend-up' : 'trend-down'">
                                    <i :class="item.trend > 0 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"></i>
                                    {{ Math.abs(item.trend) }}%
                                </div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 会员统计概览 -->
        <div class="member-statistics-overview" style="margin-top: 20px;">
            <el-row :gutter="20">
                <!-- 总会员数 -->
                <el-col :span="6">
                    <el-card class="member-card card-member-total">
                        <div class="card-content">
                            <div class="card-icon">
                                <i class="el-icon-user-solid"></i>
                            </div>
                            <div class="card-info">
                                <div class="card-title">总会员数</div>
                                <div class="card-value">{{ formatNumber(memberCards.totalMembers) }}</div>
                                <div class="card-unit">人</div>
                                <div class="card-subtitle">本月新增：{{ formatNumber(memberCards.newMembers) }}人</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <!-- 活跃会员数 -->
                <el-col :span="6">
                    <el-card class="member-card card-member-active">
                        <div class="card-content">
                            <div class="card-icon">
                                <i class="el-icon-success"></i>
                            </div>
                            <div class="card-info">
                                <div class="card-title">活跃会员数</div>
                                <div class="card-value">{{ formatNumber(memberCards.activeMembers) }}</div>
                                <div class="card-unit">人</div>
                                <div class="card-subtitle">活跃率：{{ memberCards.activeRate }}%</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <!-- 剩余权益总金额 -->
                <el-col :span="6">
                    <el-card class="member-card card-member-amount">
                        <div class="card-content">
                            <div class="card-icon">
                                <i class="el-icon-wallet"></i>
                            </div>
                            <div class="card-info">
                                <div class="card-title">剩余权益总金额</div>
                                <div class="card-value">{{ formatNumber(memberCards.totalRemainingAmount / 10000) }}
                                </div>
                                <div class="card-unit">万元</div>
                                <div class="card-subtitle">人均：{{ formatNumber(memberCards.avgRemainingAmount) }}元</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <!-- 沉睡会员数 -->
                <el-col :span="6">
                    <el-card class="member-card card-member-sleep">
                        <div class="card-content">
                            <div class="card-icon">
                                <i class="el-icon-warning"></i>
                            </div>
                            <div class="card-info">
                                <div class="card-title">沉睡会员数</div>
                                <div class="card-value">{{ formatNumber(memberCards.totalSleepMembers) }}</div>
                                <div class="card-unit">人</div>
                                <div class="card-subtitle">30-90天：{{ formatNumber(memberCards.sleep30_90) }} | 90天+：{{
                                    formatNumber(memberCards.sleepOver90) }}</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 20px;">
                <!-- 会员类型分布 -->
                <el-col :span="12">
                    <el-card class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="chart-title">
                                <i class="el-icon-pie-chart"></i>
                                会员类型分布
                            </span>
                        </div>
                        <div class="chart-container" ref="memberTypeChart"></div>
                    </el-card>
                </el-col>

                <!-- 会员分类统计 -->
                <el-col :span="12">
                    <el-card class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="chart-title">
                                <i class="el-icon-s-grid"></i>
                                会员分类统计
                            </span>
                        </div>
                        <div class="member-category-list">
                            <div class="category-item" v-for="(item, index) in memberCategoryList" :key="index">
                                <div class="category-icon" :class="`category-${index + 1}`">
                                    <i :class="item.icon"></i>
                                </div>
                                <div class="category-info">
                                    <div class="category-name">{{ item.name }}</div>
                                    <div class="category-value">{{ formatNumber(item.value) }}人</div>
                                </div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 图表区域 -->
        <div class="charts-section">
            <el-row :gutter="20">
                <!-- 门店业绩趋势 -->
                <el-col :span="12">
                    <el-card class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="chart-title">
                                <i class="el-icon-trend-charts"></i>
                                门店业绩趋势
                            </span>
                            <el-button-group class="chart-controls">
                                <el-button size="mini" @click="switchStoreTrendType('performance')"
                                    :type="storeTrendType === 'performance' ? 'primary' : ''">业绩</el-button>
                                <el-button size="mini" @click="switchStoreTrendType('orders')"
                                    :type="storeTrendType === 'orders' ? 'primary' : ''">订单</el-button>
                            </el-button-group>
                        </div>
                        <div class="chart-container" ref="storeTrendChart"></div>
                    </el-card>
                </el-col>

                <!-- 门店业绩排行榜 -->
                <el-col :span="12">
                    <el-card class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="chart-title">
                                <i class="el-icon-trophy"></i>
                                门店业绩排行榜
                            </span>
                            <el-select v-model="rankingTopCount" @change="refreshRankingData" size="mini"
                                class="ranking-select">
                                <el-option label="前5名" :value="5"></el-option>
                                <el-option label="前10名" :value="10"></el-option>
                                <el-option label="前20名" :value="20"></el-option>
                            </el-select>
                        </div>
                        <div class="chart-container" ref="storeRankingChart"></div>
                    </el-card>
                </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 20px;">
                <!-- 健康师业绩排行榜 -->
                <el-col :span="12">
                    <el-card class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="chart-title">
                                <i class="el-icon-user"></i>
                                健康师业绩排行榜
                            </span>
                            <el-select v-model="healthCoachTopCount" @change="refreshHealthCoachRanking" size="mini"
                                class="ranking-select">
                                <el-option label="前10名" :value="10"></el-option>
                                <el-option label="前20名" :value="20"></el-option>
                                <el-option label="前50名" :value="50"></el-option>
                            </el-select>
                        </div>
                        <div class="chart-container" ref="healthCoachRankingChart"></div>
                    </el-card>
                </el-col>

                <!-- 金三角业绩排行榜 -->
                <el-col :span="12">
                    <el-card class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="chart-title">
                                <i class="el-icon-star-on"></i>
                                金三角业绩排行榜
                            </span>
                            <el-select v-model="goldTriangleTopCount" @change="refreshGoldTriangleRanking" size="mini"
                                class="ranking-select">
                                <el-option label="前5名" :value="5"></el-option>
                                <el-option label="前10名" :value="10"></el-option>
                                <el-option label="前15名" :value="15"></el-option>
                            </el-select>
                        </div>
                        <div class="chart-container" ref="goldTriangleRankingChart"></div>
                    </el-card>
                </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 20px;">
                <!-- 金三角业绩趋势 -->
                <el-col :span="24">
                    <el-card class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="chart-title">
                                <i class="el-icon-data-line"></i>
                                金三角业绩趋势对比
                            </span>
                            <el-button-group class="chart-controls">
                                <el-button size="mini" @click="switchGoldTriangleTrendType('performance')"
                                    :type="goldTriangleTrendType === 'performance' ? 'primary' : ''">业绩</el-button>
                                <el-button size="mini" @click="switchGoldTriangleTrendType('orders')"
                                    :type="goldTriangleTrendType === 'orders' ? 'primary' : ''">订单</el-button>
                                <el-button size="mini" @click="switchGoldTriangleTrendType('members')"
                                    :type="goldTriangleTrendType === 'members' ? 'primary' : ''">成员</el-button>
                            </el-button-group>
                        </div>
                        <div class="chart-container large-chart" ref="goldTriangleTrendChart"></div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!-- 数据表格区域 -->
        <div class="data-tables">
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-card class="table-card">
                        <div slot="header" class="table-header">
                            <span class="table-title">
                                <i class="el-icon-s-grid"></i>
                                详细数据表格
                            </span>
                            <el-tabs v-model="activeTableTab" @tab-click="handleTableTabClick" class="table-tabs">
                                <el-tab-pane label="门店业绩" name="store"></el-tab-pane>
                                <el-tab-pane label="健康师业绩" name="healthCoach"></el-tab-pane>
                                <el-tab-pane label="金三角业绩" name="goldTriangle"></el-tab-pane>
                            </el-tabs>
                        </div>
                        <div class="table-container">
                            <el-table :data="tableData" v-loading="tableLoading" stripe border height="400"
                                class="data-table">
                                <el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop"
                                    :label="column.label" :width="column.width" :formatter="column.formatter"
                                    :sortable="column.sortable" />
                            </el-table>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'
import {
    getStorePerformanceTrend,
    getStorePerformanceRanking,
    getHealthCoachPerformanceRanking,
    getHealthCoachPerformanceTrend,
    getGoldTrianglePerformanceRanking,
    getGoldTrianglePerformanceTrend,
    getDashboardData
} from '@/api/report'

export default {
    name: 'ReportDashboard',
    data() {
        return {
            loading: false,
            tableLoading: false,

            // 筛选条件
            selectedMonth: '',
            dateRange: [],

            // 图表类型切换
            storeTrendType: 'performance',
            goldTriangleTrendType: 'performance',

            // 排行榜数量
            rankingTopCount: 10,
            healthCoachTopCount: 20,
            goldTriangleTopCount: 10,

            // 表格相关
            activeTableTab: 'store',
            tableData: [],
            tableColumns: [],

            // 仪表盘数据
            overviewCards: [
                {
                    title: '门店总数',
                    value: 0,
                    unit: '家',
                    icon: 'el-icon-shop',
                    trend: 0
                },
                {
                    title: '总业绩',
                    value: 0,
                    unit: '万元',
                    icon: 'el-icon-money',
                    trend: 0
                },
                {
                    title: '健康师总数',
                    value: 0,
                    unit: '人',
                    icon: 'el-icon-user',
                    trend: 0
                },
                {
                    title: '金三角总数',
                    value: 0,
                    unit: '个',
                    icon: 'el-icon-star-on',
                    trend: 0
                }
            ],

            // 会员统计卡片数据
            memberCards: {
                totalMembers: 0,
                newMembers: 0,
                activeMembers: 0,
                activeRate: 0,
                totalRemainingAmount: 0,
                avgRemainingAmount: 0,
                totalSleepMembers: 0,
                sleep30_90: 0,
                sleepOver90: 0
            },

            // 会员分类列表
            memberCategoryList: [
                { name: '生美会员', value: 0, icon: 'el-icon-star-on' },
                { name: '医美会员', value: 0, icon: 'el-icon-medicine-box' },
                { name: '科技部会员', value: 0, icon: 'el-icon-cpu' },
                { name: '教育部会员', value: 0, icon: 'el-icon-reading' }
            ],

            // 会员类型分布数据
            memberTypeDistribution: [],

            // 图表实例
            charts: {}
        }
    },

    mounted() {
        this.initPage()
    },

    methods: {
        // 初始化页面
        async initPage() {
            // 设置默认月份
            const now = new Date()
            this.selectedMonth = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}`

            // 设置默认时间范围（最近6个月）
            const startMonth = new Date(now.getFullYear(), now.getMonth() - 5, 1)
            this.dateRange = [
                `${startMonth.getFullYear()}${String(startMonth.getMonth() + 1).padStart(2, '0')}`,
                this.selectedMonth
            ]

            // 加载数据
            await this.loadDashboardData()
            await this.loadAllCharts()
        },

        // 加载仪表盘数据
        async loadDashboardData() {
            try {
                this.loading = true
                const response = await getDashboardData({
                    statisticsMonth: this.selectedMonth
                })

                if (response.data && response.data.Success) {
                    const data = response.data.Data

                    // 更新概览卡片
                    this.overviewCards[0].value = data.StorePerformance.StoreCount
                    this.overviewCards[1].value = Math.round(data.StorePerformance.TotalPerformance / 10000 * 100) / 100
                    this.overviewCards[2].value = data.HealthCoachPerformance.HealthCoachCount
                    this.overviewCards[3].value = data.GoldTrianglePerformance.GoldTriangleCount

                    // 更新会员统计数据
                    if (data.MemberStatistics) {
                        const memberStats = data.MemberStatistics
                        this.memberCards.totalMembers = memberStats.TotalMembers || 0
                        this.memberCards.newMembers = memberStats.NewMembersThisMonth || 0
                        this.memberCards.activeMembers = memberStats.ActiveMembers || 0
                        this.memberCards.activeRate = memberStats.ActiveRate || 0
                        this.memberCards.totalRemainingAmount = memberStats.TotalRemainingAmount || 0
                        this.memberCards.avgRemainingAmount = memberStats.AvgRemainingAmount || 0
                        this.memberCards.totalSleepMembers = memberStats.TotalSleepMembers || 0
                        this.memberCards.sleep30_90 = memberStats.SleepMembers30_90 || 0
                        this.memberCards.sleepOver90 = memberStats.SleepMembersOver90 || 0

                        // 更新会员分类列表
                        this.memberCategoryList[0].value = memberStats.BeautyMembers || 0
                        this.memberCategoryList[1].value = memberStats.MedicalMembers || 0
                        this.memberCategoryList[2].value = memberStats.TechMembers || 0
                        this.memberCategoryList[3].value = memberStats.EducationMembers || 0

                        // 更新会员类型分布
                        this.memberTypeDistribution = memberStats.MemberTypeDistribution || []

                        // 加载会员类型分布饼图
                        this.$nextTick(() => {
                            this.loadMemberTypeChart()
                        })
                    }
                }
            } catch (error) {
                this.$message.error('加载仪表盘数据失败')
                console.error('Dashboard data error:', error)
            } finally {
                this.loading = false
            }
        },

        // 加载所有图表
        async loadAllCharts() {
            await Promise.all([
                this.loadStoreTrendChart(),
                this.loadStoreRankingChart(),
                this.loadHealthCoachRankingChart(),
                this.loadGoldTriangleRankingChart(),
                this.loadGoldTriangleTrendChart()
            ])
        },

        // 加载会员类型分布饼图
        loadMemberTypeChart() {
            if (!this.$refs.memberTypeChart) return

            // 如果图表已存在，先销毁
            if (this.charts.memberTypeChart) {
                this.charts.memberTypeChart.dispose()
            }

            const chartDom = this.$refs.memberTypeChart
            this.charts.memberTypeChart = echarts.init(chartDom)

            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    top: 'middle'
                },
                series: [
                    {
                        name: '会员类型',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: true,
                            formatter: '{b}\n{c}人 ({d}%)'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 16,
                                fontWeight: 'bold'
                            }
                        },
                        data: this.memberTypeDistribution.map(item => ({
                            value: item.Count,
                            name: item.MemberType
                        }))
                    }
                ]
            }

            this.charts.memberTypeChart.setOption(option)

            // 响应式调整
            window.addEventListener('resize', () => {
                if (this.charts.memberTypeChart) {
                    this.charts.memberTypeChart.resize()
                }
            })
        },

        // 加载门店业绩趋势图
        async loadStoreTrendChart() {
            try {
                const response = await getStorePerformanceTrend({
                    startMonth: this.dateRange[0],
                    endMonth: this.dateRange[1]
                })

                if (response.data && response.data.Success) {
                    this.renderStoreTrendChart(response.data.Data)
                }
            } catch (error) {
                console.error('Store trend chart error:', error)
            }
        },

        // 渲染门店业绩趋势图
        renderStoreTrendChart(data) {
            const chartDom = this.$refs.storeTrendChart
            if (!chartDom) return

            const chart = echarts.init(chartDom)
            this.charts.storeTrend = chart

            const months = []
            const series = []

            data.forEach(store => {
                months.push.apply(months, store.Data.map(item => item.Month))
                series.push({
                    name: store.StoreName,
                    type: 'line',
                    smooth: true,
                    data: store.Data.map(item =>
                        this.storeTrendType === 'performance' ? item.TotalPerformance : item.FirstOrderCount + item.UpgradeOrderCount
                    )
                })
            })

            const uniqueMonths = Array.from(new Set(months)).sort()

            const option = {
                title: {
                    text: this.storeTrendType === 'performance' ? '门店业绩趋势' : '门店订单趋势',
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    top: 30,
                    type: 'scroll'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: uniqueMonths,
                    axisLabel: {
                        formatter: value => `${value.slice(0, 4)}-${value.slice(4)}`
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: this.storeTrendType === 'performance' ? '{value}元' : '{value}单'
                    }
                },
                series: series.slice(0, 10) // 限制显示前10个门店
            }

            chart.setOption(option)
        },

        // 加载门店业绩排行榜
        async loadStoreRankingChart() {
            try {
                const response = await getStorePerformanceRanking({
                    statisticsMonth: this.selectedMonth,
                    topCount: this.rankingTopCount
                })

                if (response.data && response.data.Success) {
                    this.renderStoreRankingChart(response.data.Data)
                }
            } catch (error) {
                console.error('Store ranking chart error:', error)
            }
        },

        // 渲染门店业绩排行榜
        renderStoreRankingChart(data) {
            const chartDom = this.$refs.storeRankingChart
            if (!chartDom) return

            const chart = echarts.init(chartDom)
            this.charts.storeRanking = chart

            const option = {
                title: {
                    text: '门店业绩排行榜',
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}元'
                    }
                },
                yAxis: {
                    type: 'category',
                    data: data.map(item => item.StoreName),
                    axisLabel: {
                        formatter: value => value.length > 6 ? value.slice(0, 6) + '...' : value
                    }
                },
                series: [{
                    type: 'bar',
                    data: data.map(item => item.TotalPerformance),
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: '#83bff6' },
                            { offset: 0.5, color: '#188df0' },
                            { offset: 1, color: '#188df0' }
                        ])
                    }
                }]
            }

            chart.setOption(option)
        },

        // 加载健康师业绩排行榜
        async loadHealthCoachRankingChart() {
            try {
                const response = await getHealthCoachPerformanceRanking({
                    statisticsMonth: this.selectedMonth,
                    topCount: this.healthCoachTopCount
                })

                if (response.data && response.data.Success) {
                    this.renderHealthCoachRankingChart(response.data.Data)
                }
            } catch (error) {
                console.error('Health coach ranking chart error:', error)
            }
        },

        // 渲染健康师业绩排行榜
        renderHealthCoachRankingChart(data) {
            const chartDom = this.$refs.healthCoachRankingChart
            if (!chartDom) return

            const chart = echarts.init(chartDom)
            this.charts.healthCoachRanking = chart

            const option = {
                title: {
                    text: '健康师业绩排行榜',
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}元'
                    }
                },
                yAxis: {
                    type: 'category',
                    data: data.map(item => item.UserName),
                    axisLabel: {
                        formatter: value => value.length > 4 ? value.slice(0, 4) + '...' : value
                    }
                },
                series: [{
                    type: 'bar',
                    data: data.map(item => item.TotalPerformance),
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: '#ff9f7f' },
                            { offset: 0.5, color: '#ff6b6b' },
                            { offset: 1, color: '#ff6b6b' }
                        ])
                    }
                }]
            }

            chart.setOption(option)
        },

        // 加载金三角业绩排行榜
        async loadGoldTriangleRankingChart() {
            try {
                const response = await getGoldTrianglePerformanceRanking({
                    statisticsMonth: this.selectedMonth,
                    topCount: this.goldTriangleTopCount
                })

                if (response.data && response.data.Success) {
                    this.renderGoldTriangleRankingChart(response.data.Data)
                }
            } catch (error) {
                console.error('Gold triangle ranking chart error:', error)
            }
        },

        // 渲染金三角业绩排行榜
        renderGoldTriangleRankingChart(data) {
            const chartDom = this.$refs.goldTriangleRankingChart
            if (!chartDom) return

            const chart = echarts.init(chartDom)
            this.charts.goldTriangleRanking = chart

            const option = {
                title: {
                    text: '金三角业绩排行榜',
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}元'
                    }
                },
                yAxis: {
                    type: 'category',
                    data: data.map(item => item.GoldTriangleName),
                    axisLabel: {
                        formatter: value => value.length > 6 ? value.slice(0, 6) + '...' : value
                    }
                },
                series: [{
                    type: 'bar',
                    data: data.map(item => item.TotalPerformance),
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: '#ffd93d' },
                            { offset: 0.5, color: '#ffb347' },
                            { offset: 1, color: '#ff8c00' }
                        ])
                    }
                }]
            }

            chart.setOption(option)
        },

        // 加载金三角业绩趋势图
        async loadGoldTriangleTrendChart() {
            try {
                const response = await getGoldTrianglePerformanceTrend({
                    startMonth: this.dateRange[0],
                    endMonth: this.dateRange[1]
                })

                if (response.data && response.data.Success) {
                    this.renderGoldTriangleTrendChart(response.data.Data)
                }
            } catch (error) {
                console.error('Gold triangle trend chart error:', error)
            }
        },

        // 渲染金三角业绩趋势图
        renderGoldTriangleTrendChart(data) {
            const chartDom = this.$refs.goldTriangleTrendChart
            if (!chartDom) return

            const chart = echarts.init(chartDom)
            this.charts.goldTriangleTrend = chart

            const months = []
            const series = []

            data.forEach(team => {
                months.push.apply(months, team.Data.map(item => item.Month))
                series.push({
                    name: team.GoldTriangleName,
                    type: 'line',
                    smooth: true,
                    data: team.Data.map(item => {
                        switch (this.goldTriangleTrendType) {
                            case 'performance': return item.TotalPerformance
                            case 'orders': return item.OrderCount
                            case 'members': return item.MemberCount
                            default: return item.TotalPerformance
                        }
                    })
                })
            })

            const uniqueMonths = Array.from(new Set(months)).sort()

            const option = {
                title: {
                    text: this.getGoldTriangleTrendTitle(),
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                legend: {
                    top: 30,
                    type: 'scroll'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: uniqueMonths,
                    axisLabel: {
                        formatter: value => `${value.slice(0, 4)}-${value.slice(4)}`
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: this.getGoldTriangleTrendFormatter()
                    }
                },
                series: series.slice(0, 8) // 限制显示前8个金三角
            }

            chart.setOption(option)
        },

        // 获取金三角趋势图标题
        getGoldTriangleTrendTitle() {
            switch (this.goldTriangleTrendType) {
                case 'performance': return '金三角业绩趋势'
                case 'orders': return '金三角订单趋势'
                case 'members': return '金三角成员趋势'
                default: return '金三角业绩趋势'
            }
        },

        // 获取金三角趋势图格式化器
        getGoldTriangleTrendFormatter() {
            switch (this.goldTriangleTrendType) {
                case 'performance': return '{value}元'
                case 'orders': return '{value}单'
                case 'members': return '{value}人'
                default: return '{value}元'
            }
        },

        // 切换门店趋势类型
        switchStoreTrendType(type) {
            this.storeTrendType = type
            const chart = this.charts.storeTrend
            if (chart && chart.getOption && chart.getOption().series) {
                this.renderStoreTrendChart(chart.getOption().series)
            } else {
                this.renderStoreTrendChart([])
            }
        },

        // 切换金三角趋势类型
        switchGoldTriangleTrendType(type) {
            this.goldTriangleTrendType = type
            const chart = this.charts.goldTriangleTrend
            if (chart && chart.getOption && chart.getOption().series) {
                this.renderGoldTriangleTrendChart(chart.getOption().series)
            } else {
                this.renderGoldTriangleTrendChart([])
            }
        },

        // 刷新排行榜数据
        async refreshRankingData() {
            await this.loadStoreRankingChart()
        },

        // 刷新健康师排行榜数据
        async refreshHealthCoachRanking() {
            await this.loadHealthCoachRankingChart()
        },

        // 刷新金三角排行榜数据
        async refreshGoldTriangleRanking() {
            await this.loadGoldTriangleRankingChart()
        },

        // 月份变化
        async onMonthChange() {
            await this.loadDashboardData()
            await Promise.all([
                this.loadStoreRankingChart(),
                this.loadHealthCoachRankingChart(),
                this.loadGoldTriangleRankingChart()
            ])
        },

        // 时间范围变化
        async onDateRangeChange() {
            await Promise.all([
                this.loadStoreTrendChart(),
                this.loadGoldTriangleTrendChart()
            ])
        },

        // 刷新数据
        async refreshData() {
            await this.loadDashboardData()
            await this.loadAllCharts()
            this.$message.success('数据刷新成功')
        },

        // 导出数据
        exportData() {
            this.$message.info('导出功能开发中...')
        },

        // 处理表格标签切换
        handleTableTabClick(tab) {
            this.activeTableTab = tab.name
            this.loadTableData()
        },

        // 加载表格数据
        async loadTableData() {
            this.tableLoading = true
            try {
                let response
                switch (this.activeTableTab) {
                    case 'store':
                        response = await getStorePerformanceRanking({
                            statisticsMonth: this.selectedMonth,
                            topCount: 50
                        })
                        this.tableColumns = [
                            { prop: 'Ranking', label: '排名', width: 80 },
                            { prop: 'StoreName', label: '门店名称', width: 150 },
                            { prop: 'TotalPerformance', label: '总业绩', width: 120, formatter: this.formatMoney },
                            { prop: 'TotalOrderPerformance', label: '订单业绩', width: 120, formatter: this.formatMoney },
                            { prop: 'FirstOrderCount', label: '首开单数', width: 100 },
                            { prop: 'UpgradeOrderCount', label: '升单数', width: 100 }
                        ]
                        break
                    case 'healthCoach':
                        response = await getHealthCoachPerformanceRanking({
                            statisticsMonth: this.selectedMonth,
                            topCount: 50
                        })
                        this.tableColumns = [
                            { prop: 'Ranking', label: '排名', width: 80 },
                            { prop: 'UserName', label: '姓名', width: 100 },
                            { prop: 'StoreName', label: '门店', width: 120 },
                            { prop: 'TotalPerformance', label: '总业绩', width: 120, formatter: this.formatMoney },
                            { prop: 'FirstOrderPerformance', label: '新客业绩', width: 120, formatter: this.formatMoney },
                            { prop: 'UpgradeOrderPerformance', label: '升单业绩', width: 120, formatter: this.formatMoney }
                        ]
                        break
                    case 'goldTriangle':
                        response = await getGoldTrianglePerformanceRanking({
                            statisticsMonth: this.selectedMonth,
                            topCount: 50
                        })
                        this.tableColumns = [
                            { prop: 'Ranking', label: '排名', width: 80 },
                            { prop: 'GoldTriangleName', label: '金三角名称', width: 150 },
                            { prop: 'StoreName', label: '门店', width: 120 },
                            { prop: 'TotalPerformance', label: '总业绩', width: 120, formatter: this.formatMoney },
                            { prop: 'OrderCount', label: '订单数', width: 100 },
                            { prop: 'MemberCount', label: '成员数', width: 100 }
                        ]
                        break
                }

                if (response && response.data && response.data.Success) {
                    this.tableData = response.data.Data
                }
            } catch (error) {
                this.$message.error('加载表格数据失败')
                console.error('Table data error:', error)
            } finally {
                this.tableLoading = false
            }
        },

        // 格式化数字
        formatNumber(value) {
            if (value >= 10000) {
                return (value / 10000).toFixed(1) + '万'
            }
            return value.toString()
        },

        // 格式化金额
        formatMoney(row, column, cellValue) {
            if (cellValue) {
                return '¥' + this.formatNumber(cellValue)
            }
            return '¥0'
        }
    },

    beforeDestroy() {
        // 销毁图表实例
        Object.values(this.charts).forEach(chart => {
            if (chart) {
                chart.dispose()
            }
        })
    }
}
</script>

<style lang="scss" scoped>
.report-dashboard {
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;

    .dashboard-header {
        margin-bottom: 30px;

        .header-title {
            text-align: center;
            margin-bottom: 20px;

            h1 {
                color: white;
                font-size: 32px;
                font-weight: bold;
                margin: 0;
                text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
            }

            .subtitle {
                color: rgba(255, 255, 255, 0.9);
                font-size: 16px;
                margin: 10px 0 0 0;
            }
        }

        .header-filters {
            .filter-card {
                background: rgba(255, 255, 255, 0.95);
                backdrop-filter: blur(10px);
                border-radius: 15px;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

                .filter-row {
                    display: flex;
                    align-items: center;
                    gap: 20px;
                    flex-wrap: wrap;

                    .filter-item {
                        display: flex;
                        align-items: center;
                        gap: 10px;

                        label {
                            font-weight: 600;
                            color: #333;
                            white-space: nowrap;
                        }

                        .month-picker,
                        .range-picker {
                            width: 200px;
                        }
                    }
                }
            }
        }
    }

    .member-statistics-overview {
        margin-bottom: 30px;

        .member-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;

            &:hover {
                transform: translateY(-5px);
                box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
            }

            &.card-member-total {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
            }

            &.card-member-active {
                background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
                color: white;
            }

            &.card-member-amount {
                background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
                color: white;
            }

            &.card-member-sleep {
                background: linear-gradient(135deg, #ff9a56 0%, #ff6a88 100%);
                color: white;
            }

            .card-content {
                display: flex;
                align-items: center;
                padding: 20px;

                .card-icon {
                    font-size: 48px;
                    margin-right: 20px;
                    opacity: 0.8;
                }

                .card-info {
                    flex: 1;

                    .card-title {
                        font-size: 14px;
                        font-weight: 600;
                        margin-bottom: 8px;
                        opacity: 0.9;
                    }

                    .card-value {
                        font-size: 32px;
                        font-weight: bold;
                        margin-bottom: 4px;
                    }

                    .card-unit {
                        font-size: 12px;
                        opacity: 0.8;
                        margin-bottom: 4px;
                    }

                    .card-subtitle {
                        font-size: 12px;
                        opacity: 0.8;
                        margin-top: 4px;
                    }
                }
            }
        }

        .member-category-list {
            padding: 20px;

            .category-item {
                display: flex;
                align-items: center;
                padding: 15px;
                margin-bottom: 12px;
                background: rgba(245, 247, 250, 0.8);
                border-radius: 10px;
                transition: all 0.3s ease;

                &:hover {
                    background: rgba(245, 247, 250, 1);
                    transform: translateX(5px);
                }

                &:last-child {
                    margin-bottom: 0;
                }

                .category-icon {
                    width: 50px;
                    height: 50px;
                    border-radius: 10px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 15px;
                    font-size: 24px;
                    color: white;

                    &.category-1 {
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    }

                    &.category-2 {
                        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
                    }

                    &.category-3 {
                        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
                    }

                    &.category-4 {
                        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
                    }
                }

                .category-info {
                    flex: 1;

                    .category-name {
                        font-size: 16px;
                        font-weight: 600;
                        color: #333;
                        margin-bottom: 4px;
                    }

                    .category-value {
                        font-size: 20px;
                        font-weight: bold;
                        color: #409EFF;
                    }
                }
            }
        }
    }

    .dashboard-overview {
        margin-bottom: 30px;

        .overview-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;

            &:hover {
                transform: translateY(-5px);
                box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
            }

            &.card-1 {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
            }

            &.card-2 {
                background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
                color: white;
            }

            &.card-3 {
                background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
                color: white;
            }

            &.card-4 {
                background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
                color: white;
            }

            .card-content {
                display: flex;
                align-items: center;
                padding: 20px;

                .card-icon {
                    font-size: 48px;
                    margin-right: 20px;
                    opacity: 0.8;
                }

                .card-info {
                    flex: 1;

                    .card-title {
                        font-size: 14px;
                        margin-bottom: 8px;
                        opacity: 0.9;
                    }

                    .card-value {
                        font-size: 28px;
                        font-weight: bold;
                        margin-bottom: 4px;
                    }

                    .card-unit {
                        font-size: 12px;
                        opacity: 0.8;
                        margin-bottom: 8px;
                    }

                    .card-trend {
                        font-size: 12px;
                        display: flex;
                        align-items: center;
                        gap: 4px;

                        &.trend-up {
                            color: #67c23a;
                        }

                        &.trend-down {
                            color: #f56c6c;
                        }
                    }
                }
            }
        }
    }

    .charts-section {
        margin-bottom: 30px;

        .chart-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

            .chart-header {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .chart-title {
                    font-size: 16px;
                    font-weight: bold;
                    color: #333;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                }

                .chart-controls,
                .ranking-select {
                    margin-left: auto;
                }
            }

            .chart-container {
                height: 350px;
                width: 100%;

                &.large-chart {
                    height: 400px;
                }
            }
        }
    }

    .data-tables {
        .table-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

            .table-header {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .table-title {
                    font-size: 16px;
                    font-weight: bold;
                    color: #333;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                }

                .table-tabs {
                    margin-left: auto;
                }
            }

            .table-container {
                .data-table {
                    border-radius: 8px;
                    overflow: hidden;
                }
            }
        }
    }
}

// 响应式设计
@media (max-width: 1200px) {
    .report-dashboard {
        .dashboard-overview {
            .overview-card {
                margin-bottom: 20px;
            }
        }

        .charts-section {
            .chart-card {
                margin-bottom: 20px;
            }
        }
    }
}

@media (max-width: 768px) {
    .report-dashboard {
        padding: 10px;

        .dashboard-header {
            .header-title h1 {
                font-size: 24px;
            }

            .filter-row {
                flex-direction: column;
                align-items: stretch;

                .filter-item {
                    justify-content: space-between;

                    .month-picker,
                    .range-picker {
                        width: 150px;
                    }
                }
            }
        }

        .dashboard-overview {
            .overview-card .card-content {
                padding: 15px;

                .card-icon {
                    font-size: 36px;
                    margin-right: 15px;
                }

                .card-info .card-value {
                    font-size: 24px;
                }
            }
        }

        .charts-section {
            .chart-container {
                height: 300px;

                &.large-chart {
                    height: 350px;
                }
            }
        }
    }
}
</style>
