<template>
    <uni-collapse>
        <profile-collapse-item title="工作产出" name="workOutput" :borderColor="'#FF9500'">
            <div class="detail-card">

                <!-- 通道开放趋势图 -->
                <div class="chart-section">
                    <h4 class="chart-title">通道开放趋势图</h4>
                    <div ref="channelChart" class="chart"></div>
                </div>

                <!-- 巡检问题统计图 -->
                <div class="chart-section">
                    <h4 class="chart-title">巡检问题统计图</h4>
                    <div ref="inspectionChart" class="chart"></div>
                </div>

                <!-- 查获上报统计 -->
                <div class="chart-section">
                    <h4 class="chart-title">查获上报统计</h4>

                    <!-- 三个统计项横向展示 -->
                    <div class="seizure-stats">
                        <div class="stat-item">
                            <div class="stat-label">查获总数</div>
                            <div class="stat-value">{{ (itemData.effectiveSeizureCount &&
                                itemData.effectiveSeizureCount.totalCount)
                                || 0 }}</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-label">移交公安</div>
                            <div class="stat-value">{{ (itemData.referToPoliceCount &&
                                itemData.referToPoliceCount.totalCount) || 0
                                }}</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-label">隐匿夹带</div>
                            <div class="stat-value">{{ (itemData.willfulConcealmentCount &&
                                itemData.willfulConcealmentCount.totalCount) || 0 }}</div>
                        </div>
                    </div>

                    <!-- 查获趋势图 -->
                    <h4 class="chart-title">查获趋势图</h4>
                    <div class="chart-container">
                        <div ref="seizureTrendChart" class="chart"></div>
                    </div>
                </div>
            </div>
        </profile-collapse-item>
    </uni-collapse>


</template>

<script>
import * as echarts from 'echarts'
import ProfileCollapseItem from './profile-collapse-item.vue'

export default {
    name: 'WorkOutput',
    components: {
        ProfileCollapseItem
    },
    inject: ['getPortraitData', 'moduleMetricsData', 'getInspectionProblemChartData', 'getChannelOpenTrendChartData', 'getSeizureTrendChartData'],
    data() {
        return {
            charts: {},
            seizureStats: {
                total: 0,
                transferPolice: 0,
                hiddenCarry: 0
            }
        }
    },
    computed: {
        portraitData() {
            return this.getPortraitData()
        },
        moduleMetrics() {
            return this.moduleMetricsData()
        },
        itemData() {
            return this.moduleMetrics && this.moduleMetrics.item || {}
        },
        inspectionProblemData() {
            return this.getInspectionProblemChartData()
        },
        channelOpenTrendData() {
            return this.getChannelOpenTrendChartData()
        },
        seizureTrendData() {
            return this.getSeizureTrendChartData()
        }
    },
    watch: {
        inspectionProblemData: {
            handler(newVal, oldVal) {
                this.updateInspectionChart()
            },
            deep: true
        },
        channelOpenTrendData: {
            handler(newVal, oldVal) {
                this.updateChannelChart()
            },
            deep: true
        },
        seizureTrendData: {
            handler(newVal, oldVal) {
                this.updateSeizureTrendChart()
            },
            deep: true
        }
    },
    mounted() {
        this.initCharts()

    },
    beforeDestroy() {
        Object.values(this.charts).forEach(chart => {
            chart && chart.dispose()
        })
    },
    methods: {
        initCharts() {
            this.initChannelChart()
            this.initInspectionChart()
            this.initSeizureTrendChart()
        },

        updateCharts() {
            this.updateChannelChart()
            this.updateInspectionChart()
            this.updateSeizureTrendChart()
        },

        initChannelChart() {
            const chartDom = this.$refs.channelChart
            if (!chartDom) return

            this.charts.channel = echarts.init(chartDom)
        },

        updateChannelChart() {
            const chart = this.charts.channel
            if (!chart) return

            // 使用channelOpenTrendData数据
            const channelData = this.channelOpenTrendData.trend || []
            const avg = this.channelOpenTrendData.avg || 0
            // 提取日期、通道数和开放时长
            const dates = channelData.map(item => item.date)
            const openCounts = channelData.map(item => item.openCount || 0)
            const openDurations = channelData.map(item => item.openDuration || 0)

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        let result = `日期: ${params[0].name}<br/>`
                        params.forEach(param => {
                            let value = param.value
                            if (param.seriesName === '开放时长') {
                                value = `${param.value}小时`
                            } else if (param.seriesName === '平均线') {
                                value = `平均值: ${param.value}`
                            }
                            result += `${param.marker} ${param.seriesName}: ${value}<br/>`
                        })
                        return result
                    }
                },
                legend: {
                    data: ['通道开放数', '开放时长', '平均线'],

                    left: 'center',
                    textStyle: {
                        fontSize: 12
                    }
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisLabel: {
                        rotate: 45, // 日期标签旋转45度，避免重叠
                        fontSize: 10
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '通道数',
                        position: 'left',
                        min: 0,
                        interval: function() {
                            // 动态计算间隔，确保刻度不会太密
                            const maxCount = Math.max(...openCounts, 5);
                            return maxCount > 10 ? 5 : 3;
                        }(),
                        axisLine: {
                            lineStyle: {
                                color: '#4CAF50'
                            }
                        },
                        axisLabel: {
                            formatter: '{value}'
                        }
                    },
                    {
                        type: 'value',
                        name: '时长(小时)',
                        position: 'right',
                        min: 0,
                        interval: function () {
                            // 动态计算间隔，确保刻度不会太密
                            const maxDuration = Math.max(...openDurations, 10);
                            return maxDuration > 20 ? 10 : 5;
                        }(),
                        axisLine: {
                            lineStyle: {
                                color: '#2196F3'
                            }
                        },
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }
                ],
                grid: {
                    left: '5%',
                    right: '5%',
                    top: '25%', // 增加顶部间距，降低y轴高度
                    bottom: '18%', // 为缩放控件留出空间
                    containLabel: true
                },
                dataZoom: [
                    {
                        type: 'inside', // 内置型数据区域缩放
                        start: 0, // 初始缩放范围
                        end: 100
                    },
                    {
                        type: 'slider', // 滑动条型数据区域缩放
                        show: true,
                        start: 0,
                        end: 100,
                        bottom: '5%',
                        height: 20
                    }
                ],
                series: [
                    {
                        name: '通道开放数',
                        data: openCounts,
                        type: 'line',
                        smooth: true,
                        yAxisIndex: 0,
                        lineStyle: {
                            color: '#4CAF50',
                            width: 2
                        },
                        itemStyle: {
                            color: '#4CAF50'
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0,
                                    color: 'rgba(76, 175, 80, 0.3)'
                                }, {
                                    offset: 1,
                                    color: 'rgba(76, 175, 80, 0.1)'
                                }]
                            }
                        }
                    },
                    {
                        name: '开放时长',
                        data: openDurations,
                        type: 'line',
                        smooth: true,
                        yAxisIndex: 1,
                        lineStyle: {
                            color: '#2196F3',
                            width: 2
                        },
                        itemStyle: {
                            color: '#2196F3'
                        }
                    },
                    {
                        name: '平均线',
                        data: openCounts.map(() => avg), // 为每个数据点创建相同的平均值
                        type: 'line',
                        yAxisIndex: 0,
                        lineStyle: {
                            color: '#FF9800',
                            width: 2,
                            type: 'dashed' // 虚线表示平均线
                        },
                        itemStyle: {
                            color: '#FF9800'
                        },
                        symbol: 'none', // 不显示数据点
                        label: {
                            show: true,
                            position: 'end',
                            formatter: `平均值: {c}`
                        }
                    }
                ]
            }

            chart.setOption(option)
        },

        initInspectionChart() {
            const chartDom = this.$refs.inspectionChart
            if (!chartDom) return

            this.charts.inspection = echarts.init(chartDom)
        },

        updateInspectionChart() {
            const chart = this.charts.inspection
            if (!chart) return

            // 使用inspectionProblemData数据
            const inspectionData = this.inspectionProblemData || []

            // 计算最大值，用于雷达图刻度
            const maxTotal = inspectionData.length > 0 ? Math.max(...inspectionData.map(item => item.total || 0)) : 1

            // 构建雷达图维度指示器
            const indicator = inspectionData.map((item) => {
                return {
                    name: item.name || '未知维度',
                    max: maxTotal > 0 ? maxTotal : 1
                }
            })

            // 构建雷达图数据系列
            const seriesData = [{
                value: inspectionData.map((item) => {
                    return item.total || 0
                }),
                name: '巡检问题分布',
                lineStyle: {
                    color: '#4873E3',
                    width: 2
                },
                areaStyle: {
                    color: 'rgba(72, 115, 227, 0.3)'
                },
                itemStyle: {
                    color: '#4873E3'
                }
            }]

            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        // 雷达图的params.value是数组，需要与indicator对应
                        // 使用闭包访问外部的indicator变量
                        const values = params.value || []
                        let result = ``

                        indicator.forEach((item, index) => {
                            if (values[index] !== undefined) {
                                result += `${item.name}: ${values[index]}<br/>`
                            }
                        })

                        return result
                    }
                },
                radar: {
                    indicator: indicator,
                    shape: 'polygon',
                    splitNumber: 4,
                    radius: '55%',
                    axisName: {
                        color: '#666',
                        fontSize: 12
                    },
                    splitLine: {
                        lineStyle: {
                            color: ['rgba(238, 238, 238, 0.8)', 'rgba(238, 238, 238, 0.6)',
                                'rgba(238, 238, 238, 0.4)', 'rgba(238, 238, 238, 0.2)']
                        }
                    },
                    splitArea: {
                        show: true,
                        areaStyle: {
                            color: ['rgba(250, 250, 250, 0.8)', 'rgba(250, 250, 250, 0.6)',
                                'rgba(250, 250, 250, 0.4)', 'rgba(250, 250, 250, 0.2)']
                        }
                    }
                },
                series: [{
                    type: 'radar',
                    data: seriesData,
                    symbolSize: 6,
                    symbol: 'circle',
                    // label: {
                    //     show: true,
                    //     formatter: function(params) {
                    //         return params.value
                    //     }
                    // }
                }]
            }

            chart.setOption(option)
        },

        initSeizureTrendChart() {
            const chartDom = this.$refs.seizureTrendChart
            if (!chartDom) return

            this.charts.seizureTrend = echarts.init(chartDom)
        },

        updateSeizureTrendChart() {
            const chart = this.charts.seizureTrend
            if (!chart) return

            // 使用seizureTrendData数据
            const seizureData = this.seizureTrendData || []

            // 提取日期和查获数量
            const dates = seizureData.map(item => item.date)
            const totals = seizureData.map(item => item.total || 0)

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        const data = params[0]
                        return `日期: ${data.name}<br/>查获数量: ${data.value}`
                    }
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisLine: {
                        lineStyle: {
                            color: '#999'
                        }
                    },
                    axisLabel: {
                        color: '#666',
                        rotate: 45, // 日期标签旋转45度，避免重叠
                        fontSize: 10,

                    }
                },
                yAxis: {
                    type: 'value',
                    name: '查获数量',
                    min: 0,
                    max: function () {
                        // 计算最大值并向上取整到最近的整数，确保五等分
                        const maxTotal = Math.max(...totals, 5);
                        return Math.ceil(maxTotal / 5) * 5;
                    }(),
                    interval: function () {
                        // 固定为五等分
                        const maxTotal = Math.max(...totals, 5);
                        return Math.ceil(maxTotal / 5);
                    }(),
                    axisLine: {
                        lineStyle: {
                            color: '#999'
                        }
                    },
                    axisLabel: {
                        color: '#666'
                    },
                    splitLine: {
                        lineStyle: {
                            color: '#f0f0f0'
                        }
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%', // 为缩放控件留出空间
                    containLabel: true
                },
                dataZoom: [
                    {
                        type: 'inside', // 内置型数据区域缩放
                        start: 0, // 初始缩放范围
                        end: 100
                    },
                    {
                        type: 'slider', // 滑动条型数据区域缩放
                        show: true,
                        start: 0,
                        end: 100,
                        bottom: '5%',
                        height: 20
                    }
                ],
                series: [{
                    name: '查获数量',
                    type: 'line',
                    smooth: true,
                    data: totals,
                    lineStyle: {
                        width: 3,
                        color: '#FF6B6B'
                    },
                    itemStyle: {
                        color: '#FF6B6B'
                    },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: 'rgba(255, 107, 107, 0.3)'
                            }, {
                                offset: 1,
                                color: 'rgba(255, 107, 107, 0.1)'
                            }]
                        }
                    }
                }]
            }

            chart.setOption(option)
        }
    }
}
</script>

<style lang="scss" scoped>
.detail-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 10rpx 30rpx;
    // margin-bottom: 32rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

    .detail-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 24rpx;
    }

    .chart-section {
        .chart-title {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
            margin: 24rpx 0;
        }

        .chart-container {
            display: flex;
            align-items: center;

            .chart {
                flex: 1;
                height: 400rpx;
            }
        }

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

        /* 查获统计样式 */
        .seizure-stats {
            display: flex;
            justify-content: space-between;
            margin-bottom: 32rpx;
            background: #f8f9fa;
            border-radius: 12rpx;
            padding: 24rpx;

            .stat-item {
                flex: 1;
                text-align: center;
                padding: 0 16rpx;

                &:not(:last-child) {
                    border-right: 1rpx solid #e0e0e0;
                }

                .stat-label {
                    font-size: 24rpx;
                    color: #666;
                    margin-bottom: 8rpx;
                }

                .stat-value {
                    font-size: 36rpx;
                    font-weight: bold;
                    color: #4873E3;
                }
            }
        }
    }
}
</style>