<template>
    <div class="chart-wrap">
        <div id="chartdiv" ref="chartdiv"></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: [],
        },
        mapping: {
            type: Array,
            required: true,
        },
        columnX: {
            type: String
        },
        type: {
            type: String
        }
    },
    data() {
        return {

        };
    },
    methods: {
        chartCreate: function (data, columnX, mapping) {
            let chartWarp = this.$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; // 차트 정보 전역에 담기

            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 xRenderer = am5xy.AxisRendererX.new(root, {
                cellStartLocation: 0.1,
                cellEndLocation: 0.9
            })

            let xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
                categoryField: columnX,
                renderer: xRenderer,
                tooltip: am5.Tooltip.new(root, {})
            }));

            xRenderer.grid.template.setAll({
                location: 1
            })
            xRenderer.labels.template.setAll({
                oversizedBehavior: "truncate",
                maxWidth: 100
            })

            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, fieldName) {
                let series = chart.series.push(am5xy.ColumnSeries.new(root, {
                    name: name,
                    xAxis: xAxis,
                    yAxis: yAxis,
                    valueYField: fieldName,
                    categoryXField: columnX
                }));

                series.columns.template.setAll({
                    tooltipText: "{name} : {valueY}",
                    width: am5.percent(90),
                    tooltipY: 0,
                    strokeOpacity: 0
                });

                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);
            }
            const desiredOrder = this.getDesiredOrder();

            // let keys = Object.keys(data[0]); // 데이터 객체의 모든 키를 가져옵니다.
            for (let i = 0; i < desiredOrder.length; i++) {
                let key = desiredOrder[i];
                if (key !== 'stats_date' && key !== 'post_title' && key !== 'company_nm' && key !== 'title' && key !== 'real_file_nm') { // 'stats_date'를 제외하고 차트를 생성합니다.
                    let koreanKey = mapping[key]; // 영어 키를 한글로 맵핑합니다.
                    makeSeries(koreanKey, key);
                }
            }


            // Make stuff animate on load
            // https://www.amcharts.com/docs/v5/concepts/animations/
            chart.appear(1000, 100);
        },
        getDesiredOrder() {
            // 현재 활성화된 라우터에 따라 다른 desiredOrder를 반환
            if (this.$route.name === 'AdminMenuVisit') {
                if(this.type == 'view') {
                    return ['total', 'info', 'technology', 'databook', 'company', 'notice', 'news', 'wgcommunity'];
                } else {
                    return ['total', 'technology', 'databook', 'notice', 'news', 'wgcommunity'];
                }
                
            } else if (this.$route.name === 'AdminTech') {
                return ['total', 'company', 'common'];
            } else if (this.$route.name === 'AdminData') {
                return ['total', 'company', 'common'];
            } else if (this.$route.name === 'AdminCoporate') {
                return ['total', 'company', 'common'];
            } else if (this.$route.name === 'AdminNotice') {
                return ['total', 'company', 'common','non'];
            } else if (this.$route.name === 'AdminNewsAndPr') {
                return ['total', 'company', 'common','non'];
            }else if (this.$route.name === 'AdminWgCommunity') {
                return ['total', 'company', 'common'];
            } else if (this.$route.name === 'AdminMatching') {
                return ['succesee_cnt', 'failed_cnt', 'progress_cnt', 'to_cnt', 'from_cnt', 'total_cnt'];
            }
        }
    },
    watch: {
        'chartData': function (newData) {
            this.chartCreate(newData, this.columnX, this.mapping)
        }
    },
    computed: {

    },
    components: {

    },
    mounted() {
    }
}

export default App;
</script>
 
 
 