<template>
    <uni-collapse>
        <profile-collapse-item title="管理推动" name="managementPush" :borderColor="'#00C853'">
            <div class="detail-card">

                <!-- 巡检任务执行趋势图 -->
                <div class="chart-section">
                    <h4 class="chart-title">巡检任务执行趋势统计图</h4>
                    <div ref="taskChart" class="chart"></div>
                </div>

                <!-- 整改统计 -->
                <div class="chart-section">
                    <h4 class="chart-title">整改统计</h4>
                    <div class="rectification-stats">
                        <h-legend :legend-data="rectificationData" :colorSize="20" :textSize="24" />
                        <h-line :data="rectificationData" :total="rectificationTotal" :itemWidth="300"
                            :lineHeight="'40'" />
                    </div>
                </div>

                <!-- 抽问抽答完成率趋势图 -->
                <div class="chart-section">
                    <h4 class="chart-title">抽问抽答完成率趋势图</h4>
                    <div ref="qaChart" class="chart"></div>
                </div>

                <!-- 查获审批时长统计 -->
                <div class="chart-section">
                    <h4 class="chart-title">查获审批时长统计</h4>
                    <statistic-table :columns="approvalColumns" :data="approvalData" />
                </div>
            </div>
        </profile-collapse-item>
    </uni-collapse>



</template>

<script>
import * as echarts from 'echarts'
import HLegend from '@/components/h-legend/h-legend.vue'
import HLine from '@/components/h-line/h-line.vue'
import StatisticTable from '@/components/statistic-table/statistic-table.vue'
import ProfileCollapseItem from './profile-collapse-item.vue'

export default {
    name: 'ManagementPush',
    components: {
        HLegend,
        HLine,
        StatisticTable,
        ProfileCollapseItem
    },
    inject: ['getLevelRateData', 'getManagementPushData', 'getManagementRectifyData', 'getDurationChartData'],
    data() {
        return {
            rectificationData: [],
            rectificationTotal: 0,
            approvalColumns: [
                { props: 'empty', title: '指标' },
                { props: 'duration', title: '时长' }
            ],
            approvalData: [],
            charts: {}
        }
    },
    computed: {
        levelRateData() {
            return this.getLevelRateData()
        },
        managementPushData() {
            return this.getManagementPushData()
        },
        managementRectifyData() {
            return this.getManagementRectifyData()
        },
        durationData() {
            return this.getDurationChartData()
        }
    },
    watch: {
        managementRectifyData: {
            handler(newVal) {
                this.handleData(newVal)
            },
            deep: true
        },
        levelRateData: {
            handler() {
                this.updateCharts()
            },
            deep: true
        },
        managementPushData: {
            handler() {
                this.updateTaskChart()
            },
            deep: true
        },
        durationData: {
            handler(newV) {
                this.approvalData = [
                    { empty: '平均审批时长', duration: newV.averageDurationText || '-' },
                    { empty: '最长审批时常', duration: newV.maxDurationText || '-' },
                    { empty: '最短审批时常', duration: newV.minDurationText || '-' }
                ]
            },
            deep: true
        },
    },
    mounted() {
        this.initCharts()
        this.updateCharts()
    },
    beforeDestroy() {
        Object.values(this.charts).forEach(chart => {
            chart && chart.dispose()
        })
    },
    methods: {
        handleData(newVal) {
            this.rectificationData = [
                { name: '按期整改', value: newVal.onTimeCompletedCount, color: '#4873E3' },
                { name: '超期整改', value: newVal.overTimeCompletedCount, color: '#FF6B6B' }
            ]
            this.rectificationTotal = newVal.onTimeCompletedCount + newVal.overTimeCompletedCount
        },
        initCharts() {
            this.initTaskChart()
            this.initQAChart()
        },

        updateCharts() {
            this.updateTaskChart()
            this.updateQAChart()
        },

        initTaskChart() {
            const chartDom = this.$refs.taskChart
            if (!chartDom) return

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

        updateTaskChart() {
            const chart = this.charts.task
            if (!chart) return

            // 处理managementPushData数据
            const managementData = this.managementPushData || []

            // 按日期分组数据
            const dateGroups = {}
            managementData.length && managementData.forEach(item => {
                if (!dateGroups[item.date]) {
                    dateGroups[item.date] = {
                        date: item.date,
                        dailyTask: 0,
                        specialTask: 0
                    }
                }

                if (item.typeDesc === '日常任务') {
                    dateGroups[item.date].dailyTask = item.total
                } else if (item.typeDesc === '专项任务') {
                    dateGroups[item.date].specialTask = item.total
                }
            })

            // 转换为数组并按日期排序
            const sortedData = Object.values(dateGroups).sort((a, b) => {
                return new Date(a.date) - new Date(b.date)
            })

            // 提取x轴数据（格式化日期）
            const xAxisData = sortedData.map(item => {
                const date = new Date(item.date)
                return `${date.getMonth() + 1}月${date.getDate()}日`
            })

            // 提取两条曲线的数据
            const dailyTaskData = sortedData.map(item => item.dailyTask)
            const specialTaskData = sortedData.map(item => item.specialTask)

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        let result = `${params[0].axisValue}<br/>`
                        params.forEach(param => {
                            result += `${param.seriesName}: ${param.value}<br/>`
                        })
                        return result
                    }
                },
                legend: {
                    data: ['日常任务', '专项任务'],
                    top: 10
                },
                dataZoom: [
                    {
                        type: 'slider', // 滑动条型数据区域缩放组件
                        show: true,
                        xAxisIndex: [0],
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 10,
                        backgroundColor: '#f5f5f5',
                        dataBackground: {
                            lineStyle: {
                                color: '#9C27B0',
                                width: 1,
                                opacity: 0.3
                            },
                            areaStyle: {
                                color: 'rgba(156, 39, 176, 0.1)'
                            }
                        },
                        fillerColor: 'rgba(156, 39, 176, 0.2)',
                        borderColor: '#ddd',
                        textStyle: {
                            color: '#666'
                        }
                    },
                    {
                        type: 'inside', // 内置型数据区域缩放组件
                        xAxisIndex: [0],
                        start: 0,
                        end: 100,
                        zoomOnMouseWheel: true, // 支持鼠标滚轮缩放
                        moveOnMouseMove: true, // 支持鼠标拖拽平移
                        moveOnMouseWheel: false
                    }
                ],
                xAxis: {
                    type: 'category',
                    data: xAxisData,
                    axisLabel: {
                        rotate: 45,

                        fontSize: 10
                    },
                    axisTick: {
                        alignWithLabel: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '任务数量'
                },
                series: [
                    {
                        name: '日常任务',
                        data: dailyTaskData,
                        type: 'line',
                        smooth: true,
                        lineStyle: {
                            color: '#9C27B0',
                            width: 3
                        },
                        itemStyle: {
                            color: '#9C27B0'
                        },
                        areaStyle: {
                            color: 'rgba(156, 39, 176, 0.3)'
                        }
                    },
                    {
                        name: '专项任务',
                        data: specialTaskData,
                        type: 'line',
                        smooth: true,
                        lineStyle: {
                            color: '#00BCD4',
                            width: 3
                        },
                        itemStyle: {
                            color: '#00BCD4'
                        },
                        areaStyle: {
                            color: 'rgba(0, 188, 212, 0.3)'
                        }
                    }
                ],
                grid: {
                    left: '5%',
                    right: '5%',
                    top: '15%',
                    bottom: '20%', // 增加底部空间给数据缩放组件
                    containLabel: true
                }
            }

            chart.setOption(option)
        },

        initQAChart() {
            const chartDom = this.$refs.qaChart
            if (!chartDom) return

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

        updateQAChart() {
            const chart = this.charts.qa
            if (!chart) return

            // 使用levelRateData数据
            const levelRateData = this.levelRateData || []
            const dates = levelRateData.map(item => item.date)
            const completedTasks = levelRateData.map(item => item.completedTasks)

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        const data = params[0]
                        return `${data.name}<br/>已完成任务: ${data.value}`
                    }
                },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisLabel: {
                        rotate: 45,

                        fontSize: 10
                    },
                    axisTick: {
                        alignWithLabel: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '已完成任务'
                },
                dataZoom: [
                    {
                        type: 'slider', // 滑动条型数据区域缩放组件
                        show: true,
                        xAxisIndex: [0],
                        start: 0,
                        end: 100,
                        height: 20,
                        bottom: 10,
                        backgroundColor: '#f5f5f5',
                        dataBackground: {
                            lineStyle: {
                                color: '#00BCD4',
                                width: 1,
                                opacity: 0.3
                            },
                            areaStyle: {
                                color: 'rgba(0, 188, 212, 0.1)'
                            }
                        },
                        fillerColor: 'rgba(0, 188, 212, 0.2)',
                        borderColor: '#ddd',
                        textStyle: {
                            color: '#666'
                        }
                    },
                    {
                        type: 'inside', // 内置型数据区域缩放组件
                        xAxisIndex: [0],
                        start: 0,
                        end: 100,
                        zoomOnMouseWheel: true, // 支持鼠标滚轮缩放
                        moveOnMouseMove: true, // 支持鼠标拖拽平移
                        moveOnMouseWheel: false
                    }
                ],
                series: [{
                    name: '已完成任务',
                    data: completedTasks,
                    type: 'line',
                    smooth: true,
                    lineStyle: {
                        color: '#00BCD4',
                        width: 3
                    },
                    itemStyle: {
                        color: '#00BCD4'
                    },
                    areaStyle: {
                        color: 'rgba(0, 188, 212, 0.3)'
                    }
                }],
                grid: {
                    left: '5%',
                    right: '5%',
                    top: '15%',
                    bottom: '20%', // 增加底部空间给数据缩放组件
                    containLabel: true
                }
            }

            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-bottom: 24rpx;
        }

        .chart {
            height: 500rpx;
        }

        .rectification-stats {
            .h-line {
                margin-top: 24rpx;
            }
        }
    }
}
</style>