<template>
    <div class="financial-report-container">
        <!-- 筛选区域 -->
        <el-card class="search-card" shadow="never">
            <el-form :inline="true" :model="queryParams" size="small" class="search-form">
                <el-form-item label="时间范围">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 240px"
                        @change="handleDateRangeChange" />
                </el-form-item>
                <el-form-item label="统计周期">
                    <el-radio-group v-model="queryParams.periodType" size="small">
                        <el-radio-button label="day">按日</el-radio-button>
                        <el-radio-button label="month">按月</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="门店">
                    <el-select v-model="queryParams.storeIds" multiple placeholder="请选择门店（可多选）" clearable filterable
                        style="width: 300px" :loading="loading">
                        <el-option v-for="store in storeOptions" :key="store.id || store.F_Id"
                            :label="store.fullName || store.dm || store.name" :value="store.id || store.F_Id" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                    <el-button icon="el-icon-refresh-right" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 统计卡片区域 -->
        <el-row :gutter="20" class="stat-cards-section">
            <el-col :xs="24" :sm="12" :md="6">
                <div class="stat-card income-card">
                    <div class="stat-icon">
                        <i class="el-icon-coin"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-label">总收入</div>
                        <div class="stat-value">{{ formatCurrency(totalIncome) }}</div>
                        <div class="stat-meta">
                            <span>{{ totalBillingCount }} 笔订单</span>
                        </div>
                    </div>
                </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6">
                <div class="stat-card channel-card">
                    <div class="stat-icon">
                        <i class="el-icon-credit-card"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-label">收款渠道收入</div>
                        <div class="stat-value">{{ formatCurrency(channelIncome) }}</div>
                        <div class="stat-meta">
                            <span>{{ channelCount }} 个渠道</span>
                        </div>
                    </div>
                </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6">
                <div class="stat-card payable-card">
                    <div class="stat-icon">
                        <i class="el-icon-shopping-cart-2"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-label">合作机构应付</div>
                        <div class="stat-value">{{ formatCurrency(cooperationPayable) }}</div>
                        <div class="stat-meta">
                            <span>{{ cooperationCount }} 个机构</span>
                        </div>
                    </div>
                </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6">
                <div class="stat-card receivable-card">
                    <div class="stat-icon">
                        <i class="el-icon-bank-card"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-label">付款医院应收</div>
                        <div class="stat-value">{{ formatCurrency(hospitalReceivable) }}</div>
                        <div class="stat-meta">
                            <span>{{ hospitalCount }} 个医院</span>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>

        <!-- 图表区域 -->
        <el-row :gutter="20" class="charts-section">
            <!-- 总收入趋势图 -->
            <el-col :xs="24" :lg="16">
                <el-card class="chart-card" shadow="hover">
                    <div slot="header" class="chart-header">
                        <span class="chart-title">
                            <i class="el-icon-data-line"></i>
                            门店总收入趋势
                        </span>
                    </div>
                    <div ref="totalIncomeChart" class="chart-container"></div>
                </el-card>
            </el-col>
            <!-- 收款渠道分布饼图 -->
            <el-col :xs="24" :lg="8">
                <el-card class="chart-card" shadow="hover">
                    <div slot="header" class="chart-header">
                        <span class="chart-title">
                            <i class="el-icon-pie-chart"></i>
                            收款渠道分布
                        </span>
                    </div>
                    <div ref="channelPieChart" class="chart-container"></div>
                </el-card>
            </el-col>
        </el-row>

        <el-row :gutter="20" class="charts-section">
            <!-- 合作机构应付趋势 -->
            <el-col :xs="24" :lg="12">
                <el-card class="chart-card" shadow="hover">
                    <div slot="header" class="chart-header">
                        <span class="chart-title">
                            <i class="el-icon-shopping-bag-1"></i>
                            合作机构应付趋势
                        </span>
                    </div>
                    <div ref="payableChart" class="chart-container"></div>
                </el-card>
            </el-col>
            <!-- 付款医院应收趋势 -->
            <el-col :xs="24" :lg="12">
                <el-card class="chart-card" shadow="hover">
                    <div slot="header" class="chart-header">
                        <span class="chart-title">
                            <i class="el-icon-wallet"></i>
                            付款医院应收趋势
                        </span>
                    </div>
                    <div ref="receivableChart" class="chart-container"></div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 数据表格区域 -->
        <el-card class="table-card" shadow="hover">
            <div slot="header" class="table-header">
                <span class="table-title">
                    <i class="el-icon-s-grid"></i>
                    详细数据
                </span>
                <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="table-tabs">
                    <el-tab-pane label="总收入" name="totalIncome"></el-tab-pane>
                    <el-tab-pane label="收款渠道" name="channel"></el-tab-pane>
                    <el-tab-pane label="合作机构应付" name="payable"></el-tab-pane>
                    <el-tab-pane label="付款医院应收" name="receivable"></el-tab-pane>
                </el-tabs>
            </div>
            <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>
        </el-card>
    </div>
</template>

<script>
import * as echarts from 'echarts'
import {
    getStorePaymentChannelIncome,
    getStoreCooperationPayable,
    getStorePaymentHospitalReceivable,
    getStoreTotalIncome
} from '@/api/extend/financialReport'
import { getStoreSelector } from '@/api/extend/store'

export default {
    name: 'FinancialReport',
    data() {
        return {
            // 查询参数
            queryParams: {
                startTime: null,
                endTime: null,
                periodType: 'day',
                storeIds: []
            },
            dateRange: [],
            // 门店选项
            storeOptions: [],
            // 数据加载状态
            loading: false,
            tableLoading: false,
            // 统计数据
            totalIncome: 0,
            totalBillingCount: 0,
            channelIncome: 0,
            channelCount: 0,
            cooperationPayable: 0,
            cooperationCount: 0,
            hospitalReceivable: 0,
            hospitalCount: 0,
            // 原始数据
            totalIncomeData: [],
            channelData: [],
            payableData: [],
            receivableData: [],
            // 图表实例
            totalIncomeChart: null,
            channelPieChart: null,
            payableChart: null,
            receivableChart: null,
            // 表格数据
            activeTab: 'totalIncome',
            tableData: [],
            tableColumns: []
        }
    },
    async mounted() {
        // 初始化默认时间范围
        this.initDefaultDateRange()
        // 加载门店选项
        await this.loadStoreOptions()
        // 初始化图表
        this.$nextTick(() => {
            this.initCharts()
            // 自动加载数据（延迟一下确保图表容器已渲染）
            setTimeout(() => {
                this.handleSearch()
            }, 300)
        })
    },
    beforeDestroy() {
        this.disposeCharts()
    },
    methods: {
        // 初始化默认时间范围（最近30天）
        initDefaultDateRange() {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 30)
            this.dateRange = [
                this.formatDate(start),
                this.formatDate(end)
            ]
            this.handleDateRangeChange(this.dateRange)
        },
        // 格式化日期
        formatDate(date) {
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${year}-${month}-${day}`
        },
        // 日期范围变化
        handleDateRangeChange(val) {
            if (val && val.length === 2) {
                this.queryParams.startTime = val[0] + 'T00:00:00'
                this.queryParams.endTime = val[1] + 'T23:59:59'
            } else {
                this.queryParams.startTime = null
                this.queryParams.endTime = null
            }
        },
        // 加载门店选项
        async loadStoreOptions() {
            try {
                const res = await getStoreSelector()
                console.log('门店接口返回:', res)
                if (res.code === 200) {
                    // 门店接口返回格式：{ list: [...] }
                    const data = (res.data && res.data.list) ? res.data.list : (res.data || [])
                    this.storeOptions = Array.isArray(data) ? data : []
                    console.log('门店选项数量:', this.storeOptions.length)
                    if (this.storeOptions.length === 0) {
                        this.$message.warning('暂无门店数据')
                    }
                } else {
                    this.$message.warning('加载门店列表失败: ' + (res.msg || '未知错误'))
                }
            } catch (error) {
                console.error('加载门店选项失败:', error)
                this.$message.error('加载门店列表失败: ' + (error.message || '未知错误'))
            }
        },
        // 查询
        async handleSearch() {
            if (!this.queryParams.startTime || !this.queryParams.endTime) {
                this.$message.warning('请选择时间范围')
                return
            }
            this.loading = true
            this.tableLoading = true
            try {
                await Promise.all([
                    this.loadTotalIncomeData(),
                    this.loadChannelData(),
                    this.loadPayableData(),
                    this.loadReceivableData()
                ])
                this.$nextTick(() => {
                    this.updateCharts()
                    this.updateTable()
                })
            } catch (error) {
                console.error('加载数据失败:', error)
                this.$message.error('加载数据失败: ' + (error.message || '未知错误'))
            } finally {
                this.loading = false
                this.tableLoading = false
            }
        },
        // 重置
        handleReset() {
            this.initDefaultDateRange()
            this.queryParams.periodType = 'day'
            this.queryParams.storeIds = []
            this.$nextTick(() => {
                this.handleSearch()
            })
        },
        // 加载总收入数据
        async loadTotalIncomeData() {
            try {
                const res = await getStoreTotalIncome(this.queryParams)
                console.log('总收入接口返回:', res)
                if (res.code === 200) {
                    // 后端接口返回的是 List，直接就是数组
                    const data = Array.isArray(res.data) ? res.data : []
                    console.log('总收入数据:', data)
                    this.totalIncome = data.reduce((sum, item) => sum + (item.totalIncome || 0), 0)
                    this.totalBillingCount = data.reduce((sum, item) => sum + (item.billingCount || 0), 0)
                    this.totalIncomeData = data
                    console.log('总收入汇总:', this.totalIncome, '笔数:', this.totalBillingCount)
                } else {
                    console.error('总收入接口返回错误:', res.msg)
                    this.totalIncomeData = []
                }
            } catch (error) {
                console.error('加载总收入数据失败:', error)
                this.totalIncomeData = []
            }
        },
        // 加载收款渠道数据
        async loadChannelData() {
            try {
                const res = await getStorePaymentChannelIncome(this.queryParams)
                console.log('收款渠道接口返回:', res)
                if (res.code === 200) {
                    const data = Array.isArray(res.data) ? res.data : []
                    console.log('收款渠道数据:', data)
                    let totalChannelIncome = 0
                    const channelSet = new Set()
                    data.forEach(store => {
                        totalChannelIncome += store.totalIncome || 0
                        if (store.paymentChannels && Array.isArray(store.paymentChannels)) {
                            store.paymentChannels.forEach(ch => {
                                channelSet.add(ch.paymentMethod)
                            })
                        }
                    })
                    this.channelIncome = totalChannelIncome
                    this.channelCount = channelSet.size
                    this.channelData = data
                    console.log('收款渠道汇总:', this.channelIncome, '渠道数:', this.channelCount)
                } else {
                    console.error('收款渠道接口返回错误:', res.msg)
                    this.channelData = []
                }
            } catch (error) {
                console.error('加载收款渠道数据失败:', error)
                this.channelData = []
            }
        },
        // 加载合作机构应付数据
        async loadPayableData() {
            try {
                const res = await getStoreCooperationPayable(this.queryParams)
                console.log('合作机构应付接口返回:', res)
                if (res.code === 200) {
                    const data = Array.isArray(res.data) ? res.data : []
                    console.log('合作机构应付数据:', data)
                    let totalPayable = 0
                    const cooperationSet = new Set()
                    data.forEach(store => {
                        totalPayable += store.totalPayable || 0
                        if (store.cooperationItems && Array.isArray(store.cooperationItems)) {
                            store.cooperationItems.forEach(item => {
                                cooperationSet.add(item.cooperationId)
                            })
                        }
                    })
                    this.cooperationPayable = totalPayable
                    this.cooperationCount = cooperationSet.size
                    this.payableData = data
                    console.log('合作机构应付汇总:', this.cooperationPayable, '机构数:', this.cooperationCount)
                } else {
                    console.error('合作机构应付接口返回错误:', res.msg)
                    this.payableData = []
                }
            } catch (error) {
                console.error('加载合作机构应付数据失败:', error)
                this.payableData = []
            }
        },
        // 加载付款医院应收数据
        async loadReceivableData() {
            try {
                const res = await getStorePaymentHospitalReceivable(this.queryParams)
                console.log('付款医院应收接口返回:', res)
                if (res.code === 200) {
                    const data = Array.isArray(res.data) ? res.data : []
                    console.log('付款医院应收数据:', data)
                    let totalReceivable = 0
                    const hospitalSet = new Set()
                    data.forEach(store => {
                        totalReceivable += store.totalReceivable || 0
                        if (store.hospitalItems && Array.isArray(store.hospitalItems)) {
                            store.hospitalItems.forEach(item => {
                                hospitalSet.add(item.hospitalId)
                            })
                        }
                    })
                    this.hospitalReceivable = totalReceivable
                    this.hospitalCount = hospitalSet.size
                    this.receivableData = data
                    console.log('付款医院应收汇总:', this.hospitalReceivable, '医院数:', this.hospitalCount)
                } else {
                    console.error('付款医院应收接口返回错误:', res.msg)
                    this.receivableData = []
                }
            } catch (error) {
                console.error('加载付款医院应收数据失败:', error)
                this.receivableData = []
            }
        },
        // 初始化图表
        initCharts() {
            this.initTotalIncomeChart()
            this.initChannelPieChart()
            this.initPayableChart()
            this.initReceivableChart()
        },
        // 初始化总收入趋势图
        initTotalIncomeChart() {
            if (!this.$refs.totalIncomeChart) return
            if (this.totalIncomeChart) {
                this.totalIncomeChart.dispose()
            }
            this.totalIncomeChart = echarts.init(this.$refs.totalIncomeChart)
            window.addEventListener('resize', () => {
                if (this.totalIncomeChart) {
                    this.totalIncomeChart.resize()
                }
            })
        },
        // 初始化收款渠道饼图
        initChannelPieChart() {
            if (!this.$refs.channelPieChart) return
            if (this.channelPieChart) {
                this.channelPieChart.dispose()
            }
            this.channelPieChart = echarts.init(this.$refs.channelPieChart)
            window.addEventListener('resize', () => {
                if (this.channelPieChart) {
                    this.channelPieChart.resize()
                }
            })
        },
        // 初始化应付趋势图
        initPayableChart() {
            if (!this.$refs.payableChart) return
            if (this.payableChart) {
                this.payableChart.dispose()
            }
            this.payableChart = echarts.init(this.$refs.payableChart)
            window.addEventListener('resize', () => {
                if (this.payableChart) {
                    this.payableChart.resize()
                }
            })
        },
        // 初始化应收趋势图
        initReceivableChart() {
            if (!this.$refs.receivableChart) return
            if (this.receivableChart) {
                this.receivableChart.dispose()
            }
            this.receivableChart = echarts.init(this.$refs.receivableChart)
            window.addEventListener('resize', () => {
                if (this.receivableChart) {
                    this.receivableChart.resize()
                }
            })
        },
        // 更新所有图表
        updateCharts() {
            this.$nextTick(() => {
                this.updateTotalIncomeChart()
                this.updateChannelPieChart()
                this.updatePayableChart()
                this.updateReceivableChart()
            })
        },
        // 更新总收入趋势图
        updateTotalIncomeChart() {
            if (!this.totalIncomeChart) {
                console.warn('总收入图表实例不存在')
                return
            }
            if (!this.totalIncomeData || this.totalIncomeData.length === 0) {
                console.warn('总收入数据为空')
                this.totalIncomeChart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'middle',
                        textStyle: {
                            color: '#999',
                            fontSize: 16
                        }
                    }
                })
                return
            }

            // 按日期聚合数据
            const dateMap = new Map()
            this.totalIncomeData.forEach(item => {
                const date = item.periodDate
                const income = item.totalIncome || 0
                if (dateMap.has(date)) {
                    dateMap.set(date, dateMap.get(date) + income)
                } else {
                    dateMap.set(date, income)
                }
            })

            const dates = Array.from(dateMap.keys()).sort()
            const values = dates.map(date => dateMap.get(date))

            console.log('总收入图表数据 - 日期:', dates, '金额:', values)

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: (params) => {
                        const param = params[0]
                        return `${param.axisValue}<br/>${param.seriesName}: ${this.formatCurrency(param.value)}`
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisLine: { lineStyle: { color: '#E0E6F1' } },
                    axisLabel: { color: '#666', rotate: 45 }
                },
                yAxis: {
                    type: 'value',
                    axisLine: { lineStyle: { color: '#E0E6F1' } },
                    axisLabel: {
                        color: '#666',
                        formatter: (value) => {
                            if (value >= 10000) {
                                return (value / 10000).toFixed(1) + '万'
                            }
                            return value
                        }
                    },
                    splitLine: { lineStyle: { color: '#F0F0F0' } }
                },
                series: [{
                    name: '总收入',
                    type: 'line',
                    smooth: true,
                    data: values,
                    itemStyle: { color: '#409EFF' },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                { offset: 0, color: 'rgba(64,158,255,0.3)' },
                                { offset: 1, color: 'rgba(64,158,255,0.1)' }
                            ]
                        }
                    }
                }]
            }
            this.totalIncomeChart.setOption(option, true)
            // 确保图表大小正确
            setTimeout(() => {
                if (this.totalIncomeChart) {
                    this.totalIncomeChart.resize()
                }
            }, 100)
        },
        // 更新收款渠道饼图
        updateChannelPieChart() {
            if (!this.channelPieChart) {
                console.warn('收款渠道图表实例不存在')
                return
            }
            if (!this.channelData || this.channelData.length === 0) {
                console.warn('收款渠道数据为空')
                this.channelPieChart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'middle',
                        textStyle: {
                            color: '#999',
                            fontSize: 16
                        }
                    }
                })
                return
            }

            // 按渠道聚合数据
            const channelMap = new Map()
            this.channelData.forEach(store => {
                if (store.paymentChannels && Array.isArray(store.paymentChannels)) {
                    store.paymentChannels.forEach(ch => {
                        const method = ch.paymentMethod || '未填写'
                        const amount = ch.amount || 0
                        if (channelMap.has(method)) {
                            channelMap.set(method, channelMap.get(method) + amount)
                        } else {
                            channelMap.set(method, amount)
                        }
                    })
                }
            })

            const data = Array.from(channelMap.entries()).map(([name, value]) => ({
                name,
                value
            }))

            console.log('收款渠道图表数据:', data)

            if (data.length === 0) {
                this.channelPieChart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'middle',
                        textStyle: {
                            color: '#999',
                            fontSize: 16
                        }
                    }
                })
                return
            }

            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}: {d}%'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '16',
                            fontWeight: 'bold'
                        }
                    },
                    data: data
                }]
            }
            this.channelPieChart.setOption(option, true)
            setTimeout(() => {
                if (this.channelPieChart) {
                    this.channelPieChart.resize()
                }
            }, 100)
        },
        // 更新应付趋势图
        updatePayableChart() {
            if (!this.payableChart) {
                console.warn('应付图表实例不存在')
                return
            }
            if (!this.payableData || this.payableData.length === 0) {
                console.warn('应付数据为空')
                this.payableChart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'middle',
                        textStyle: {
                            color: '#999',
                            fontSize: 16
                        }
                    }
                })
                return
            }

            const dateMap = new Map()
            this.payableData.forEach(item => {
                const date = item.periodDate
                const amount = item.totalPayable || 0
                if (dateMap.has(date)) {
                    dateMap.set(date, dateMap.get(date) + amount)
                } else {
                    dateMap.set(date, amount)
                }
            })

            const dates = Array.from(dateMap.keys()).sort()
            const values = dates.map(date => dateMap.get(date))

            console.log('应付图表数据 - 日期:', dates, '金额:', values)

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: (params) => {
                        const param = params[0]
                        return `${param.axisValue}<br/>${param.seriesName}: ${this.formatCurrency(param.value)}`
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisLine: { lineStyle: { color: '#E0E6F1' } },
                    axisLabel: { color: '#666', rotate: 45 }
                },
                yAxis: {
                    type: 'value',
                    axisLine: { lineStyle: { color: '#E0E6F1' } },
                    axisLabel: {
                        color: '#666',
                        formatter: (value) => {
                            if (value >= 10000) {
                                return (value / 10000).toFixed(1) + '万'
                            }
                            return value
                        }
                    },
                    splitLine: { lineStyle: { color: '#F0F0F0' } }
                },
                series: [{
                    name: '应付金额',
                    type: 'bar',
                    data: values,
                    itemStyle: { color: '#E6A23C' }
                }]
            }
            this.payableChart.setOption(option, true)
            setTimeout(() => {
                if (this.payableChart) {
                    this.payableChart.resize()
                }
            }, 100)
        },
        // 更新应收趋势图
        updateReceivableChart() {
            if (!this.receivableChart) {
                console.warn('应收图表实例不存在')
                return
            }
            if (!this.receivableData || this.receivableData.length === 0) {
                console.warn('应收数据为空')
                this.receivableChart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'middle',
                        textStyle: {
                            color: '#999',
                            fontSize: 16
                        }
                    }
                })
                return
            }

            const dateMap = new Map()
            this.receivableData.forEach(item => {
                const date = item.periodDate
                const amount = item.totalReceivable || 0
                if (dateMap.has(date)) {
                    dateMap.set(date, dateMap.get(date) + amount)
                } else {
                    dateMap.set(date, amount)
                }
            })

            const dates = Array.from(dateMap.keys()).sort()
            const values = dates.map(date => dateMap.get(date))

            console.log('应收图表数据 - 日期:', dates, '金额:', values)

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: (params) => {
                        const param = params[0]
                        return `${param.axisValue}<br/>${param.seriesName}: ${this.formatCurrency(param.value)}`
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisLine: { lineStyle: { color: '#E0E6F1' } },
                    axisLabel: { color: '#666', rotate: 45 }
                },
                yAxis: {
                    type: 'value',
                    axisLine: { lineStyle: { color: '#E0E6F1' } },
                    axisLabel: {
                        color: '#666',
                        formatter: (value) => {
                            if (value >= 10000) {
                                return (value / 10000).toFixed(1) + '万'
                            }
                            return value
                        }
                    },
                    splitLine: { lineStyle: { color: '#F0F0F0' } }
                },
                series: [{
                    name: '应收金额',
                    type: 'bar',
                    data: values,
                    itemStyle: { color: '#67C23A' }
                }]
            }
            this.receivableChart.setOption(option, true)
            setTimeout(() => {
                if (this.receivableChart) {
                    this.receivableChart.resize()
                }
            }, 100)
        },
        // 销毁图表
        disposeCharts() {
            if (this.totalIncomeChart) {
                this.totalIncomeChart.dispose()
                this.totalIncomeChart = null
            }
            if (this.channelPieChart) {
                this.channelPieChart.dispose()
                this.channelPieChart = null
            }
            if (this.payableChart) {
                this.payableChart.dispose()
                this.payableChart = null
            }
            if (this.receivableChart) {
                this.receivableChart.dispose()
                this.receivableChart = null
            }
        },
        // 切换表格Tab
        handleTabClick(tab) {
            this.updateTable()
        },
        // 更新表格数据
        updateTable() {
            this.tableLoading = true
            setTimeout(() => {
                switch (this.activeTab) {
                    case 'totalIncome':
                        this.updateTotalIncomeTable()
                        break
                    case 'channel':
                        this.updateChannelTable()
                        break
                    case 'payable':
                        this.updatePayableTable()
                        break
                    case 'receivable':
                        this.updateReceivableTable()
                        break
                }
                this.tableLoading = false
            }, 100)
        },
        // 更新总收入表格
        updateTotalIncomeTable() {
            if (!this.totalIncomeData) {
                this.tableData = []
                return
            }
            this.tableColumns = [
                { prop: 'storeName', label: '门店名称', width: 150 },
                { prop: 'periodDate', label: '统计日期', width: 120 },
                {
                    prop: 'totalIncome',
                    label: '总收入',
                    width: 150,
                    formatter: (row) => this.formatCurrency(row.totalIncome)
                },
                { prop: 'billingCount', label: '开单笔数', width: 120 },
                {
                    prop: 'averageAmount',
                    label: '平均单笔',
                    width: 150,
                    formatter: (row) => this.formatCurrency(row.averageAmount)
                }
            ]
            this.tableData = this.totalIncomeData.map(item => ({
                ...item,
                averageAmount: item.billingCount > 0 ? item.totalIncome / item.billingCount : 0
            }))
        },
        // 更新收款渠道表格
        updateChannelTable() {
            if (!this.channelData) {
                this.tableData = []
                return
            }
            this.tableColumns = [
                { prop: 'storeName', label: '门店名称', width: 150 },
                { prop: 'periodDate', label: '统计日期', width: 120 },
                { prop: 'paymentMethod', label: '付款方式', width: 120 },
                {
                    prop: 'amount',
                    label: '收款金额',
                    width: 150,
                    formatter: (row) => this.formatCurrency(row.amount)
                },
                { prop: 'count', label: '笔数', width: 100 },
                {
                    prop: 'percentage',
                    label: '占比',
                    width: 100,
                    formatter: (row) => (row.percentage || 0) + '%'
                }
            ]
            const list = []
            this.channelData.forEach(store => {
                if (store.paymentChannels) {
                    store.paymentChannels.forEach(ch => {
                        list.push({
                            storeName: store.storeName,
                            periodDate: store.periodDate,
                            paymentMethod: ch.paymentMethod,
                            amount: ch.amount,
                            count: ch.count,
                            percentage: ch.percentage
                        })
                    })
                }
            })
            this.tableData = list
        },
        // 更新应付表格
        updatePayableTable() {
            if (!this.payableData) {
                this.tableData = []
                return
            }
            this.tableColumns = [
                { prop: 'storeName', label: '门店名称', width: 150 },
                { prop: 'periodDate', label: '统计日期', width: 120 },
                { prop: 'cooperationName', label: '合作机构', width: 200 },
                {
                    prop: 'payableAmount',
                    label: '应付金额',
                    width: 150,
                    formatter: (row) => this.formatCurrency(row.payableAmount)
                },
                { prop: 'billingCount', label: '开单笔数', width: 120 }
            ]
            const list = []
            this.payableData.forEach(store => {
                if (store.cooperationItems) {
                    store.cooperationItems.forEach(item => {
                        list.push({
                            storeName: store.storeName,
                            periodDate: store.periodDate,
                            cooperationName: item.cooperationName,
                            payableAmount: item.payableAmount,
                            billingCount: item.billingCount
                        })
                    })
                }
            })
            this.tableData = list
        },
        // 更新应收表格
        updateReceivableTable() {
            if (!this.receivableData) {
                this.tableData = []
                return
            }
            this.tableColumns = [
                { prop: 'storeName', label: '门店名称', width: 150 },
                { prop: 'periodDate', label: '统计日期', width: 120 },
                { prop: 'hospitalName', label: '付款医院', width: 200 },
                {
                    prop: 'receivableAmount',
                    label: '应收金额',
                    width: 150,
                    formatter: (row) => this.formatCurrency(row.receivableAmount)
                },
                { prop: 'billingCount', label: '开单笔数', width: 120 }
            ]
            const list = []
            this.receivableData.forEach(store => {
                if (store.hospitalItems) {
                    store.hospitalItems.forEach(item => {
                        list.push({
                            storeName: store.storeName,
                            periodDate: store.periodDate,
                            hospitalName: item.hospitalName,
                            receivableAmount: item.receivableAmount,
                            billingCount: item.billingCount
                        })
                    })
                }
            })
            this.tableData = list
        },
        // 格式化货币
        formatCurrency(value) {
            if (value === null || value === undefined) return '¥0.00'
            const num = Number(value)
            if (isNaN(num)) return '¥0.00'
            return '¥' + num.toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.financial-report-container {
    padding: 20px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    min-height: calc(100vh - 84px);

    // 筛选卡片
    .search-card {
        margin-bottom: 20px;
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);

        .search-form {
            ::v-deep .el-form-item {
                margin-bottom: 0;
            }
        }
    }

    // 统计卡片区域
    .stat-cards-section {
        margin-bottom: 20px;

        .stat-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 24px;
            display: flex;
            align-items: center;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            cursor: pointer;
            border: 1px solid rgba(255, 255, 255, 0.8);

            &:hover {
                transform: translateY(-4px);
                box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
            }

            .stat-icon {
                width: 64px;
                height: 64px;
                border-radius: 12px;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 20px;
                font-size: 32px;
                flex-shrink: 0;
            }

            .stat-content {
                flex: 1;
                min-width: 0;

                .stat-label {
                    font-size: 14px;
                    color: #666;
                    margin-bottom: 8px;
                    font-weight: 500;
                }

                .stat-value {
                    font-size: 24px;
                    font-weight: 700;
                    color: #0f172a;
                    margin-bottom: 4px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .stat-meta {
                    font-size: 12px;
                    color: #999;
                }
            }

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

            &.channel-card .stat-icon {
                background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
                color: #fff;
            }

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

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

    // 图表区域
    .charts-section {
        margin-bottom: 20px;

        .chart-card {
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            transition: all 0.3s ease;

            &:hover {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
            }

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

                .chart-title {
                    font-size: 16px;
                    font-weight: 600;
                    color: #0f172a;
                    display: flex;
                    align-items: center;
                    gap: 8px;

                    i {
                        font-size: 18px;
                        color: #409EFF;
                    }
                }
            }

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

    // 表格卡片
    .table-card {
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);

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

            .table-title {
                font-size: 16px;
                font-weight: 600;
                color: #0f172a;
                display: flex;
                align-items: center;
                gap: 8px;

                i {
                    font-size: 18px;
                    color: #409EFF;
                }
            }

            .table-tabs {
                ::v-deep .el-tabs__header {
                    margin: 0;
                }

                ::v-deep .el-tabs__item {
                    font-weight: 500;
                }
            }
        }

        .data-table {
            margin-top: 20px;
        }
    }
}

// 响应式适配
@media (max-width: 768px) {
    .financial-report-container {
        padding: 12px;

        .stat-cards-section {
            .stat-card {
                padding: 16px;

                .stat-icon {
                    width: 48px;
                    height: 48px;
                    font-size: 24px;
                    margin-right: 12px;
                }

                .stat-content {
                    .stat-value {
                        font-size: 20px;
                    }
                }
            }
        }

        .chart-card {
            .chart-container {
                height: 280px;
                min-height: 280px;
            }
        }
    }
}
</style>
