<template>
    <div class="historical_change_chart">
        <div class="chart_title">
            <span class="secondary_title" style="font-weight: bold;">2、</span>
            <span class="secondary_title" v-if="titleParts.knowledgeName">{{ titleParts.knowledgeName }} / </span>
            <span class="main_title">历次变化</span>
        </div>
        <div style="position: relative">
            <el-checkbox @change="(e) => { this.allSeriesSelected = e; this.toggleAllSeries(e); }"
                v-model="allSeriesSelected" :indeterminate="isIndeterminate" class="checkbox"
                v-if="hasData">显示全部</el-checkbox>
            <div ref="chart" class="chart" v-show="hasData"></div>
            <div v-show="!hasData" class="module_chart no_content_data no_data" element-loading-background="#ffffff">
                <span>暂无数据</span>
            </div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
    name: 'HistoricalChangeChart',
    props: {
        // 个人得分率
        personalList: {
            type: Array,
            default: () => []
        },
        // 班级得分率
        classList: {
            type: Array,
            default: () => []
        },
        // 年级得分率
        gradeList: {
            type: Array,
            default: () => []
        },
        // 考试名称
        examName: {
            type: Array,
            default: () => []
        },

        // 知识点名称
        knowledgeName: {
            type: String,
            default: ''
        },
    },
    computed: {
        // 判断是否有数据
        hasData() {
            return this.personalList && this.personalList.length > 0 &&
                ((this.classList && this.classList.length > 0) ||
                    (this.gradeList && this.gradeList.length > 0) ||
                    (this.examName && this.examName.length > 0));
        },

        // 动态生成标题各部分
        titleParts() {
            return {
                knowledgeName: this.knowledgeName || ''
            };
        }
    },
    data() {
        return {
            chart: null, // echarts实例
            allSeriesSelected: true, // 显示全部复选框状态
            isIndeterminate: false, // 不确定状态
        };
    },
    mounted() {
        // 初始化echarts图表，确保DOM渲染完成
        this.$nextTick(() => {
            if (this.hasData) {
                this.initChart();
            }
        });

        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            if (this.chart) {
                this.chart.resize();
            }
        });
    },
    beforeDestroy() {
        // 销毁echarts实例
        if (this.chart) {
            this.chart.dispose();
        }
    },
    watch: {
        // 监听hasData变化，动态初始化或销毁图表
        hasData(newVal) {
            this.$nextTick(() => {
                if (newVal) {
                    this.initChart();
                } else if (this.chart) {
                    this.chart.dispose();
                    this.chart = null;
                }
            });
        },
        // 监听props变化，动态更新图表数据
        personalList: {
            handler(newVal) {
                if (this.hasData) {
                    this.initChart();
                }
            },
            deep: true
        },
        classList: {
            handler(newVal) {
                if (this.hasData) {
                    this.initChart();
                }
            },
            deep: true
        },
        gradeList: {
            handler(newVal) {
                if (this.hasData) {
                    this.initChart();
                }
            },
            deep: true
        },
        examName: {
            handler(newVal) {
                if (this.hasData) {
                    this.initChart();
                }
            },
            deep: true
        },
    },
    methods: {
        // 初始化echarts图表
        initChart() {
            // 销毁现有的图表实例
            if (this.chart) {
                this.chart.dispose();
            }

            // 创建echarts实例
            this.chart = echarts.init(this.$refs.chart);

            // 使用props中的数据
            const examNames = this.examName; // 考试名称
            const personalList = this.personalList; ///个人得分率
            const classList = this.classList; //班级得分率
            const gradeList = this.gradeList; //年级得分率
            // 动态生成series数组，只包含有数据的系列
            const series = [];
            const legendData = [];
            // 判断个人得分率数据是否有效（非空且包含有效值）
            const hasPersonalData = personalList && personalList.length > 0 && personalList.some(data => data !== null && data !== undefined && data !== '');
            // 如果有个人得分率数据，添加个人得分率系列（使用柱状图）
            if (hasPersonalData) {
                // 将personalList转换为数字数组，确保echarts能正确显示
                const numericPersonalList = personalList.map(val => {
                    const num = parseFloat(val);
                    return isNaN(num) ? null : num;
                });

                series.push({
                    name: '个人',
                    type: 'bar',
                    data: numericPersonalList,
                    barWidth: 60,
                    itemStyle: {
                        color: '#5470C6'
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}%',
                        fontSize: 14,
                        color: '#666666'
                    }
                });
                legendData.push('个人');
            }

            // 计算动态的最大值，基于所有数据的最大值
            const allValues = [
               ...(personalList || []).filter(v => v !== null && v !== undefined)
            ];
            const maxValue = allValues.length > 0 ? Math.max(...allValues) : 0;
            // 动态计算y轴最大值，满格显示
            const dynamicMax = maxValue > 0 ? Math.ceil(maxValue / 10) * 10 : 100;

            // 配置项
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        if (params.length === 0) return '';
                        let result = `<span style="font-size:14px; font-weight:bold;">${params[0].name}</span>` + ':<br/>';
                        params.forEach(item => {
                            // 只处理个人数据
                            if (item.seriesName !== '个人') return;
                            
                            let span = `<span 
                                        style="
                                        background-color:#5470C6;
                                        width:10px;
                                        height:10px;
                                        display:block;
                                        float:left;
                                        position:absolute;
                                        top:7px;
                                        left:2px;
                                        "></span>`;
                            
                            if (item.value !== null && item.value !== undefined && item.value !== '') {
                                result += `<div style="width:100%; margin:0; padding:0; position:relative; padding-left:20px;">${span} <span style="font-size:12px;">个人得分率: ${item.value}%</span></div>`;
                            } else {
                                result += `<div style="width:100%; margin:0; padding:0; position:relative; padding-left:20px;">
                                    ${span} <span style="font-size:12px;">个人得分率:暂无数据</span>
                                </div>`;
                            }
                        });
                        return result;
                    }
                },
                legend: {
                    data: legendData,
                    left: 90,
                    top: -2,
                    orient: 'horizontal',
                    itemGap: 20,
                    itemWidth: 20,
                    itemHeight: 10,
                    textStyle: {
                        fontSize: 12,
                        color: '#333'
                    },
                    selectedMode: 'multiple',
                    selected: {
                        // 默认选中所有有数据的系列
                        ...(hasPersonalData ? { '个人': true } : {}),
                    }
                },
                grid: {
                    left: '0%',
                    right: '0%',
                    bottom: '2%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: examNames,
                    axisLabel: {
                        fontSize: 14,
                        rotate: 0,
                        color: '#666',
                        formatter: function (value) {
                            // 名称过长时换行，每4个字符换一行
                            if (value.length > 10) {
                                return value.replace(/(.{10})/g, '$1\n');
                            }
                            return value;
                        },
                        height: 60, // 设置足够的高度来容纳多行标签
                        verticalAlign: 'top'
                    }
                },
                yAxis: {
                    type: 'value',
                    // name: '百分比',
                    axisLabel: {
                        formatter: '{value}%',
                        fontSize: 14,
                        color: '#666',
                    },
                    max: dynamicMax
                },
                series: series
            };

            // 设置配置项
            this.chart.setOption(option);

            // 监听图例点击事件，更新全选状态
            this.chart.on('legendselectchanged', (params) => {
                const selected = params.selected;
                const selectedSeriesCount = Object.values(selected).filter(Boolean).length;
                const totalSeriesCount = legendData.length;

                // 检查是否所有系列都被选中
                const isAllSelected = selectedSeriesCount === totalSeriesCount;
                const isNoneSelected = selectedSeriesCount === 0;

                this.$nextTick(() => {
                    this.allSeriesSelected = isAllSelected;
                    this.isIndeterminate = !isAllSelected && !isNoneSelected;
                });
            });
        },

        // 切换所有系列的显示状态
        toggleAllSeries(showAll) {
            if (this.chart) {
                // 动态生成selected对象，只包含有数据的系列
                const selected = {};


                // 判断个人数据是否有效
                const hasPersonalData = this.personalList && this.personalList.length > 0 && this.personalList.some(data => data !== null && data !== undefined);

                if (hasPersonalData) selected['个人'] = showAll;


                this.chart.setOption({
                    legend: {
                        selected: selected
                    }
                });
                this.isIndeterminate = false;
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.historical_change_chart {
    background: #FFFFFF;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 10px;
    height: 316px;
    display: flex;
    flex-direction: column;

    .chart_title {
        font-size: 16px;
        margin-bottom: 20px;

        .main_title {
            font-weight: 600;
            color: #333;
        }

        .secondary_title {
            font-weight: normal;
            color: #999;
        }
    }

    .chart {
        flex: 1;
        width: 100%;
        height: calc(100% - 10px);
        min-height: 290px;

    }

    .radios {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        display: inline-block;
    }

    [style^="position: relative"] {
        flex: 1;
        display: flex;
        flex-direction: column;
    }

    .checkbox {
        position: absolute;
        left: 0;
        top: -2px;
        color: #333;

        // margin-top: 4px;
        :deep(.el-checkbox__label) {
            font-size: 12px !important;
        }
    }

    .no_data {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 220px;
        font-size: 14px;
        color: #999999;
        border-radius: 4px;

        span {
            margin-top: 11%;
        }
    }
}
</style>
