<template>
    <div class="chart-wrap">
        <div class="content"></div>
    </div>
</template>

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


const App = {
    props: {
        chartData: {
            type: Array,
            default: [],
        },
        columnX: {
            type: String
        },
        colors: {
            type: Array,
            default: ['#f46b75', '#ffcd70', '#74d4c0', '#6ccff6', '#b084cc', '#e6e9ec', '#4b6584', '#f7a1a6', '#bfeee8', '#f3e08a', '#95a5a6']
        }
    },
    data() {
        return {

        };
    },
    methods: {
        
        chartCreate: function (data, columnX, colors) {
            let chartWarp = this.$parent.$refs["chartdiv"]; // 차트 상위 div ref 매칭
            chartWarp.innerHTML = ""; // 차트 상위 div 내용 초기화 (기존 차트 삭제)
            let div = document.createElement("div"); // 차트를 담을 빈 div 생성 (차트 하위 div)
            div.style.width = "100%"; // 차트를 담을 div의 넓이
            div.style.height = "100%"; // 차트를 담을 div의 높이
            chartWarp.appendChild(div); // 차트 상위 div 안에 차트 하위 div를 추가
            let root = am5.Root.new(div); // 차트 하위 div에 차트(root) 담기
            this.charts = root; // 차트 정보 전역에 담기
            // am5.addLicense("AM5C11202011971121")
            // root._logo.dispose();

            // Set themes
            // https://www.amcharts.com/docs/v5/concepts/themes/
            root.setThemes([
                am5themes_Animated.new(root)
            ]);

            // Create chart
            // https://www.amcharts.com/docs/v5/charts/xy-chart/
            let chart = root.container.children.push(am5xy.XYChart.new(root, {
                panX: false,
                panY: false,
                wheelX: "panX",
                wheelY: "zoomX",
                layout: root.verticalLayout
            }));

            // Add legend
            // https://www.amcharts.com/docs/v5/charts/xy-chart/legend-xy-series/
            let legend = chart.children.push(
                am5.Legend.new(root, {
                    centerX: am5.p50,
                    x: am5.p50
                })
            );

            // Create axes
            // https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
            let xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
                categoryField: columnX,
                renderer: am5xy.AxisRendererX.new(root, {}),
                tooltip: am5.Tooltip.new(root, {})
            }));
            xAxis.labelsContainer.set("tooltip", am5.Tooltip.new(root, {
                pointerOrientation: "down"
            }));


            let xRenderer = xAxis.get("renderer");

            xRenderer.labels.template.setAll({
                tooltipText: "{category}",
                oversizedBehavior: "truncate",
                maxWidth: 150
            });

            xRenderer.labels.template.setup = function (target) {
                target.set("background", am5.Rectangle.new(root, {
                    fill: am5.color(0x000000),
                    fillOpacity: 0
                }));
            };

            xAxis.labelsContainer.set("tooltip", am5.Tooltip.new(root, {
                pointerOrientation: "down"
            }));

            xAxis.data.setAll(data);

            let yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
                min: 0,
                baseValue: 0,
                maxPrecision: 0,
                renderer: am5xy.AxisRendererY.new(root, {
                    strokeOpacity: 0
                })
            }));

            // Add series
            // https://www.amcharts.com/docs/v5/charts/xy-chart/series/
            function makeSeries(name, color) {
                let series = chart.series.push(am5xy.ColumnSeries.new(root, {
                    name: name,
                    xAxis: xAxis,
                    yAxis: yAxis,
                    valueYField: name,
                    categoryXField: columnX
                }));

                series.columns.template.setAll({
                    tooltipText: "{categoryX}\n{name}:{valueY}",
                    width: am5.percent(80),
                    tooltipY: 0,
                    strokeOpacity: 0,
                    fill: am5.color(color),
                });

                series.data.setAll(data);

                // Make stuff animate on load
                // https://www.amcharts.com/docs/v5/concepts/animations/
                series.appear();

                series.bullets.push(function () {
                    return am5.Bullet.new(root, {
                        locationY: 0,
                        sprite: am5.Label.new(root, {
                            text: "{valueY}",
                            fill: root.interfaceColors.get("alternativeText"),
                            centerY: 0,
                            centerX: am5.p50,
                            populateText: true,
                        })
                    });
                });

                legend.data.push(series);
            }

            let keyIndex = 0;
            if (this.chartData.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    if (keyIndex < Object.keys(data[i]).length) {
                        keyIndex = i;
                    }
                }

                let keys = Object.keys(data[0]); // 데이터 객체의 모든 키를 가져옵니다.
                for (let i = 0; i < keys.length; i++) {
                    let key = keys[i];
                    if (key !== columnX && key !== '전체' && key !== 'ttl') {
                        let color = colors[i % colors.length]; // 색상을 순환하여 적용
                        makeSeries(key, color);
                    }
                }
            }

            // Make stuff animate on load
            // https://www.amcharts.com/docs/v5/concepts/animations/
            chart.appear(1000, 100);
        },
    },
    watch: {
        'chartData': function (newData) {
            this.chartCreate(newData, this.columnX, this.colors)
        }
    },
    computed: {

    },
    components: {

    },
    mounted() {
    }
}

export default App;
</script>
