<template>
    <div ref="CategoryBarChart" class="chart-container"></div>
</template>

<script>
import * as am5 from '@amcharts/amcharts5';
import * as am5xy from '@amcharts/amcharts5/xy';
import am5themes_Animated from '@amcharts/amcharts5/themes/Animated';
import axios from 'axios';

export default {
    name: 'CategoryBarChart',

    data() {
        return {
            chartData: [],
            currentStdId: '1',
        };
    },

    mounted() {
        this.getCategoryScoreData();
    },

    methods: {
        // 카테고리별 점수 데이터 가져오기
        getCategoryScoreData() {
            const vm = this;
            axios
                .post('/dashboard/categoryScoreData.json', {
                    std_id: vm.currentStdId,
                })
                .then((response) => {
                    vm.chartData = response.data.map((item) => ({
                        ...item,
                        combinedCategory: `${item.categoryNm}\n(${item.categoryCls})`,
                    }));
                    vm.createChart();
                })
                .catch((error) => {
                    console.error('카테고리 점수 데이터를 가져오는 중 오류 발생:', error);
                });
        },

        createChart() {
            // Initialize root
            const root = am5.Root.new(this.$refs.CategoryBarChart);

            // Apply themes
            root.setThemes([am5themes_Animated.new(root)]);

            // Create chart
            const chart = root.container.children.push(
                am5xy.XYChart.new(root, {
                    panX: false,
                    panY: false,
                    wheelX: 'panX',
                    wheelY: 'zoomX',
                    layout: root.verticalLayout,
                })
            );

            // Create axes
            const yAxis = chart.yAxes.push(
                am5xy.ValueAxis.new(root, {
                    renderer: am5xy.AxisRendererY.new(root, {}),
                    min: 0,
                })
            );

            const xAxis = chart.xAxes.push(
                am5xy.CategoryAxis.new(root, {
                    categoryField: 'combinedCategory',
                    renderer: am5xy.AxisRendererX.new(root, {}),
                    tooltip: am5.Tooltip.new(root, { themeTags: ['axis'] }),
                })
            );

            xAxis.get('renderer').labels.template.setAll({
                textAlign: 'center',
                centerX: am5.p50,
            });

            xAxis.data.setAll(this.chartData);

            // Create series
            const series = chart.series.push(
                am5xy.ColumnSeries.new(root, {
                    name: 'Category Scores',
                    xAxis: xAxis,
                    yAxis: yAxis,
                    valueYField: 'totalScore',
                    categoryXField: 'combinedCategory',
                    tooltip: am5.Tooltip.new(root, {
                        labelText: '{categoryX}: {valueY}',
                    }),
                })
            );

            // Set color manually for each bar (simplified for clarity)
            series.columns.template.setAll({
                fill: am5.color('#67b7dc'),
                stroke: am5.color('#67b7dc'),
                fillOpacity: 0.8, // Adjust opacity if needed
                strokeWidth: 0,
                cornerRadiusTL: 5,
                cornerRadiusTR: 5,
            });

            // Assign data
            series.data.setAll(this.chartData);

            // Add legend
            chart.children.push(
                am5.Legend.new(root, {
                    centerX: am5.p50,
                    x: am5.p50,
                    marginTop: 15,
                    marginBottom: 15,
                })
            );

            // Play initial series animation
            series.appear(1000, 100);
        },
    },
};
</script>

<style scoped>
/* 스타일은 필요에 따라 추가 */
.chart-container {
    display: block;
    position: absolute;
    bottom: 30px;
    right: 5px;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
