<template>
    <HomeContainer :customStyle="{ background: 'none', backgroundColor: '#F6F7FA' }">
        <!-- 时间范围选择 -->
        <div class="time-range-section">
            <div class="time-tags-container">
                <div v-for="tag in timeTags" :key="tag.value"
                    :class="['time-tag', { 'active': selectedTimeRange === tag.value, 'time-range-label': tag.isLabel }]"
                    @click="tag.isLabel ? null : handleTimeTagClick(tag)">
                    {{ tag.label }}
                </div>

                <!-- 自定义时间显示 - 紧跟自定义时间标签 -->
                <div v-if="selectedTimeRange === 'custom'" class="custom-time-inline">
                    <uni-datetime-picker v-model="dateRange" type="daterange" rangeSeparator="至"
                        @change="handleDateRangeChange" class="date-range-picker" :clear-icon="false" />
                    <div class="days-count">共 {{ totalDays }} 天</div>
                </div>
            </div>
        </div>

        <!-- 查获效率部分 -->
        <div class="section-title">查获效率</div>
        <view class="section efficiency-section">
            <!-- 数据网格 -->
            <div class="data-grid-container">
                <div class="data-grid-title">查获效率</div>
                <div class="data-grid">
                    <div v-for="(dataItem, dataIndex) in efficiencyData" :key="dataIndex" class="data-item">
                        <div class="data-value">
                            <image v-if="dataItem.isImage" :src="dataItem.value" class="data-image" />
                            <span v-else :style="{ color: dataItem.color || '#333333' }">{{ dataItem.value }}</span>
                        </div>
                        <div class="data-label">{{ dataItem.label }}</div>
                        <div v-if="dataIndex == dividerIndex" class="divider"></div>
                    </div>
                </div>
            </div>

            <!-- 大队查获效率排行 -->
            <div class="rank-section">
                <div class="rank-header">
                    <div class="rank-title">大队查获效率排行</div>
                </div>

                <div v-for="(brigade, i) in brigadeRank" :key="'brigade-' + i" class="rank-item">
                    <div class="rank-label">{{ brigade.name }}</div>
                    <div class="rank-progress">
                        <h-rank-line :percentage="getPercentage(brigade.efficiency, brigadeRank)" endType="round"
                            :height="10" :color="['#A8E6CF', '#4CAF50']">
                            <div class="rank-info"><span style="color: #999999">{{ (brigade.efficiency * 100 ||
                                0).toFixed(2)
                                    }}%</span></div>
                        </h-rank-line>
                    </div>
                </div>
            </div>

            <!-- 主管查获数量排行 -->
            <div class="rank-section">
                <div class="rank-header">
                    <div class="rank-title">主管查获效率排行</div>
                </div>

                <div v-for="(dept, i) in departmentRank" :key="'dept-' + i" class="rank-item">
                    <div class="rank-label">{{ dept.name }}</div>
                    <div class="rank-progress">
                        <h-rank-line :percentage="getPercentage(dept.efficiency, departmentRank)" endType="round"
                            :height="10" :color="['#F9CA91', '#ED9E3E']">
                            <div class="rank-info"><span style="color: #999999">{{ (dept.efficiency * 100 ||
                                0).toFixed(2)
                                    }}%</span></div>
                        </h-rank-line>
                    </div>
                </div>
            </div>

            <!-- 班组查获效率排行 -->
            <div class="rank-section">
                <div class="rank-header">
                    <div class="rank-title">班组查获效率排行</div>
                    <div class="sort-buttons">
                        <div :class="['sort-btn', { 'active': teamSortType === 'asc' }]" @click="teamSortType = 'asc'">
                            正序</div>
                        <div :class="['sort-btn', { 'active': teamSortType === 'desc' }]"
                            @click="teamSortType = 'desc'">倒序</div>
                    </div>
                </div>

                <template v-if="teamSortType === 'asc'">
                    <div v-for="(team, i) in (teamRank || []).slice(0, 5)" :key="'team-asc-' + i" class="rank-item">
                        <div class="rank-label">{{ team.name }}</div>
                        <div class="rank-progress">
                            <h-rank-line :percentage="getPercentage(team.efficiency, teamRank)" endType="round"
                                :height="10" :color="['#87BFFC', '#5580F7']">
                                <div class="rank-info"><span style="color: #999999">{{ (team.efficiency * 100 ||
                                    0).toFixed(2) }}%</span>
                                </div>
                            </h-rank-line>
                        </div>
                    </div>
                </template>
                <template v-else>
                    <div v-for="(team, i) in (bottomTeamRank || []).slice(0, 5)" :key="'team-desc-' + i"
                        class="rank-item">
                        <div class="rank-label">{{ team.name }}</div>
                        <div class="rank-progress">
                            <h-rank-line :percentage="getPercentage(team.efficiency, bottomTeamRank)" endType="round"
                                :height="10" :color="['#87BFFC', '#5580F7']">
                                <div class="rank-info"><span style="color: #999999">{{ (team.efficiency * 100 ||
                                    0).toFixed(2) }}%</span>
                                </div>
                            </h-rank-line>
                        </div>
                    </div>
                </template>
            </div>

            <!-- 安检员查获效率排行 -->
            <div class="rank-section">
                <div class="rank-header">
                    <div class="rank-title">安检员查获效率排行</div>
                    <div class="sort-buttons">
                        <div :class="['sort-btn', { 'active': inspectorSortType === 'asc' }]"
                            @click="inspectorSortType = 'asc'">正序
                        </div>
                        <div :class="['sort-btn', { 'active': inspectorSortType === 'desc' }]"
                            @click="inspectorSortType = 'desc'">
                            倒序</div>
                    </div>
                </div>

                <template v-if="inspectorSortType === 'asc'">
                    <div v-for="(inspector, i) in (inspectorRank || []).slice(0, 5)" :key="'inspector-asc-' + i"
                        class="rank-item">
                        <div class="rank-label">{{ inspector.name }}</div>
                        <div class="rank-progress">
                            <h-rank-line :percentage="getPercentage(inspector.efficiency, inspectorRank)"
                                endType="round" :height="10" :color="['#87BFFC', '#5580F7']">
                                <div class="rank-info"><span style="color: #999999">{{ (inspector.efficiency * 100 ||
                                    0).toFixed(2) }}%</span>
                                </div>
                            </h-rank-line>
                        </div>
                    </div>
                </template>
                <template v-else>
                    <div v-for="(inspector, i) in (bottomInspectorRank || []).slice(0, 5)" :key="'inspector-desc-' + i"
                        class="rank-item">
                        <div class="rank-label">{{ inspector.name }}</div>
                        <div class="rank-progress">
                            <h-rank-line :percentage="getPercentage(inspector.efficiency, bottomInspectorRank)"
                                endType="round" :height="10" :color="['#87BFFC', '#5580F7']">
                                <div class="rank-info"><span style="color: #999999">{{ (inspector.efficiency * 100 ||
                                    0).toFixed(2) }}%</span>
                                </div>
                            </h-rank-line>
                        </div>
                    </div>
                </template>
            </div>
        </view>

        <!-- 查获统计部分 -->
        <div class="section-title">查获统计</div>
        <view class="section chart-section">
            <div class="chart-container">
                <!-- 安检站查获数量分布 -->
                <div class="chart-item">
                    <div class="chart-title">安检站查获数量分布直方图</div>
                    <div id="station-bar-chart" class="chart bar-chart"></div>
                </div>

                <!-- 箱线图 -->
                <div class="chart-item">
                    <div class="chart-title">查获数量差异对比箱线图</div>
                    <div id="box-plot-chart" class="chart"></div>
                </div>
            </div>
        </view>

        <!-- 绩效评优部分 -->
        <div class="section-title">绩效评优</div>
        <view class="section performance-section">
            <!-- 按钮组 -->
            <!-- <div class="button-group">
                <div v-for="button in performanceButtons" :key="button.value"
                    :class="['performance-btn', { 'active': selectedPerformance === button.value }]"
                    @click="selectedPerformance = button.value">
                    {{ button.label }}
                </div>
            </div> -->

            <!-- 判断矩阵 -->
            <!-- <div class="matrix-section">
                <div class="matrix-title">示例判断矩阵（假设三个因素）</div>
                <StatisticTable :columns="matrixColumns" :data="matrixData" class="matrix-table" />
            </div> -->

            <!-- 筛选表格 -->
            <div class="filter-section">
                <div class="filter-row">
                    <div class="filter-group">
                        <div class="filter-item">
                            <uni-data-select v-model="statisticalDimension" class="filter-select"
                                :localdata="statisticalDimensionOptions" placeholder="统计维度" :clear="false"
                                @change="onFilterChange" />
                        </div>
                        <div class="filter-item">
                            <uni-data-select v-model="sortMethod" class="filter-select" :localdata="sortMethodOptions"
                                placeholder="排序方式" :clear="false" @change="onFilterChange" />
                        </div>
                    </div>
                    <div class="sort-buttons">
                        <div :class="['sort-btn', { 'active': performanceSortType === 'asc' }]"
                            @click="onSortTypeChange('asc')">正序</div>
                        <div :class="['sort-btn', { 'active': performanceSortType === 'desc' }]"
                            @click="onSortTypeChange('desc')">倒序</div>
                    </div>
                </div>

                <StatisticTable :columns="performanceColumns" :data="performanceData" class="performance-table">
                    <template #column-name="{ row, index }">
                        <div class="name-cell" @click="showNameTooltip(row)">
                            {{ row.name }}
                        </div>
                    </template>
                </StatisticTable>
            </div>
        </view>
    </HomeContainer>
</template>

<script>
import HomeContainer from '@/components/HomeContainer.vue'
import StatisticTable from '@/components/statistic-table/statistic-table.vue'
import * as echarts from 'echarts'
// 导入uni-datetime-picker组件
import uniDatetimePicker from "@/uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue";
// 导入统计分析API
import {
    getItemPerformanceList,
    getItemPerformanceHistogram,
    getItemPerformanceBoxplot,
    getItemPerformanceMetrics
} from '@/api/statisticalAnalysis/statisticalAnalysis';

export default {
    name: 'StatisticalAnalysis',
    components: {
        HomeContainer,
        StatisticTable,
        uniDatetimePicker
    },
    data() {
        return {
            // 时间选择相关数据
            startDate: '',
            endDate: '',
            dateRange: [],
            totalDays: 0,
            selectedTimeRange: 'week',
            timeTags: [
                { label: '时间范围:', value: 'label', isLabel: true },
                { label: '近一周', value: 'week' },
                { label: '近一月', value: 'month' },
                { label: '近三月', value: 'quarter' },
                { label: '近半年', value: 'halfYear' },
                { label: '近一年', value: 'year' },
                { label: '自定义时间', value: 'custom' }
            ],
            // 分隔线索引
            dividerIndex: 0,
            // 查获效率数据 - 参考getSeizeDataItems方法中test/zhijianke角色的实现
            efficiencyData: [],
            // 主管排行数据
            departmentRank: [],
            // 大队排行数据
            brigadeRank: [],
            // 班组排行数据
            teamSortType: 'asc',
            teamRank: [],
            bottomTeamRank: [],
            // 安检员排行数据
            inspectorSortType: 'asc',
            inspectorRank: [],
            bottomInspectorRank: [],
            // 绩效评优数据
            selectedPerformance: 'workingHours',
            // performanceButtons: [
            //     { label: '在岗时长', value: 'workingHours' },
            //     { label: '查获效率', value: 'seizureEfficiency' },
            //     { label: '巡检合格率', value: 'inspectionRate' },
            //     { label: '培训得分', value: 'trainingScore' },
            //     { label: '抽问抽答正确率', value: 'questionRate' },
            //     { label: '查获数量', value: 'seizureCount' }
            // ],
            // 判断矩阵数据
            matrixColumns: [
                { props: 'factor', title: '因素' },
                { props: 'weight', title: '权重' },
                { props: 'score', title: '得分' }
            ],
            matrixData: [
                { factor: '查获数量', weight: '0.4', score: '85' },
                { factor: '在岗时长', weight: '0.3', score: '90' },
                { factor: '巡检合格率', weight: '0.3', score: '88' }
            ],

            // 绩效表格数据
            statisticalDimension: '4', // 统计维度：1-人员, 2-班级, 3-科级
            sortMethod: 'totalScore', // 排序方式：seizureEfficiency-查获效率, inspectionPassRate-巡检合格率, trainingScore-培训得分, totalScore-总分
            // 统计维度选项
            statisticalDimensionOptions: [
                { value: '1', text: '人员' },
                { value: '2', text: '班级' },
                { value: '3', text: '主管' },
                { value: '4', text: '大队' }
            ],
            // 排序方式选项
            sortMethodOptions: [
                { value: 'seizureEfficiency', text: '查获效率' },
                { value: 'inspectionPassRate', text: '巡检合格率' },
                { value: 'trainingScore', text: '抽问抽答正确率' },
                { value: 'totalScore', text: '总分' }
            ],
            performanceSortType: 'asc',
            performanceColumns: [
                { props: 'name', title: '组织/姓名', slot: true },
                { props: 'seizureEfficiency', title: '查获效率' },
                { props: 'inspectionPassRate', title: '巡检合格率' },
                { props: 'trainingScore', title: '抽问抽答正确率' },
                { props: 'totalScore', title: '总分' }
            ],
            performanceData: [],
            // ECharts实例
            stationChart: null,
            boxPlotChart: null
        }
    },

    mounted() {
        this.setDefaultDates()
        this.initCharts()
        this.loadAllData() // 页面加载时立即请求数据
    },

    beforeDestroy() {
        if (this.stationChart) {
            this.stationChart.dispose()
        }
        if (this.boxPlotChart) {
            this.boxPlotChart.dispose()
        }
    },

    methods: {
        // 设置默认日期
        setDefaultDates() {
            const today = new Date()
            const oneWeekAgo = new Date(today)
            oneWeekAgo.setDate(today.getDate() - 7)
            const yesterday = new Date(today)
            yesterday.setDate(today.getDate() - 1)

            // 使用本地时间格式化，避免UTC时间转换问题
            this.startDate = this.formatLocalDate(oneWeekAgo)
            this.endDate = this.formatLocalDate(yesterday)

            // 初始化dateRange
            this.dateRange = [this.startDate, this.endDate]
            this.calculateDays()
        },

        // 格式化本地日期为YYYY-MM-DD格式
        formatLocalDate(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}`;
        },

        // 计算天数
        calculateDays() {
            if (this.startDate && this.endDate) {
                const start = new Date(this.startDate)
                const end = new Date(this.endDate)
                const diffTime = Math.abs(end - start)
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
                this.totalDays = diffDays
            }
        },

        // 处理时间标签点击
        handleTimeTagClick(tag) {
            this.selectedTimeRange = tag.value
            this.calculateDateRange(tag.value)
            this.loadAllData()
        },

        // 处理日期范围变化
        async handleDateRangeChange(e) {
            if (e && Array.isArray(e) && e.length === 2) {
                this.startDate = e[0]
                // 自定义时间范围时，结束时间加一天
                const endDate = new Date(e[1])
                endDate.setDate(endDate.getDate() + 1)
                this.endDate = this.formatLocalDate(endDate)
                this.calculateDays()
                await this.loadAllData();
            }
        },

        // 根据时间范围计算开始和结束日期
        calculateDateRange(timeRange) {
            const today = new Date()
            let startDate = new Date()

            switch (timeRange) {
                case 'week':
                    startDate.setDate(today.getDate() - 7)
                    break
                case 'month':
                    startDate.setMonth(today.getMonth() - 1)
                    break
                case 'quarter':
                    startDate.setMonth(today.getMonth() - 3)
                    break
                case 'halfYear':
                    startDate.setMonth(today.getMonth() - 6)
                    break
                case 'year':
                    startDate.setFullYear(today.getFullYear() - 1)
                    break
                case 'custom':
                    // 自定义时间范围，使用当前设置的日期，endDate减一天
                    const endDate = new Date(this.endDate)
                    endDate.setDate(endDate.getDate() - 1)
                    return { startDate: this.startDate, endDate: this.formatLocalDate(endDate) }
                default:
                    startDate.setFullYear(today.getFullYear() - 1)
            }

            this.startDate = this.formatLocalDate(startDate)
            const yesterday = new Date(today)
            yesterday.setDate(today.getDate() - 1)
            this.endDate = this.formatLocalDate(yesterday)
            this.dateRange = [this.startDate, this.endDate]
            this.calculateDays()

            return { startDate: this.startDate, endDate: this.endDate }
        },

        // 统一加载所有数据的方法
        async loadAllData() {
            try {
                console.log('加载数据，时间范围:', this.startDate, '至', this.endDate)

                // 构建请求参数
                const params = {
                    startDate: this.startDate,
                    endDate: this.endDate
                };

                // 使用Promise.allSettled并行请求所有接口
                const results = await Promise.allSettled([
                    getItemPerformanceList(params),
                    getItemPerformanceHistogram(params),
                    getItemPerformanceBoxplot(params),
                    this.loadPerformanceMetricsData()
                ]);

                // 处理每个接口的结果
                results.forEach((result, index) => {
                    if (result.status === 'fulfilled') {
                        const { data } = result.value;
                        switch (index) {
                            case 0: // 绩效列表数据
                                this.handlePerformanceListData(data);
                                break;
                            case 1: // 柱状图数据
                                this.handleHistogramData(data);
                                break;
                            case 2: // 箱线图数据
                                this.handleBoxplotData(data);
                                break;
                            case 3: // 绩效指标数据
                                this.handlePerformanceMetricsData(data);
                                break;
                        }
                    } else {
                        console.error(`接口${index}请求失败:`, result.reason);
                    }
                });

            } catch (error) {
                console.error('加载数据失败:', error);
            }
        },

        // 处理绩效列表数据
        handlePerformanceListData(data) {
            console.log('绩效列表数据:', data);
            const { departmentRankList, teamRankList, efficiency, individualRankList, brigadeRankList } = data;
            this.efficiencyData = [
                { label: '全站', value: `${(efficiency * 100).toFixed(2)}%`, isImage: false },
                { label: this.getRank(departmentRankList, 1), value: '/static/images/icon/one.png', isImage: true },
                { label: this.getRank(departmentRankList, 2), value: '/static/images/icon/two.png', isImage: true },
                { label: this.getRank(departmentRankList, 3), value: '/static/images/icon/three.png', isImage: true }
            ];
            this.departmentRank = departmentRankList;

            // brigadeRank取前五的数据
            this.brigadeRank = brigadeRankList ? brigadeRankList.slice(0, 5) : [];

            // teamRank取前五的数据
            this.teamRank = teamRankList.slice(0, 5);
            // bottomTeamRank取倒数五个数据
            this.bottomTeamRank = teamRankList.slice(-5).reverse();

            // inspectorRank取前五的数据
            this.inspectorRank = individualRankList.slice(0, 5);
            // bottomInspectorRank取倒数五个数据
            this.bottomInspectorRank = individualRankList.slice(-5).reverse();;

        },
        getRank(arr, index) {
            return (arr.find(item => item.rank == index) || {}).name || ''
        },
        // 处理柱状图数据（改为瀑布图展示范围数据）
        handleHistogramData(data) {
            console.log('柱状图数据:', data);
            // 将数据转换为瀑布图格式
            const waterfallData = this.convertToWaterfallData(data);
            // 更新瀑布图
            this.updateWaterfallChart(waterfallData);
        },

        // 将API数据转换为直方图格式
        convertToWaterfallData(data) {
            if (!Array.isArray(data)) return [];

            return data.map(item => {
                // 将lowerBound和upperBound取整
                const lowerBound = Math.round(item.lowerBound);
                const upperBound = Math.round(item.upperBound);

                return {
                    name: `${lowerBound}~${upperBound}`,
                    count: item.count,
                    lowerBound: lowerBound,
                    upperBound: upperBound
                };
            });
        },

        // 处理箱线图数据
        handleBoxplotData(data) {
            console.log('箱线图数据:', data);
            // 这里处理箱线图数据，更新图表
            this.updateBoxPlotChart(data);
        },

        // 处理绩效指标数据
        handlePerformanceMetricsData(data) {
            console.log('绩效指标数据:', data);
            // 这里处理绩效指标数据，更新相关数据属性
            this.performanceData = data;
            // 例如：this.efficiencyData = this.formatEfficiencyData(data);
        },

        // 独立加载绩效指标数据的方法
        async loadPerformanceMetricsData() {
            return new Promise(async (resolve, reject) => {
                try {
                    // 将performanceSortType转换为API需要的sortOrder参数
                    const sortOrder = this.performanceSortType === 'asc' ? 2 : 1;

                    const params = {
                        startTime: this.startDate,
                        endTime: this.endDate,
                        dimension: this.statisticalDimension,
                        sortField: this.sortMethod,
                        sortOrder: sortOrder
                    };

                    console.log('请求绩效指标数据，参数:', params);
                    const result = await getItemPerformanceMetrics(params);
                    this.handlePerformanceMetricsData(result.data);
                    resolve(result); // 成功时resolve
                } catch (error) {
                    console.error('加载绩效指标数据失败:', error);
                    reject(error); // 失败时reject
                }
            });
        },

        // 下拉框变化事件处理
        onFilterChange() {
            console.log('筛选条件变化，重新加载绩效指标数据');
            console.log('统计维度:', this.statisticalDimension, '排序方式:', this.sortMethod);
            this.loadPerformanceMetricsData();
        },

        // 排序类型变化事件处理
        onSortTypeChange(sortType) {
            this.performanceSortType = sortType;
            console.log('排序类型变化，重新加载绩效指标数据');
            console.log('排序类型:', sortType, 'API参数sortOrder:', sortType === 'asc' ? '1' : '2');
            this.loadPerformanceMetricsData();
        },

        // 初始化图表
        initCharts() {
            this.initStationBarChart()
            this.initBoxPlotChart()
        },

        // 初始化安检站瀑布图
        initStationBarChart() {
            const chartDom = document.getElementById('station-bar-chart')
            if (!chartDom) return

            this.stationChart = echarts.init(chartDom)
            // 初始化为空数据，等待API数据更新
            this.updateWaterfallChart([]);
        },

        // 更新直方图数据
        updateWaterfallChart(histogramData) {
            if (!this.stationChart) return;

            // 构建x轴刻度数据 - 所有边界点
            let arr = [];
            for (let i = 0; i < histogramData.length; i++) {
                arr.push(histogramData[i]?.lowerBound)
                arr.push(histogramData[i]?.upperBound)
            }
            const xAxisData = arr.length > 0 ? Array.from(new Set(arr)).sort((a, b) => a - b) : [];
            console.log('xAxisData:', xAxisData);
            // 构建直方图数据 - 使用数值轴和自定义柱子位置
            // 每个柱子显示在两个刻度之间
            const data = histogramData.map((item, index) => {
                return {
                    name: `${item.lowerBound}~${item.upperBound}`,
                    value: [item.lowerBound, item.upperBound, item.count], // [起点, 终点, 高度]
                    itemStyle: {
                        color: '#5580F7'
                    }
                };
            });
            console.log('直方图数据:', data);

            // 计算y轴最大值 - 根据实际数据动态调整
            const maxCount = Math.max(...histogramData.map(item => item.count));
            

            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        return `范围: ${params.data.name}<br/>数量: ${params.data.value[2]}`;
                    }
                },
                grid: {
                    left: '3%',
                    right: '10%',
                    bottom: '0%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value', // 使用数值轴
                    name: '',
                    min: xAxisData[0] || 0,
                    max: xAxisData[xAxisData.length - 1],
                    axisLine: {
                        show: true
                    },
                    axisTick: {
                        show: true,
                        alignWithLabel: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            // 显示xAxisData中的值
                            return Math.round(value);
                        }
                    },
                    // 设置七等分刻度
                    interval: xAxisData[xAxisData.length - 1] / (xAxisData.length-1),
                    // 自定义刻度，强制显示所有边界值
                    splitLine: {
                        show: false
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '数量',
                    min: 0,
                    max: maxCount,
                    splitLine: {
                        show: false
                    }
                },
                series: [
                    {
                        name: '查获数量分布',
                        type: 'custom', // 使用自定义系列
                        renderItem: function (params, api) {
                            
                            const lowerBound = api.value(0); // 起点
                            const upperBound = api.value(1); // 终点
                            const count = api.value(2); // 高度
                            
                            console.log('数据:', lowerBound, upperBound, count);
                            
                            // 计算左下角坐标：[lowerBound, 0]
                            const bottomLeft = api.coord([lowerBound, 0]);
                            // 计算右上角坐标：[upperBound, count]
                            const topRight = api.coord([upperBound, count]);
                            
                            console.log('左下角坐标:', bottomLeft);
                            console.log('右上角坐标:', topRight);
                            
                            // 计算矩形的宽度和高度
                            const width = Math.max(topRight[0] - bottomLeft[0], 1);
                            const height = Math.max(bottomLeft[1] - topRight[1], 1);
                            
                            console.log('矩形位置:', bottomLeft[0], topRight[1], width, height);
                            
                            return {
                                type: 'rect',
                                shape: {
                                    x: bottomLeft[0],
                                    y: topRight[1],
                                    width: width,
                                    height: height
                                },
                                style: {
                                    fill: '#5580F7'
                                }
                            };
                        },
                        data: data,
                        itemStyle: {
                            color: '#5580F7'
                        }
                    }
                ]
            };

            this.stationChart.setOption(option);
        },

        // 初始化箱线图
        initBoxPlotChart() {
            const chartDom = document.getElementById('box-plot-chart')
            if (!chartDom) return

            this.boxPlotChart = echarts.init(chartDom)
            // 初始化为空数据，等待API数据更新
            this.updateBoxPlotChart([]);
        },

        // 更新箱线图数据
        updateBoxPlotChart(boxPlotData) {
            if (!this.boxPlotChart) return;
            let outliers = [];
            // 提取x轴标签和箱线图数据
            const xAxisData = boxPlotData.map(item => item.groupName || '');
            const seriesData = boxPlotData.map(item => {
                const { boxPlotData: ele } = item;

                if (ele.outliers && ele.outliers.length > 0) {

                    outliers.push(ele.outliers);
                } else {
                    outliers.push([]); // 如果没有离散点，也要推入空数组
                }

                return [ele.lowerBound, ele.q1, ele.median, ele.q3, ele.upperBound]
            });

            // 生成离散点数据
            const scatterData = [];
            outliers.forEach((outlierGroup, groupIndex) => {
                if (outlierGroup && outlierGroup.length > 0) {
                    outlierGroup.forEach(outlierValue => {
                        scatterData.push([groupIndex, outlierValue]);
                    });
                }
            });

            const option = {
                tooltip: {
                    trigger: 'item',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: function (params) {
                        const data = params.data;
                        if (Array.isArray(data) && data.length === 5) {
                            return `最小值: ${data[0].toFixed(2)}<br/>
                                    下四分位数: ${data[1].toFixed(2)}<br/>
                                    中位数: ${data[2].toFixed(2)}<br/>
                                    上四分位数: ${data[3].toFixed(2)}<br/>
                                    最大值: ${data[4].toFixed(2)}`;
                        }
                        return params.name;
                    }
                },
                grid: {
                    left: '10%',
                    right: '10%',
                    bottom: '15%'
                },
                xAxis: {
                    type: 'category',
                    data: xAxisData,
                    boundaryGap: true,
                    nameGap: 30,
                    splitArea: {
                        show: false
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '',
                    splitLine: {
                        show: false // 移除水平刻度线
                    },
                    splitArea: {
                        show: true
                    }
                },
                series: [{
                    name: '查获数量分布',
                    type: 'boxplot',
                    showBackground: true,
                    backgroundStyle: {
                        color: '#F8F8FF'
                    },
                    data: seriesData,
                    itemStyle: function (params) {
                        // 配置颜色顺序为#CFADF9 #F9ADAD #76E1CE #97A1FC #E7C581
                        const colors = ['#CFADF9', '#F9ADAD', '#76E1CE', '#97A1FC', '#E7C581'];
                        const colorIndex = params.dataIndex % colors.length;
                        return {
                            color: colors[colorIndex],
                            borderColor: colors[colorIndex]
                        };
                    }
                }, {
                    name: '离散点',
                    type: 'scatter',
                    data: scatterData,
                    symbolSize: 6,
                    itemStyle: {
                        color: '#ff0000'
                    },
                    // label: {
                    //     show: true,
                    //     formatter: function(params) {
                    //         return params.value[1].toFixed(2); // 显示y轴数值，保留2位小数
                    //     },
                    //     position: 'top',
                    //     fontSize: 10
                    // },
                    tooltip: {
                        show: true,
                        formatter: function (params) {
                            return `${params.value[1].toFixed(2)}`;
                        }
                    }
                }]
            };

            this.boxPlotChart.setOption(option);
        },

        // 计算百分比
        getPercentage(value, data) {
            if (!data || data.length === 0) return 0
            const maxValue = Math.max(...data.map(item => Number(item.efficiency) || 0))
            if (maxValue === 0) return 0
            return (Number(value) || 0) / maxValue * 100
        },

        // 显示名称提示
        showNameTooltip(row) {
            const displayName = row.className || row.deptName;

            if (!displayName) return;
            uni.showToast({
                title: displayName,
                icon: 'none',
                duration: 2000
            });
        }
    }
}
</script>

<style lang="scss" scoped>
// 时间范围选择样式
.time-range-section {
    margin-bottom: 30rpx;

    .time-tags-container {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 7rpx;

        .time-tag {
            padding: 7rpx 14rpx;
            border-radius: 8rpx;
            font-size: 26rpx;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1rpx solid #DCDFE6;
            background: #FFFFFF;
            color: #606266;

            &.active {
                background: #5884F7;
                color: #FFFFFF;
                border-color: #5884F7;
            }

            &.time-range-label {
                border: none;
                background: transparent;
                color: #333333;
                font-weight: bold;
                cursor: default;
                padding-left: 0;
            }
        }

        .custom-time-inline {
            display: flex;
            align-items: center;
            gap: 16rpx;

            .date-range-picker {
                flex: 1;
                min-width: 300rpx;

                ::v-deep .icon-calendar {
                    display: none !important;
                }

                ::v-deep .uni-date-range {
                    font-size: 16rpx !important;
                    background: transparent !important;
                    color: black !important;
                }

                ::v-deep .uni-date-x {
                    height: 25rpx !important;
                    line-height: 25rpx !important;

                    .range-separator {
                        font-size: 20rpx !important;
                        padding: 0 !important
                    }

                    .uni-date__x-input {
                        height: 25rpx !important;
                        line-height: 25rpx !important;
                    }
                }

                ::v-deep .uni-date-x--border {
                    border: none !important;
                }
            }

            .days-count {
                font-size: 26rpx;
                color: #999999;
                white-space: nowrap;
            }
        }
    }
}

// 全局section-title样式
.section-title {
    font-size: 32rpx;
    font-weight: 900;
    /* 加粗 */
    color: #1a1a1a;
    /* 文字颜色加深 */
    margin-bottom: 24rpx;
    padding-left: 20rpx;
    /* 添加padding-left */
}

.section {
    margin-bottom: 40rpx;
}

// 查获效率部分样式
.efficiency-section {
    background: #FFFFFF;
    border-radius: 20rpx;
    padding: 40rpx 34rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

// 数据网格样式
.data-grid-container {
    background: #EFF2FE;
    border-radius: 15rpx;
    padding: 27rpx 23rpx;
    margin-bottom: 30rpx;
}

.data-grid-title {
    font-size: 28rpx;
    font-weight: bold;
    /* 加粗 */
    color: #333333;
    padding-left: 20rpx;
    margin-bottom: 15rpx;
    text-align: left;
}

.data-grid {
    display: flex;
    justify-content: space-evenly;

    .data-item {
        display: flex;
        flex: 1;
        flex-direction: column;
        align-items: center;
        text-align: center;
        position: relative;

        .data-value {
            font-size: 34rpx;
            font-weight: bold;
            color: #333333;
            margin-bottom: 8rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 50rpx;
        }

        .data-image {
            width: 40rpx;
            height: 40rpx;
            border-radius: 8rpx;
        }

        .data-label {
            font-size: 24rpx;
            color: #999999;
        }

        .divider {
            position: absolute;
            right: -4%;
            top: 50%;
            transform: translateY(-50%);
            width: 1rpx;
            height: 60%;
            background: rgba(0, 0, 0, 0.1);
        }
    }
}

// 排行样式
.rank-section {
    margin-bottom: 15rpx;

    .rank-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
    }

    .rank-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333333;
    }

    .sort-buttons {
        display: flex;

        div:nth-child(1) {
            border-radius: 8rpx 0 0 8rpx;
        }

        div:nth-child(2) {
            border-radius: 0 8rpx 8rpx 0;
        }

        .sort-btn {
            padding: 8rpx 16rpx;
            border: 1rpx solid #DCDFE6;

            font-size: 24rpx;
            color: #606266;
            cursor: pointer;

            &.active {
                background: #5884F7;
                color: #FFFFFF;
                border-color: #5884F7;
            }
        }
    }

    .rank-item {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;

        .rank-label {
            width: 120rpx;
            font-size: 26rpx;
            color: #333;
        }

        .rank-progress {
            flex: 1;
            margin: 0 20rpx;
        }

        .rank-info {
            width: 80rpx;
            text-align: right;
            font-size: 26rpx;
            color: #666;
        }
    }
}

// 查获统计部分样式
.chart-section {
    background: #FFFFFF;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

// 图表样式
.chart-container {
    display: flex;
    flex-direction: column;
    gap: 30rpx;
}

.chart-item {
    .chart-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333333;

    }

    .chart {
        width: 100%;
        height: 450rpx;
    }

    .bar-chart {
        height: 550rpx;
    }
}

// 绩效评优部分样式
.performance-section {
    background: #FFFFFF;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

// 绩效评优样式
.button-group {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-bottom: 30rpx;

    .performance-btn {
        padding: 8rpx 16rpx;
        border: 1rpx solid #5884F7;
        border-radius: 8rpx;
        font-size: 26rpx;
        color: #5884F7;
        background: #FFFFFF;
        cursor: pointer;

        &.active {
            background: #5884F7;
            color: #FFFFFF;
        }
    }
}

.matrix-section {
    margin-bottom: 30rpx;

    .matrix-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333333;
        margin-bottom: 20rpx;
    }
}

.filter-section {
    .filter-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 20rpx;
        margin-bottom: 20rpx;

        .filter-group {
            display: flex;
            gap: 8rpx;

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

                label {
                    font-size: 26rpx;
                    color: #333;
                    white-space: nowrap;
                }

                .filter-select {
                    width: 200rpx !important;

                    ::v-deep .uni-stat-box {
                        background: transparent !important;
                        color: black !important;

                        .border-default {
                            border: none !important;
                        }
                    }
                }
            }
        }

        .sort-buttons {
            display: flex;

            div:nth-child(1) {
                border-radius: 8rpx 0 0 8rpx;
            }

            div:nth-child(2) {
                border-radius: 0 8rpx 8rpx 0;
            }

            .sort-btn {
                padding: 8rpx 16rpx;
                border: 1rpx solid #DCDFE6;

                font-size: 24rpx;
                color: #606266;
                cursor: pointer;

                &.active {
                    background: #5884F7;
                    color: #FFFFFF;
                    border-color: #5884F7;
                }
            }
        }


    }
}
</style>