<template lang="html">
  <div class="content"></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,
      default: [],
    },
    columnX: {
      type: String,
    },
  },
  data: function () {
    return {};
  },
  methods: {
    chartCreate: function (data, columnX) {
      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의 높이
      let root = am5.Root.new(div); // 차트 하위 div에 차트(root) 담기
      chartWarp.appendChild(div); // 차트 상위 div 안에 차트 하위 div를 추가
      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, {
          panY: false,
          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,
        })
      );

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

        series.columns.template.setAll({
          tooltipText: "[bold]{name}[/]\n: {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);
      }

      // 데이터 객체의 모든 키를 가져옵니다.
      let keyIndex = 0;
      for (let i = 0; i < data.length; i++) {
        if (keyIndex < Object.keys(data[i]).length) {
          keyIndex = i;
        }
      }
      let keys = Object.keys(data[keyIndex]);
      for (let key of keys) {
        if (key !== columnX) {
          createSeries(key);
        }
      }

      // Make stuff animate on load
      // https://www.amcharts.com/docs/v5/concepts/animations/
      chart.appear(1000, 100);
    },
  },
  computed: {},
  watch: {
    chartData: function (newData) {
      if (newData != null && newData.length > 0) {
        this.chartCreate(newData, this.columnX);
      }
    },
  },
  //beforeCreate: function () {},
  //created: function () {},
  //beforeUpdate: function () {},
  //updated: function () {},
  mounted: function () {
    if (this.chartData != null && this.chartData.length > 0) {
      this.chartCreate(this.chartData, this.columnX);
    }
  },
};
</script>
