<template>
    <div class="chart-container" ref="chartdiv"></div>
</template>
  
<script>
import * as am5 from '@amcharts/amcharts5';
import * as am5xy from '@amcharts/amcharts5/xy';
import am5themes_Animated from '@amcharts/amcharts5/themes/Animated';

export default {
    props: {
        chartData: {
            type: Array,
            required: true,
        },
        keyMapping: {
            type: Object,
        },
        xField: {
            type: String,
            default: null
            // required: true,
        },

    },
    data() {
        return {
            chart: null,
        };
    },
    methods: {
        createChart(data, xField) {
            // console.log(typeof(xField));
            // let mappedData = [];
            // let keys = Object.keys(data[0]);

            // for (let dataIndex = 0; dataIndex < data.length; dataIndex++) {
            //     let currentItem = data[dataIndex];
            //     let mappedItem = {};

            //     for (let i = 0; i < keys.length; i++) {
            //         let key = keys[i];
            //         let koreanKey = keyMapping[key];

            //         if (koreanKey) {
            //             mappedItem[koreanKey] = currentItem[key];
            //         }
            //     }

            //     mappedData.push(mappedItem);
            // }

            // console.log("mappedData - ",mappedData)

            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: true,
                panY: true,
                wheelX: "panX",
                wheelY: "zoomX",
                pinchZoomX: true
            }));

            chart.get("colors").set("step", 3);


            // Add cursor
            // https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
            let cursor = chart.set("cursor", am5xy.XYCursor.new(root, {}));
            cursor.lineY.set("visible", false);


            // Create axes
            // https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
            let xRenderer = am5xy.AxisRendererX.new(root, {});
            let xAxis = chart.xAxes.push(
                am5xy.CategoryAxis.new(root, {
                    categoryField: xField,
                    renderer: xRenderer,
                })
            );
            xRenderer.grid.template.setAll({
                location: 1
            })

            /* let lineData = [
                { search_date: "2023-01-01", value1: 10, value2: 20, value3: 50 },
                { search_date: "2023-01-02", value1: 15, value2: 25, value3: 50 },
                { search_date: "2023-01-03", value1: 20, value2: 30, value3: 50 },
            ] */

            xAxis.data.setAll(data);

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

            // Add series
            Object.keys(data[0]).forEach((key, index) => {
                if (key !== xField) {
                    let series = chart.series.push(am5xy.LineSeries.new(root, {
                        name: key,
                        xAxis: xAxis,
                        yAxis: yAxis,
                        valueYField: key,
                        categoryXField: xField,
                        tooltip: am5.Tooltip.new(root, {
                            labelText: "{name}: {valueY}"
                        })
                    }));

                    series.strokes.template.setAll({
                        strokeWidth: 2
                    });

                    series.get("tooltip").get("background").set("fillOpacity", 0.5);
                    
                    /* console.log('!!!!!',data.map(item => ({
                        [xField]: item[xField],
                        [key]: item[key]
                    }))); */
                    console.log("data: ", key, xField, data);

                    // series.data.setAll(data.map(item => ({
                    //     [xField]: item[xField],
                    //     [key]: item[key]
                    // })));
                    series.data.setAll(data);
                    series.appear(1000);
                }
            });


            // Make stuff animate on load
            // https://www.amcharts.com/docs/v5/concepts/animations/
            /* chart.series.each((series) => {
                series.appear(1000);
            }); */
            chart.appear(1000, 100);

            // for (let i = 1; i < data.length; i++) {
            //         createSeries(valueDataList[i], valueDataList[i], options['seriesColorList'][i]);
            // }

        }

    },
    watch: {
        'chartData': function (newData) {
            this.createChart(newData ,this.xField);
        }
    },
    mounted() {
        // this.chart = this.createChart(this.data, this.xField, this.yField, this.colors, this.unit);
    },
};
</script>
  
<style scoped>
.chart-container {
    width: 100%;
    height: 400px;
}
</style>
  