<template>
    <uni-collapse>
        <profile-collapse-item title="组织支撑" name="organizationSupport" :borderColor="'#007AFF'">
            <div class="detail-card">

                <!-- 左右布局的文字信息 -->
                <div class="text-layout">
                    <div class="content-item">
                        <div class="item-label">胜任岗位数统计</div>
                        <!-- <div class="item-value">{{ showData.positionCount || '-' }}</div> -->
                    </div>
                    <div class="content-item">

                        <div class="item-value">{{ showData.positionText || '-' }}</div>
                    </div>
                    <div class="content-item" style="margin-bottom: 18rpx;">
                        <div class="item-label">人均在岗时长</div>
                        <div class="item-value">{{ showData.averagePersonnel || '-' }}</div>
                    </div>
                </div>

                <!-- 资质能力统计图 -->
                <div class="chart-section">
                    <h4 class="chart-title">资质能力统计图</h4>
                    <div class="chart-container">
                        <div ref="qualificationChart" class="chart"></div>
                    </div>
                </div>

                <!-- 培训测试平均分趋势图 -->
                <div class="chart-section">
                    <h4 class="chart-title">培训测试平均分趋势图</h4>
                    <div class="chart-container">
                        <div ref="trainingChart" class="chart"></div>
                    </div>
                </div>
            </div>
        </profile-collapse-item>
    </uni-collapse>

</template>

<script>
import * as echarts from 'echarts'
import useDictMixin from "@/utils/dict";
import ProfileCollapseItem from './profile-collapse-item.vue'
export default {
    name: 'OrganizationSupport',
    components: {
        ProfileCollapseItem
    },

    mixins: [useDictMixin],
    inject: ['overviewData', 'moduleMetricsData', 'getTrainingTestScoreTrendData'],
    data() {
        return {
            charts: {},
            showData: {}
        }
    },
    computed: {
        organization() {
            return this.overviewData.organization || ''
        },
        moduleMetrics() {
            return this.moduleMetricsData() || {}
        },
        testScoreTrend() {
            return this.getTrainingTestScoreTrendData() || []
        },
        channelOpenTrend() {
            return this.getChannelOpenTrendChartData() || []
        },
    },
    mounted() {
        this.initCharts()

    },
    beforeDestroy() {
        Object.values(this.charts).forEach(chart => {
            chart && chart.dispose()
        })
    },
    watch: {
        moduleMetrics: {
            handler(newVal, oldVal) {
                this.updateQualificationChart()
                const positionCompetencyStats = newVal.system && newVal.system.positionCompetencyStats || []
                let positionText = []
                for (const item of positionCompetencyStats) {
                    positionText.push(`${item.postName} ${item.competentCount}人`)
                }
                this.showData = {
                    averagePersonnel: newVal.attendance.workingHours.averagePersonnel || '-',
                    positionText: positionText.join('、'),
                    positionCount: positionCompetencyStats.reduce((acc, cur) => acc + cur.competentCount, 0) || '-',
                }
            },
            deep: true
        },
        testScoreTrend: {
            handler(newVal, oldVal) {
                this.updateTrainingChart()
            },
            deep: true
        },

    },
    methods: {
        initCharts() {
            this.initQualificationChart()
            this.initTrainingChart()
        },

        updateCharts() {
            this.updateQualificationChart()
            this.updateTrainingChart()
        },

        initQualificationChart() {
            const chartDom = this.$refs.qualificationChart
            if (!chartDom) return

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

        async updateQualificationChart() {
            const chart = this.charts.qualification
            if (!chart) return
            const dict = await this.useDict('sys_user_qualification_level')
            const qualificationDict = dict['sys_user_qualification_level'] || [];

            // 获取availablePositions数据，如果没有数据则使用默认数据
            let qualificationLevel = this.moduleMetrics.system && this.moduleMetrics.system.qualificationLevelStats || []
            //let qualificationLevelArr = qualificationLevel.filter(item => item.levelName)

            // 转换数据格式用于环形图
            const chartData = qualificationLevel.map((position, index) => ({
                value: position.count, // 使用索引+1作为值，确保每个岗位都有值
                name: position.levelName
            }))



            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        return `${params.name}: ${params.value}`;
                    }
                },
                legend: {
                    orient: 'vertical',
                    right: 5,
                    top: 'center',
                    itemGap: 8,
                    textStyle: {
                        fontSize: 10
                    },
                    itemWidth: 10,
                    itemHeight: 8
                },
                series: [{
                    name: '可用岗位',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    center: ['45%', '50%'],
                    avoidLabelOverlap: false,

                    label: {
                        show: true,
                        formatter: '{b}: {c}'
                    },

                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 18,
                            fontWeight: 'bold',
                            formatter: '{b}\n{c}'
                        }
                    },

                    data: chartData.length > 0 ? chartData : [
                        { value: 1, name: '暂无岗位数据' }
                    ]
                }]
            }

            chart.setOption(option)
        },

        initTrainingChart() {
            const chartDom = this.$refs.trainingChart
            if (!chartDom) return

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

        updateTrainingChart() {
            const chart = this.charts.training
            if (!chart) return

            // 处理testScoreTrend数据
            const xAxisData = this.testScoreTrend.map(item => {
                // 格式化日期，只显示月份和日期
                const date = new Date(item.date);
                return `${date.getMonth() + 1}月${date.getDate()}日`;
            });

            const yAxisData = this.testScoreTrend.map(item => item.number);

            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        const data = params[0];
                        const originalData = this.testScoreTrend[data.dataIndex];
                        return `${originalData.name}<br/>${originalData.date}: ${originalData.number}分`;
                    }.bind(this)
                },
                xAxis: {
                    type: 'category',
                    data: xAxisData,
                    axisLabel: {
                        rotate: 45, // 日期标签旋转45度，避免重叠

                    }
                },
                yAxis: {
                    type: 'value',
                    min: function (value) {
                        // 设置y轴最小值，留出一些空间
                        return Math.max(0, Math.floor(value.min * 0.9));
                    },
                    max: function (value) {
                        // 设置y轴最大值，留出一些空间
                        return Math.min(100, Math.ceil(value.max * 1.1));
                    }
                },
                series: [{
                    data: yAxisData,
                    type: 'line',
                    smooth: true,
                    lineStyle: {
                        color: '#4873E3',
                        width: 3
                    },
                    itemStyle: {
                        color: '#4873E3'
                    },
                    areaStyle: {
                        color: 'rgba(72, 115, 227, 0.3)'
                    },
                    // markPoint: {
                    //     data: [
                    //         { type: 'max', name: '最高分' },
                    //         { type: 'min', name: '最低分' }
                    //     ]
                    // }
                }]
            }

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

<style lang="scss" scoped>
.content-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;

    &:last-child {
        margin-bottom: 0;
    }
}

.item-label {
    font-size: 28rpx;
    color: #333333;
    font-weight: 500;
    min-width: 120rpx;
}

.item-value {
    font-size: 28rpx;
    color: #999999;
    font-weight: 500;
}

.detail-card {

    padding: 10rpx 30rpx;


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

    .text-layout {}

    .chart-section {
        width: 100%;

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

        .chart-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 400rpx;
            width: 100%;

            .chart {
                width: 100%;
                height: 100%;
            }
        }
    }
}
</style>