<template>
    <div class="tk-dashboard-container">
        <!-- 页面头部区域 -->
        <div class="dashboard-header">
            <div class="page-header">
                <div class="header-content">
                    <h1>
                        <i class="el-icon-data-analysis"></i>
                        拓客决策指挥中心
                    </h1>
                    <div class="header-actions">
                        <div class="filter-item">
                            <span class="filter-label">时间范围：</span>
                            <el-date-picker v-model="dateRange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" size="small"
                                :picker-options="pickerOptions" @change="handleDateChange">
                            </el-date-picker>
                        </div>
                        <div class="filter-item">
                            <span class="filter-label">拓客活动：</span>
                            <el-select v-model="queryParams.eventId" placeholder="请输入活动名称或编号搜索" clearable filterable
                                remote reserve-keyword size="small" class="filter-select" @change="handleEventChange"
                                :remote-method="remoteSearchEvent" :loading="eventListLoading">
                                <el-option v-for="item in filteredEventList" :key="item.id || item.Id"
                                    :label="item.eventName || item.EventName || item.name || item.Name"
                                    :value="item.id || item.Id">
                                </el-option>
                            </el-select>
                        </div>
                        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery"
                            :loading="loading" class="modern-search-btn">查询</el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container" v-loading="loading" element-loading-text="正在分析数据..."></div>

        <!-- 主要内容区域 -->
        <div v-else class="dashboard-content">
            <!-- 核心指标概览 - KPI卡片 -->
            <div class="kpi-grid" v-if="overviewData">
                <el-row :gutter="16">
                    <el-col :span="6" v-for="item in kpiList" :key="item.key">
                        <el-card shadow="hover" class="kpi-card" :class="item.type">
                            <div class="kpi-content">
                                <div class="kpi-icon-wrapper" :class="item.type">
                                    <i :class="item.icon"></i>
                                </div>
                                <div class="kpi-info">
                                    <div class="kpi-label">{{ item.label }}</div>
                                    <div class="kpi-value">
                                        <span v-if="item.isMoney">¥</span>
                                        {{ item.value }}
                                    </div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- 图表区域 - 第一排 -->
            <el-row :gutter="16" class="chart-row">
                <el-col :span="8">
                    <el-card shadow="hover" class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="title"><i class="el-icon-s-data"></i> 拓客转化漏斗</span>
                        </div>
                        <div ref="funnelChart" class="chart-container"></div>
                    </el-card>
                </el-col>
                <el-col :span="8">
                    <el-card shadow="hover" class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="title"><i class="el-icon-time"></i> 到店转化时效</span>
                        </div>
                        <div ref="visitChart" class="chart-container"></div>
                    </el-card>
                </el-col>
                <el-col :span="8">
                    <el-card shadow="hover" class="chart-card">
                        <div slot="header" class="chart-header">
                            <span class="title"><i class="el-icon-s-marketing"></i> 大单统计</span>
                            <el-tag size="mini" type="danger" effect="plain">业绩 > 10000</el-tag>
                        </div>
                        <div class="big-order-summary">
                            <div class="bo-item">
                                <div class="label">大单总数</div>
                                <div class="value primary">{{ bigOrderStats.count || 0 }}</div>
                            </div>
                            <div class="bo-item">
                                <div class="label">大单金额</div>
                                <div class="value success">¥{{ formatMoney(bigOrderStats.amount) }}</div>
                            </div>
                            <div class="bo-item">
                                <div class="label">占比</div>
                                <div class="value warning">{{ bigOrderStats.rate || 0 }}%</div>
                            </div>
                        </div>
                        <div class="big-order-list">
                            <el-table :data="bigOrderDetailList" height="200" style="width: 100%" size="mini"
                                :show-header="false">
                                <el-table-column prop="CustomerName" width="80">
                                    <template slot-scope="scope">{{ scope.row.CustomerName || scope.row.customerName ||
                                        '-' }}</template>
                                </el-table-column>
                                <el-table-column prop="BillingAmount" align="right">
                                    <template slot-scope="scope">
                                        <span class="money">¥{{ formatMoney(scope.row.BillingAmount ||
                                            scope.row.billingAmount || 0) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="StoreName" show-overflow-tooltip align="right">
                                    <template slot-scope="scope">{{ scope.row.StoreName || scope.row.storeName || '-'
                                    }}</template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <!-- 图表区域 - 第二排：排行榜 -->
            <el-row :gutter="16" class="ranking-row">
                <el-col :span="12">
                    <el-card shadow="hover" class="ranking-card">
                        <div slot="header" class="card-header">
                            <span class="title"><i class="el-icon-medal"></i> 员工拓客排行榜 (Top 10)</span>
                            <el-button type="text" size="small"
                                @click="activeTab = 'staff'; scrollToTable()">查看全部</el-button>
                        </div>
                        <div class="ranking-table-wrapper">
                            <el-table :data="staffRankingList" style="width: 100%" size="small" stripe>
                                <el-table-column type="index" label="排名" width="60" align="center">
                                    <template slot-scope="scope">
                                        <span class="rank-badge" :class="getRankClass(scope.$index + 1)">
                                            {{ scope.$index + 1 }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" label="姓名" min-width="100" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="count" label="拓客数" width="100" align="right">
                                    <template slot-scope="scope">
                                        <span class="rank-value">{{ scope.row.count }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="12">
                    <el-card shadow="hover" class="ranking-card">
                        <div slot="header" class="card-header">
                            <span class="title"><i class="el-icon-office-building"></i> 门店拓客排行榜 (Top 10)</span>
                            <el-button type="text" size="small"
                                @click="activeTab = 'store'; scrollToTable()">查看全部</el-button>
                        </div>
                        <div class="ranking-table-wrapper">
                            <el-table :data="storeRankingList" style="width: 100%" size="small" stripe>
                                <el-table-column type="index" label="排名" width="60" align="center">
                                    <template slot-scope="scope">
                                        <span class="rank-badge" :class="getRankClass(scope.$index + 1)">
                                            {{ scope.$index + 1 }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" label="门店名称" min-width="150" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="count" label="拓客数" width="100" align="right">
                                    <template slot-scope="scope">
                                        <span class="rank-value">{{ scope.row.count }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <!-- 流失节点分析区域 -->
            <el-row :gutter="16" class="loss-node-row" v-if="lossNodeData">
                <el-col :span="24">
                    <el-card shadow="hover" class="loss-node-card">
                        <div slot="header" class="card-header">
                            <span class="title"><i class="el-icon-warning-outline"></i> 流失节点分析</span>
                        </div>
                        <div class="loss-node-content">
                            <!-- 各节点人数统计 -->
                            <div class="node-count-section">
                                <div class="section-title">转化链路各节点人数</div>
                                <div class="node-count-list">
                                    <div class="node-item">
                                        <div class="node-label">拓客</div>
                                        <div class="node-value">{{ nodeCountData.expansionCount }}</div>
                                    </div>
                                    <div class="node-arrow">→</div>
                                    <div class="node-item">
                                        <div class="node-label">邀约</div>
                                        <div class="node-value">{{ nodeCountData.inviteCount }}</div>
                                    </div>
                                    <div class="node-arrow">→</div>
                                    <div class="node-item">
                                        <div class="node-label">预约</div>
                                        <div class="node-value">{{ nodeCountData.appointmentCount }}</div>
                                    </div>
                                    <div class="node-arrow">→</div>
                                    <div class="node-item">
                                        <div class="node-label">到店</div>
                                        <div class="node-value">{{ nodeCountData.visitCount }}</div>
                                    </div>
                                    <div class="node-arrow">→</div>
                                    <div class="node-item">
                                        <div class="node-label">开单</div>
                                        <div class="node-value">{{ nodeCountData.billingCount }}</div>
                                    </div>
                                </div>
                            </div>

                            <!-- 流失节点统计卡片 -->
                            <div class="loss-node-cards">
                                <div class="section-title">流失节点统计</div>
                                <el-row :gutter="16">
                                    <el-col :span="6" v-for="node in lossNodeList" :key="node.nodeIndex">
                                        <el-card shadow="hover" class="loss-node-card-item"
                                            :class="'loss-node-' + node.nodeIndex">
                                            <div class="loss-card-content">
                                                <div class="loss-card-title">{{ node.nodeName }}</div>
                                                <div class="loss-card-value">{{ node.lossCount }}</div>
                                                <div class="loss-card-rate">
                                                    <span class="rate-label">流失率：</span>
                                                    <span class="rate-value">{{ node.lossRate }}%</span>
                                                </div>
                                                <div class="loss-card-percentage">
                                                    <span class="percentage-label">占比：</span>
                                                    <span class="percentage-value">{{ node.lossPercentage }}%</span>
                                                </div>
                                            </div>
                                        </el-card>
                                    </el-col>
                                </el-row>
                            </div>

                            <!-- 转化率统计 -->
                            <div class="conversion-rate-section">
                                <div class="section-title">转化率统计</div>
                                <el-row :gutter="16">
                                    <el-col :span="6">
                                        <div class="rate-item">
                                            <div class="rate-label">拓客→邀约</div>
                                            <div class="rate-value">{{ conversionRate.expansionToInvite }}%</div>
                                        </div>
                                    </el-col>
                                    <el-col :span="6">
                                        <div class="rate-item">
                                            <div class="rate-label">邀约→预约</div>
                                            <div class="rate-value">{{ conversionRate.inviteToAppointment }}%</div>
                                        </div>
                                    </el-col>
                                    <el-col :span="6">
                                        <div class="rate-item">
                                            <div class="rate-label">预约→到店</div>
                                            <div class="rate-value">{{ conversionRate.appointmentToVisit }}%</div>
                                        </div>
                                    </el-col>
                                    <el-col :span="6">
                                        <div class="rate-item">
                                            <div class="rate-label">到店→开单</div>
                                            <div class="rate-value">{{ conversionRate.visitToBilling }}%</div>
                                        </div>
                                    </el-col>
                                </el-row>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <!-- 详细数据明细 -->
            <el-row :gutter="16" class="table-row" id="detailTable">
                <el-col :span="24">
                    <el-card shadow="hover" class="table-card">
                        <el-tabs v-model="activeTab">
                            <el-tab-pane label="全员战报明细" name="staff">
                                <el-table :data="employeeList" style="width: 100%" height="500" stripe border
                                    size="small" v-loading="loading">
                                    <el-table-column type="index" label="排名" width="60"
                                        align="center"></el-table-column>
                                    <el-table-column prop="EmployeeName" label="姓名" width="100" show-overflow-tooltip>
                                        <template slot-scope="scope">{{ scope.row.EmployeeName || scope.row.employeeName
                                            || '-' }}</template>
                                    </el-table-column>
                                    <el-table-column prop="StoreName" label="所属门店" width="150" show-overflow-tooltip>
                                        <template slot-scope="scope">{{ scope.row.StoreName || scope.row.storeName ||
                                            '-' }}</template>
                                    </el-table-column>
                                    <el-table-column prop="ExpansionCount" label="拓客数" align="center" sortable>
                                        <template slot-scope="scope">{{ scope.row.ExpansionCount ||
                                            scope.row.expansionCount || 0 }}</template>
                                    </el-table-column>
                                    <el-table-column prop="VisitCount" label="到店数" align="center" sortable>
                                        <template slot-scope="scope">{{ scope.row.VisitCount || scope.row.visitCount ||
                                            0 }}</template>
                                    </el-table-column>
                                    <el-table-column prop="VisitRate" label="到店率" align="center" sortable>
                                        <template slot-scope="scope">{{ Number(scope.row.VisitRate ||
                                            scope.row.visitRate || 0).toFixed(2) }}%</template>
                                    </el-table-column>
                                    <el-table-column prop="BillingCount" label="开单数" align="center" sortable>
                                        <template slot-scope="scope">{{ scope.row.BillingCount || scope.row.billingCount
                                            || 0 }}</template>
                                    </el-table-column>
                                    <el-table-column prop="BillingAmount" label="开单金额" align="center" sortable
                                        width="120">
                                        <template slot-scope="scope">¥{{ formatMoney(scope.row.BillingAmount ||
                                            scope.row.billingAmount || 0)
                                        }}</template>
                                    </el-table-column>
                                    <el-table-column prop="BigOrderCount" label="大单数" align="center" sortable>
                                        <template slot-scope="scope">{{ scope.row.BigOrderCount ||
                                            scope.row.bigOrderCount || 0 }}</template>
                                    </el-table-column>
                                </el-table>
                            </el-tab-pane>
                            <el-tab-pane label="门店战报明细" name="store">
                                <el-table :data="storeList" style="width: 100%" height="500" stripe border size="small"
                                    v-loading="loading">
                                    <el-table-column type="index" label="排名" width="60"
                                        align="center"></el-table-column>
                                    <el-table-column prop="StoreName" label="门店名称" width="200" show-overflow-tooltip>
                                        <template slot-scope="scope">{{ scope.row.StoreName || scope.row.storeName ||
                                            '-' }}</template>
                                    </el-table-column>
                                    <el-table-column prop="ExpansionCount" label="拓客数" align="center" sortable>
                                        <template slot-scope="scope">{{ scope.row.ExpansionCount ||
                                            scope.row.expansionCount || 0 }}</template>
                                    </el-table-column>
                                    <el-table-column prop="VisitCount" label="到店数" align="center" sortable>
                                        <template slot-scope="scope">{{ scope.row.VisitCount || scope.row.visitCount ||
                                            0 }}</template>
                                    </el-table-column>
                                    <el-table-column prop="VisitRate" label="到店率" align="center" sortable>
                                        <template slot-scope="scope">{{ Number(scope.row.VisitRate ||
                                            scope.row.visitRate || 0).toFixed(2) }}%</template>
                                    </el-table-column>
                                    <el-table-column prop="AverageVisitInterval" label="平均到店间隔(天)" align="center"
                                        sortable>
                                        <template slot-scope="scope">{{ scope.row.AverageVisitInterval ||
                                            scope.row.averageVisitInterval || '-'
                                        }}</template>
                                    </el-table-column>
                                </el-table>
                            </el-tab-pane>
                        </el-tabs>
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import {
    getDashboardOverview,
    getBigOrderStatistics,
    getEmployeeParticipationStatistics,
    getVisitConversionAnalysis,
    getFunnelDataForDashboard,
    getLossNodeAnalysis
} from '@/api/lqTkDashboard'
import { getLqEventList as getEventList } from '@/api/extend/lqevent'

export default {
    name: 'LqTkDashboard',
    data() {
        return {
            loading: false,
            dateRange: [],
            queryParams: {
                eventId: '',
                startTime: '',
                endTime: ''
            },
            eventList: [],
            filteredEventList: [],
            eventListLoading: false,
            eventSearchTimer: null,
            selectedEvent: null, // 保存当前选中的活动信息
            overviewData: null,
            bigOrderStats: {},
            bigOrderDetailList: [],
            visitAnalysisData: null,
            employeeList: [],
            storeList: [],
            funnelData: null,
            lossNodeData: null, // 流失节点分析数据
            charts: {
                funnel: null,
                visit: null
            },
            activeTab: 'staff',
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            }
        }
    },
    computed: {
        kpiList() {
            const d = this.overviewData || {};
            // 兼容大小写
            const totalBillingAmount = Number(d.TotalBillingAmount || d.totalBillingAmount || 0);
            const totalTkCount = Number(d.TotalExpansionCount || d.totalExpansionCount || d.TotalTkCount || d.totalTkCount || 0);
            const totalVisitCount = Number(d.TotalVisitCount || d.totalVisitCount || 0);
            const overallVisitRate = Number(d.OverallVisitRate || d.overallVisitRate || d.VisitRate || d.visitRate || 0);

            return [
                { key: 'billing', label: '总业绩', value: this.formatMoney(totalBillingAmount), icon: 'el-icon-wallet', type: 'primary', isMoney: true },
                { key: 'tk', label: '总拓客数', value: totalTkCount, icon: 'el-icon-user-solid', type: 'success' },
                { key: 'visit', label: '总到店数', value: totalVisitCount, icon: 'el-icon-location', type: 'warning' },
                { key: 'rate', label: '整体到店率', value: overallVisitRate.toFixed(2) + '%', icon: 'el-icon-pie-chart', type: 'info' }
            ]
        },
        hasData() {
            return !!this.overviewData;
        },
        // 节点人数数据
        nodeCountData() {
            if (!this.lossNodeData) {
                return {
                    expansionCount: 0,
                    inviteCount: 0,
                    appointmentCount: 0,
                    visitCount: 0,
                    billingCount: 0
                };
            }
            const nodeCount = this.lossNodeData.nodeCount || this.lossNodeData.NodeCount || {};
            return {
                expansionCount: nodeCount.expansionCount || nodeCount.ExpansionCount || 0,
                inviteCount: nodeCount.inviteCount || nodeCount.InviteCount || 0,
                appointmentCount: nodeCount.appointmentCount || nodeCount.AppointmentCount || 0,
                visitCount: nodeCount.visitCount || nodeCount.VisitCount || 0,
                billingCount: nodeCount.billingCount || nodeCount.BillingCount || 0
            };
        },
        // 流失节点列表
        lossNodeList() {
            if (!this.lossNodeData) return [];
            const nodes = this.lossNodeData.lossNodes || this.lossNodeData.LossNodes || [];
            return nodes.map(node => ({
                nodeIndex: node.nodeIndex || node.NodeIndex,
                nodeName: node.nodeName || node.NodeName,
                lossCount: node.lossCount || node.LossCount || 0,
                lossRate: (node.lossRate || node.LossRate || 0).toFixed(2),
                lossPercentage: (node.lossPercentage || node.LossPercentage || 0).toFixed(2)
            }));
        },
        // 转化率数据
        conversionRate() {
            if (!this.lossNodeData) {
                return {
                    expansionToInvite: 0,
                    inviteToAppointment: 0,
                    appointmentToVisit: 0,
                    visitToBilling: 0
                };
            }
            const rate = this.lossNodeData.conversionRate || this.lossNodeData.ConversionRate || {};
            return {
                expansionToInvite: (rate.expansionToInviteRate || rate.ExpansionToInviteRate || 0).toFixed(2),
                inviteToAppointment: (rate.inviteToAppointmentRate || rate.InviteToAppointmentRate || 0).toFixed(2),
                appointmentToVisit: (rate.appointmentToVisitRate || rate.AppointmentToVisitRate || 0).toFixed(2),
                visitToBilling: (rate.visitToBillingRate || rate.VisitToBillingRate || 0).toFixed(2)
            };
        },
        staffRankingList() {
            if (!this.employeeList || this.employeeList.length === 0) {
                return [];
            }
            return this.employeeList
                .filter(item => item && (item.EmployeeName || item.employeeName))
                .map(item => ({
                    name: item.EmployeeName || item.employeeName || '未知',
                    count: Number(item.ExpansionCount || item.expansionCount || 0)
                }))
                .sort((a, b) => b.count - a.count)
                .slice(0, 10);
        },
        storeRankingList() {
            if (!this.storeList || this.storeList.length === 0) {
                return [];
            }
            return this.storeList
                .filter(item => item && (item.StoreName || item.storeName))
                .map(item => ({
                    name: item.StoreName || item.storeName || '未知',
                    count: Number(item.ExpansionCount || item.expansionCount || 0)
                }))
                .sort((a, b) => b.count - a.count)
                .slice(0, 10);
        }
    },
    mounted() {
        // 默认本月1号到今天
        const end = dayjs().format('YYYY-MM-DD');
        const start = dayjs().startOf('month').format('YYYY-MM-DD');
        this.dateRange = [start, end];
        this.queryParams.startTime = start;
        this.queryParams.endTime = end;

        this.getEventList();
        this.handleQuery();

        window.addEventListener('resize', this.resizeCharts);
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.resizeCharts);
        if (this.charts.funnel) {
            this.charts.funnel.dispose();
        }
        if (this.charts.visit) {
            this.charts.visit.dispose();
        }
    },
    methods: {
        formatMoney(val) {
            if (!val) return '0.00';
            return Number(val).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        },
        getEventList() {
            // 初始化时加载部分数据（可选）
            // 远程搜索模式下，可以不预加载数据
        },
        remoteSearchEvent(query) {
            // 清除之前的定时器
            if (this.eventSearchTimer) {
                clearTimeout(this.eventSearchTimer);
            }

            // 如果查询为空，清空列表
            if (!query || query.trim() === '') {
                this.filteredEventList = [];
                return;
            }

            // 防抖处理，延迟300ms执行
            this.eventSearchTimer = setTimeout(() => {
                this.eventListLoading = true;
                const keyword = query.trim();

                // 调用接口搜索
                // 后端接口支持 EventName 和 EventNumber 模糊查询
                // 注意：后端使用 AND 逻辑，所以同时传递两个参数会要求同时满足
                // 为了更好的搜索体验，我们分别搜索名称和编号，然后合并结果
                Promise.all([
                    // 搜索活动名称
                    getEventList({
                        page: 1,
                        rows: 50,
                        EventName: keyword
                    }),
                    // 搜索活动编号
                    getEventList({
                        page: 1,
                        rows: 50,
                        EventNumber: keyword
                    })
                ]).then(results => {
                    // 合并两个搜索结果并去重
                    const allResults = [];
                    const idSet = new Set();

                    results.forEach(res => {
                        if (res && res.code === 200 && res.data && res.data.list) {
                            res.data.list.forEach(event => {
                                const id = event.id || event.Id;
                                if (!idSet.has(id)) {
                                    idSet.add(id);
                                    allResults.push(event);
                                }
                            });
                        }
                    });

                    // 统一数据格式，兼容大小写
                    this.filteredEventList = allResults.map(event => ({
                        id: event.id || event.Id,
                        eventName: event.eventName || event.EventName || event.name || event.Name,
                        eventNumber: event.eventNumber || event.EventNumber,
                        startTime: event.startTime || event.StartTime,
                        endTime: event.endTime || event.EndTime
                    }));

                    this.eventListLoading = false;
                }).catch(error => {
                    console.error('搜索拓客活动失败:', error);
                    this.eventListLoading = false;
                    this.filteredEventList = [];
                });
            }, 300);
        },
        handleDateChange(val) {
            if (val) {
                this.queryParams.startTime = val[0];
                this.queryParams.endTime = val[1];
                // 如果选择了时间，清空活动ID，或者保留？ 用户需求是"时间优先，活动可选"
                // 这里保留活动ID，支持"某活动在特定时间内"的数据
            } else {
                this.queryParams.startTime = '';
                this.queryParams.endTime = '';
            }
            this.handleQuery();
        },
        handleEventChange(val) {
            // 选择活动后，自动填充活动的时间范围
            if (val) {
                // 从 filteredEventList 中查找活动（因为现在使用远程搜索）
                let event = this.filteredEventList.find(e => (e.id || e.Id) === val);

                // 如果 filteredEventList 中没有找到，尝试从 eventList 中查找
                if (!event) {
                    event = this.eventList.find(e => (e.id || e.Id) === val);
                }

                if (event) {
                    // 保存选中的活动信息
                    this.selectedEvent = event;

                    const startTime = event.startTime || event.StartTime;
                    const endTime = event.endTime || event.EndTime;

                    if (startTime && endTime) {
                        // 格式化日期为 YYYY-MM-DD
                        const startDate = dayjs(startTime).format('YYYY-MM-DD');
                        const endDate = dayjs(endTime).format('YYYY-MM-DD');

                        // 设置时间范围
                        this.dateRange = [startDate, endDate];
                        this.queryParams.startTime = startDate;
                        this.queryParams.endTime = endDate;
                    } else {
                        this.$message.warning('该活动没有设置开始时间或结束时间');
                    }
                } else {
                    // 如果都找不到，清空选中的活动信息
                    this.selectedEvent = null;
                    this.$message.warning('未找到活动信息，请重新搜索选择');
                }
            } else {
                // 清空活动时，清空选中的活动信息，但保留时间范围（用户可能已手动选择）
                this.selectedEvent = null;
            }
            this.handleQuery();
        },
        async handleQuery() {
            // 验证参数
            if (!this.queryParams.eventId && (!this.queryParams.startTime || !this.queryParams.endTime)) {
                this.$message.warning('请选择拓客活动或时间范围');
                return;
            }

            this.loading = true;
            const errors = [];

            try {
                const params = {
                    EventId: this.queryParams.eventId || null,
                    StartTime: this.queryParams.startTime ? this.queryParams.startTime + ' 00:00:00' : null,
                    EndTime: this.queryParams.endTime ? this.queryParams.endTime + ' 23:59:59' : null
                };

                // 使用 Promise.allSettled 确保部分接口失败不影响其他数据加载
                const results = await Promise.allSettled([
                    getDashboardOverview(params),
                    getBigOrderStatistics(params),
                    getEmployeeParticipationStatistics(params),
                    getVisitConversionAnalysis(params),
                    getFunnelDataForDashboard(params),
                    getLossNodeAnalysis(params)
                ]);

                // 处理概览数据
                if (results[0].status === 'fulfilled' && results[0].value && results[0].value.code === 200) {
                    this.overviewData = results[0].value.data || results[0].value;
                } else {
                    errors.push('概览数据加载失败');
                    console.error('概览数据加载失败:', results[0].reason || results[0].value);
                }

                // 处理大单数据
                if (results[1].status === 'fulfilled' && results[1].value && results[1].value.code === 200) {
                    const bigOrderData = results[1].value.data || results[1].value;
                    const summary = bigOrderData.Summary || bigOrderData.summary || {};
                    this.bigOrderStats = {
                        count: summary.BigOrderCount || summary.bigOrderCount || 0,
                        amount: summary.BigOrderAmount || summary.bigOrderAmount || 0,
                        rate: summary.BigOrderRate || summary.bigOrderRate || 0
                    };
                    this.bigOrderDetailList = bigOrderData.Details || bigOrderData.details || [];
                } else {
                    errors.push('大单数据加载失败');
                    console.error('大单数据加载失败:', results[1].reason || results[1].value);
                }

                // 处理员工参与统计
                if (results[2].status === 'fulfilled' && results[2].value && results[2].value.code === 200) {
                    const employeeData = results[2].value.data || results[2].value;
                    // 后端返回的是 List<EmployeeParticipationStatisticsOutput>
                    this.employeeList = Array.isArray(employeeData) ? employeeData : (employeeData.Details || employeeData.details || []);
                } else {
                    errors.push('员工数据加载失败');
                    console.error('员工数据加载失败:', results[2].reason || results[2].value);
                }

                // 处理到店转化分析
                if (results[3].status === 'fulfilled' && results[3].value && results[3].value.code === 200) {
                    const visitData = results[3].value.data || results[3].value;
                    this.visitAnalysisData = visitData;
                    this.storeList = visitData.ByStore || visitData.byStore || [];
                } else {
                    errors.push('到店分析数据加载失败');
                    console.error('到店分析数据加载失败:', results[3].reason || results[3].value);
                }

                // 处理漏斗数据
                if (results[4].status === 'fulfilled' && results[4].value && results[4].value.code === 200) {
                    this.funnelData = results[4].value.data || results[4].value;
                } else {
                    errors.push('漏斗数据加载失败');
                    console.error('漏斗数据加载失败:', results[4].reason || results[4].value);
                }

                // 处理流失节点分析数据
                if (results[5].status === 'fulfilled' && results[5].value && results[5].value.code === 200) {
                    this.lossNodeData = results[5].value.data || results[5].value;
                    console.log('流失节点分析数据:', this.lossNodeData);
                } else {
                    errors.push('流失节点分析数据加载失败');
                    console.error('流失节点分析数据加载失败:', results[5].reason || results[5].value);
                    this.lossNodeData = null;
                }

                // 初始化图表 - 延迟一点确保DOM已渲染
                this.$nextTick(() => {
                    setTimeout(() => {
                        this.initCharts();
                    }, 100);
                });

                // 显示错误信息
                if (errors.length > 0) {
                    this.$message.warning(`部分数据加载失败: ${errors.join(', ')}`);
                } else if (this.overviewData || this.employeeList.length > 0 || this.storeList.length > 0) {
                    this.$message.success('数据加载成功');
                } else {
                    this.$message.info('暂无数据');
                }

            } catch (error) {
                console.error('查询失败:', error);
                this.$message.error('数据加载失败: ' + (error.message || '未知错误'));
            } finally {
                this.loading = false;
            }
        },
        initCharts() {
            this.initFunnelChart();
            this.initVisitChart();
            // 排行榜已改为表格，不再需要图表初始化
            // this.initStaffRankChart();
            // this.initStoreRankChart();
        },
        resizeCharts() {
            Object.keys(this.charts).forEach(key => {
                if (this.charts[key]) {
                    this.charts[key].resize();
                }
            });
        },
        initFunnelChart() {
            if (!this.$refs.funnelChart) {
                console.warn('funnelChart ref not found');
                return;
            }

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

            const chart = echarts.init(this.$refs.funnelChart);
            this.charts.funnel = chart;

            // 优先使用 overviewData，如果没有则使用 funnelData
            const d = this.overviewData || this.funnelData || {};
            console.log('漏斗数据:', d);

            // 兼容大小写，优先从 overviewData 获取
            const exp = Number(
                d.TotalExpansionCount || d.totalExpansionCount ||
                d.TotalTkCount || d.totalTkCount || 0
            );
            const visit = Number(
                d.TotalVisitCount || d.totalVisitCount || 0
            );
            const billing = Number(
                d.TotalBillingCount || d.totalBillingCount ||
                d.BillingCount || d.billingCount || 0
            );
            const bigOrder = Number(
                d.BigOrderCount || d.bigOrderCount || 0
            );

            const data = [
                { value: exp, name: '拓客人数' },
                { value: visit, name: '到店人数' },
                { value: billing, name: '开单人数' },
                { value: bigOrder, name: '大单人数' }
            ];

            // 即使有0值也显示，但不显示为0的项
            const validData = data.filter(item => item.value > 0);

            if (validData.length === 0) {
                chart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'middle',
                        textStyle: { color: '#999', fontSize: 14 }
                    }
                });
                return;
            }

            chart.setOption({
                tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c}" },
                color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C'],
                series: [{
                    name: '拓客漏斗',
                    type: 'funnel',
                    left: '10%', top: 20, bottom: 20, width: '80%',
                    min: 0,
                    max: Math.max(...validData.map(item => item.value), 100),
                    minSize: '0%',
                    maxSize: '100%',
                    sort: 'descending',
                    gap: 2,
                    label: { show: true, position: 'inside' },
                    itemStyle: { borderColor: '#fff', borderWidth: 1 },
                    emphasis: { label: { fontSize: 20 } },
                    data: validData
                }]
            });
        },
        initVisitChart() {
            if (!this.$refs.visitChart) {
                console.warn('visitChart ref not found');
                return;
            }

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

            const chart = echarts.init(this.$refs.visitChart);
            this.charts.visit = chart;

            const dist = (this.visitAnalysisData && (this.visitAnalysisData.VisitIntervalDistribution || this.visitAnalysisData.visitIntervalDistribution))
                ? (this.visitAnalysisData.VisitIntervalDistribution || this.visitAnalysisData.visitIntervalDistribution)
                : {};

            console.log('到店转化时效数据:', this.visitAnalysisData, dist);

            const xData = ['1天内', '3天内', '7天内', '15天内', '30天内', '30天以上'];
            const sData = [
                Number(dist.Within1Day || dist.within1Day || 0),
                Number(dist.Within3Days || dist.within3Days || 0),
                Number(dist.Within7Days || dist.within7Days || 0),
                Number(dist.Within15Days || dist.within15Days || 0),
                Number(dist.Within30Days || dist.within30Days || 0),
                Number(dist.Over30Days || dist.over30Days || 0)
            ];

            if (sData.every(val => val === 0)) {
                chart.setOption({
                    title: {
                        text: '暂无数据',
                        left: 'center',
                        top: 'middle',
                        textStyle: { color: '#999', fontSize: 14 }
                    }
                });
                return;
            }

            chart.setOption({
                tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
                xAxis: { type: 'category', data: xData, axisTick: { alignWithLabel: true } },
                yAxis: { type: 'value' },
                series: [{
                    name: '人数',
                    type: 'bar',
                    barWidth: '60%',
                    data: sData,
                    itemStyle: { color: '#409EFF' }
                }]
            });
        },
        scrollToTable() {
            const el = document.getElementById('detailTable');
            if (el) el.scrollIntoView({ behavior: 'smooth' });
        },
        getRankClass(rank) {
            if (rank === 1) return 'rank-gold';
            if (rank === 2) return 'rank-silver';
            if (rank === 3) return 'rank-bronze';
            return 'rank-normal';
        }
    }
}
</script>

<style lang="scss" scoped>
.tk-dashboard-container {
    padding: 16px;
    padding-bottom: 32px;
    background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 50%, #f0f4f8 100%);
    min-height: 100vh;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    box-sizing: border-box;

    .dashboard-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
        padding: 12px 20px;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
        border: 1px solid rgba(64, 158, 255, 0.1);
        position: relative;
        overflow: hidden;

        &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, #409EFF 0%, #66b1ff 50%, #409EFF 100%);
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;

            h1 {
                margin: 0;
                font-size: 20px;
                color: #303133;
                font-weight: 600;
                display: flex;
                align-items: center;

                i {
                    margin-right: 8px;
                    color: #409EFF;
                    font-size: 20px;
                }
            }

            .header-actions {
                display: flex;
                align-items: center;
                gap: 16px;
                float: right;
                text-align: right;

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

                    .filter-label {
                        font-size: 14px;
                        color: #606266;
                        margin-right: 8px;
                    }

                    .filter-select {
                        width: 180px;
                    }
                }

                .modern-search-btn {
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);

                    &:hover {
                        transform: translateY(-2px);
                        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
                    }

                    &:active {
                        transform: translateY(0);
                    }
                }
            }
        }
    }

    .dashboard-content {
        .kpi-grid {
            margin-bottom: 16px;

            .el-col:nth-child(n+5) {
                margin-top: 16px;
            }

            .kpi-card {
                background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
                padding: 20px 10px;
                border-radius: 12px;
                display: flex;
                align-items: center;
                position: relative;
                overflow: hidden;
                height: 100px;
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                cursor: pointer;
                border: 1px solid rgba(64, 158, 255, 0.08);

                &::after {
                    content: '';
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    height: 2px;
                    background: linear-gradient(90deg, transparent 0%, rgba(64, 158, 255, 0.3) 50%, transparent 100%);
                    opacity: 0;
                    transition: opacity 0.3s;
                }

                &:hover {
                    transform: translateY(-4px);
                    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12), 0 4px 12px rgba(0, 0, 0, 0.08);
                    border-color: rgba(64, 158, 255, 0.2);

                    &::after {
                        opacity: 1;
                    }
                }

                &.primary {
                    border-left: 4px solid #409EFF;
                    background: linear-gradient(135deg, #ffffff 0%, rgba(64, 158, 255, 0.03) 100%);

                    .kpi-icon-wrapper {
                        color: #409EFF;
                        background: linear-gradient(135deg, rgba(64, 158, 255, 0.15) 0%, rgba(64, 158, 255, 0.08) 100%);
                        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
                    }
                }

                &.success {
                    border-left: 4px solid #67C23A;
                    background: linear-gradient(135deg, #ffffff 0%, rgba(103, 194, 58, 0.03) 100%);

                    .kpi-icon-wrapper {
                        color: #67C23A;
                        background: linear-gradient(135deg, rgba(103, 194, 58, 0.15) 0%, rgba(103, 194, 58, 0.08) 100%);
                        box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2);
                    }
                }

                &.warning {
                    border-left: 4px solid #E6A23C;
                    background: linear-gradient(135deg, #ffffff 0%, rgba(230, 162, 60, 0.03) 100%);

                    .kpi-icon-wrapper {
                        color: #E6A23C;
                        background: linear-gradient(135deg, rgba(230, 162, 60, 0.15) 0%, rgba(230, 162, 60, 0.08) 100%);
                        box-shadow: 0 2px 8px rgba(230, 162, 60, 0.2);
                    }
                }

                &.info {
                    border-left: 4px solid #909399;
                    background: linear-gradient(135deg, #ffffff 0%, rgba(144, 147, 153, 0.03) 100%);

                    .kpi-icon-wrapper {
                        color: #909399;
                        background: linear-gradient(135deg, rgba(144, 147, 153, 0.15) 0%, rgba(144, 147, 153, 0.08) 100%);
                        box-shadow: 0 2px 8px rgba(144, 147, 153, 0.2);
                    }
                }

                .kpi-content {
                    display: flex;
                    align-items: center;
                    width: 100%;

                    .kpi-icon-wrapper {
                        width: 48px;
                        height: 48px;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        font-size: 24px;
                        margin-right: 15px;
                    }

                    .kpi-info {
                        flex: 1;

                        .kpi-label {
                            font-size: 13px;
                            color: #909399;
                            margin-bottom: 6px;
                        }

                        .kpi-value {
                            font-size: 20px;
                            font-weight: bold;
                            color: #303133;
                        }
                    }
                }
            }
        }

        .chart-row {
            margin-bottom: 16px;

            .chart-card {
                border: 1px solid rgba(64, 158, 255, 0.1);
                border-radius: 12px;
                margin-bottom: 16px;
                background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                overflow: hidden;

                &:hover {
                    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12), 0 4px 12px rgba(0, 0, 0, 0.08);
                    transform: translateY(-2px);
                    border-color: rgba(64, 158, 255, 0.2);
                }

                ::v-deep .el-card__header {
                    padding: 12px 20px;
                    border-bottom: 1px solid rgba(64, 158, 255, 0.1);
                    background: linear-gradient(135deg, rgba(64, 158, 255, 0.05) 0%, rgba(64, 158, 255, 0.02) 100%);
                    min-height: 48px;
                    display: flex;
                    align-items: center;
                }

                .chart-header {
                    font-size: 15px;
                    font-weight: 600;
                    color: #303133;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 100%;

                    .title {
                        display: flex;
                        align-items: center;

                        i {
                            color: #409EFF;
                            margin-right: 8px;
                            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                        }
                    }
                }

                &:hover .chart-header .title i {
                    transform: scale(1.1) rotate(5deg);
                }

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

                .big-order-summary {
                    display: flex;
                    justify-content: space-around;
                    margin-bottom: 16px;
                    padding: 16px;
                    background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
                    border-radius: 12px;
                    border: 1px solid rgba(64, 158, 255, 0.08);
                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

                    .bo-item {
                        text-align: center;
                        flex: 1;
                        position: relative;

                        &:not(:last-child)::after {
                            content: '';
                            position: absolute;
                            right: 0;
                            top: 50%;
                            transform: translateY(-50%);
                            width: 1px;
                            height: 60%;
                            background: #e0e0e0;
                        }

                        .label {
                            font-size: 12px;
                            color: #909399;
                            margin-bottom: 6px;
                        }

                        .value {
                            font-size: 18px;
                            font-weight: bold;
                        }

                        .primary {
                            color: #409EFF;
                        }

                        .success {
                            color: #67C23A;
                        }

                        .warning {
                            color: #E6A23C;
                        }
                    }
                }

                .money {
                    font-weight: 700;
                    color: #F56C6C;
                }
            }
        }

        .ranking-row {
            margin-bottom: 16px;

            .ranking-card {
                border: 1px solid rgba(64, 158, 255, 0.1);
                border-radius: 12px;
                margin-bottom: 16px;
                background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
                box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                overflow: hidden;

                &:hover {
                    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12), 0 4px 12px rgba(0, 0, 0, 0.08);
                    transform: translateY(-2px);
                    border-color: rgba(64, 158, 255, 0.2);
                }

                ::v-deep .el-card__header {
                    padding: 12px 20px;
                    border-bottom: 1px solid rgba(64, 158, 255, 0.1);
                    background: linear-gradient(135deg, rgba(64, 158, 255, 0.05) 0%, rgba(64, 158, 255, 0.02) 100%);
                    min-height: 48px;
                    display: flex;
                    align-items: center;
                }

                .card-header {
                    font-size: 15px;
                    font-weight: 600;
                    color: #303133;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 100%;

                    .title {
                        display: flex;
                        align-items: center;

                        i {
                            color: #409EFF;
                            margin-right: 8px;
                            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                        }
                    }
                }

                &:hover .card-header .title i {
                    transform: scale(1.1) rotate(5deg);
                }

                .ranking-table-wrapper {
                    padding: 0;

                    ::v-deep .el-table {
                        border-radius: 8px;
                        border: 1px solid rgba(64, 158, 255, 0.1);
                        overflow: hidden;
                    }

                    ::v-deep .el-table__header {
                        th {
                            background: linear-gradient(135deg, rgba(64, 158, 255, 0.08) 0%, rgba(64, 158, 255, 0.05) 100%);
                            color: #303133;
                            font-weight: 600;
                            border-bottom: 1px dotted rgba(64, 158, 255, 0.15);
                            padding: 12px 0;
                            height: 48px;
                        }
                    }

                    ::v-deep .el-table__body {
                        tr {
                            transition: background-color 0.2s;

                            &:hover {
                                background-color: rgba(64, 158, 255, 0.05);
                            }
                        }

                        td {
                            border-bottom: 1px solid rgba(64, 158, 255, 0.08);
                        }
                    }

                    .rank-badge {
                        display: inline-block;
                        width: 28px;
                        height: 28px;
                        line-height: 28px;
                        text-align: center;
                        border-radius: 50%;
                        font-size: 13px;
                        font-weight: 600;

                        &.rank-gold {
                            background: linear-gradient(135deg, #FFD700, #FFA500);
                            color: #fff;
                        }

                        &.rank-silver {
                            background: linear-gradient(135deg, #C0C0C0, #808080);
                            color: #fff;
                        }

                        &.rank-bronze {
                            background: linear-gradient(135deg, #CD7F32, #8B4513);
                            color: #fff;
                        }

                        &.rank-normal {
                            background: #f0f2f5;
                            color: #606266;
                        }
                    }

                    .rank-value {
                        font-weight: 600;
                        color: #303133;
                    }
                }
            }
        }

        .loss-node-row {
            margin-top: 16px;
            margin-bottom: 16px;
        }

        .loss-node-card {
            border: 1px solid rgba(64, 158, 255, 0.1);
            border-radius: 12px;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            overflow: hidden;

            &:hover {
                box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12), 0 4px 12px rgba(0, 0, 0, 0.08);
                transform: translateY(-2px);
                border-color: rgba(64, 158, 255, 0.2);
            }

            ::v-deep .el-card__header {
                padding: 12px 20px;
                border-bottom: 1px solid rgba(64, 158, 255, 0.1);
                background: linear-gradient(135deg, rgba(64, 158, 255, 0.05) 0%, rgba(64, 158, 255, 0.02) 100%);
                min-height: 48px;
                display: flex;
                align-items: center;
            }

            .loss-node-content {
                .section-title {
                    font-size: 16px;
                    font-weight: 600;
                    color: #303133;
                    margin-bottom: 16px;
                    padding-bottom: 8px;
                    border-bottom: 2px solid #409EFF;
                }

                .node-count-section {
                    margin-bottom: 32px;

                    .node-count-list {
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        flex-wrap: wrap;
                        gap: 16px;

                        .node-item {
                            display: flex;
                            flex-direction: column;
                            align-items: center;
                            padding: 16px 24px;
                            background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
                            border-radius: 12px;
                            color: #fff;
                            min-width: 100px;
                            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
                            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                            cursor: pointer;

                            &:hover {
                                transform: translateY(-2px);
                                box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
                            }

                            .node-label {
                                font-size: 14px;
                                margin-bottom: 8px;
                                opacity: 0.9;
                            }

                            .node-value {
                                font-size: 24px;
                                font-weight: 700;
                            }
                        }

                        .node-arrow {
                            font-size: 24px;
                            color: #909399;
                            font-weight: 600;
                        }
                    }
                }

                .loss-node-cards {
                    margin-bottom: 32px;

                    .loss-node-card-item {
                        border: 1px solid rgba(64, 158, 255, 0.08);
                        border-radius: 12px;
                        background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
                        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                        cursor: pointer;
                        position: relative;
                        overflow: hidden;

                        &::after {
                            content: '';
                            position: absolute;
                            top: 0;
                            left: 0;
                            right: 0;
                            height: 2px;
                            background: linear-gradient(90deg, transparent 0%, rgba(64, 158, 255, 0.3) 50%, transparent 100%);
                            opacity: 0;
                            transition: opacity 0.3s;
                        }

                        &:hover {
                            transform: translateY(-4px);
                            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12), 0 4px 12px rgba(0, 0, 0, 0.08);
                            border-color: rgba(64, 158, 255, 0.2);

                            &::after {
                                opacity: 1;
                            }
                        }

                        &.loss-node-1 {
                            border-left: 4px solid #F56C6C;
                        }

                        &.loss-node-2 {
                            border-left: 4px solid #E6A23C;
                        }

                        &.loss-node-3 {
                            border-left: 4px solid #409EFF;
                        }

                        &.loss-node-4 {
                            border-left: 4px solid #67C23A;
                        }

                        .loss-card-content {
                            padding: 8px 0;

                            .loss-card-title {
                                font-size: 14px;
                                color: #606266;
                                margin-bottom: 12px;
                            }

                            .loss-card-value {
                                font-size: 32px;
                                font-weight: 700;
                                color: #303133;
                                margin-bottom: 8px;
                            }

                            .loss-card-rate,
                            .loss-card-percentage {
                                font-size: 12px;
                                color: #909399;
                                margin-top: 4px;

                                .rate-value,
                                .percentage-value {
                                    color: #F56C6C;
                                    font-weight: 600;
                                    margin-left: 4px;
                                }
                            }
                        }
                    }
                }

                .conversion-rate-section {
                    .rate-item {
                        text-align: center;
                        padding: 16px;
                        background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
                        border-radius: 12px;
                        border: 1px solid rgba(64, 158, 255, 0.08);
                        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
                        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                        cursor: pointer;

                        &:hover {
                            background: linear-gradient(135deg, #ecf5ff 0%, #ffffff 100%);
                            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
                            transform: translateY(-2px);
                            border-color: rgba(64, 158, 255, 0.2);
                        }

                        .rate-label {
                            font-size: 14px;
                            color: #606266;
                            margin-bottom: 8px;
                        }

                        .rate-value {
                            font-size: 24px;
                            font-weight: 700;
                            color: #409EFF;
                        }
                    }
                }
            }
        }

        .table-card {
            border: 1px solid rgba(64, 158, 255, 0.1);
            border-radius: 12px;
            margin-bottom: 16px;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            overflow: hidden;

            &:hover {
                box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12), 0 4px 12px rgba(0, 0, 0, 0.08);
                border-color: rgba(64, 158, 255, 0.2);
            }

            ::v-deep .el-tabs__header {
                margin: 0;
                background: linear-gradient(135deg, rgba(64, 158, 255, 0.05) 0%, rgba(64, 158, 255, 0.02) 100%);
                border-bottom: 1px solid rgba(64, 158, 255, 0.1);
            }

            ::v-deep .el-tabs__item {
                height: 48px;
                line-height: 48px;
                padding: 0 20px;
                font-size: 14px;
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

                i {
                    margin-right: 6px;
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                }

                &:hover {
                    color: #409EFF;

                    i {
                        transform: scale(1.1);
                    }
                }

                &.is-active {
                    color: #409EFF;
                    font-weight: 600;

                    i {
                        transform: scale(1.1);
                    }
                }
            }

            ::v-deep .el-tabs__active-bar {
                background-color: #409EFF;
                height: 3px;
            }

            ::v-deep .el-table {
                border-radius: 8px;
                border: 1px solid rgba(64, 158, 255, 0.1);
                overflow: hidden;
            }

            ::v-deep .el-table__header {
                th {
                    background: linear-gradient(135deg, rgba(64, 158, 255, 0.08) 0%, rgba(64, 158, 255, 0.05) 100%);
                    color: #303133;
                    font-weight: 600;
                    border-bottom: 1px dotted rgba(64, 158, 255, 0.15);
                    padding: 12px 0;
                }
            }

            ::v-deep .el-table__body {
                tr {
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

                    &:hover {
                        background: linear-gradient(90deg, rgba(64, 158, 255, 0.05) 0%, rgba(64, 158, 255, 0.02) 100%) !important;
                        transform: translateX(4px);
                    }
                }

                td {
                    border-bottom: 1px dotted rgba(64, 158, 255, 0.15);
                    padding: 8px 0;
                }
            }

            ::v-deep .el-table__body-wrapper {
                &::-webkit-scrollbar {
                    width: 6px;
                }

                &::-webkit-scrollbar-track {
                    background: rgba(240, 242, 245, 0.5);
                    border-radius: 3px;
                }

                &::-webkit-scrollbar-thumb {
                    background: linear-gradient(135deg, #c0c4cc 0%, #909399 100%);
                    border-radius: 3px;
                    transition: background 0.3s;

                    &:hover {
                        background: linear-gradient(135deg, #909399 0%, #606266 100%);
                    }
                }
            }
        }
    }

    .loading-container {
        height: 400px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}
</style>