<template>
  <div
    class="chartdiv"
    id="chartdiv"
    ref="chartdiv"
    style="width: 100%; height: 700px"
  ></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: {
    datalist: {
      type: Array,
      default: [],
    },
    chartName: {
      type: String,
    },
  },
  data() {
    return {
      jsonData: [],
      root: null,
    };
  },
  components: {},
  methods: {
    initializeChartArea: function () {
      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 chartArea = am5.Root.new(chartWarp.firstChild);

      chartArea.setThemes([am5themes_Animated.new(root)]);

      return chartArea;
    },
    createChart: function (data) {
      let vm = this;

      let root = this.initializeChartArea(); // 차트 초기화

      let series = null;
      let chart = null;

      // 동적 데이터 설정
      let categoryAxisRenderer = null;
      let valueAxisRenderer = null;
      let categoryAxes = null;
      let valueAxes = null;
      let categoryInversed = null; // 카테고리 셀 순서 (순차: false, 역순: true)

      categoryAxisRenderer =
        vm.chartName == "column_chart_v" ? "AxisRendererX" : "AxisRendererY";
      valueAxisRenderer =
        vm.chartName == "column_chart_v" ? "AxisRendererY" : "AxisRendererX";
      categoryAxes = vm.chartName == "column_chart_v" ? "xAxes" : "yAxes";
      valueAxes = vm.chartName == "column_chart_v" ? "yAxes" : "xAxes";
      categoryInversed = vm.chartName == "column_chart_v" ? false : true;

      // Create chart
      let panX = true;
      let panY = true;
      let wheelX = "panX";
      let wheelY = vm.chartName == "column_chart_v" ? "panY" : "zoomX";

      chart = root.container.children.push(
        am5xy.XYChart.new(root, {
          panX: panX,
          panY: panY,
          wheelX: wheelX,
          wheelY: wheelY,
        })
      );

      let categoryRenderer = am5xy[categoryAxisRenderer].new(root, {
        minGridDistance: 30,
        minorGridEnabled: true,
        inversed: categoryInversed,
      });

      categoryRenderer.labels.template.setAll({
        rotation: -90,
        centerY: am5.p50,
        centerX: am5.p100,
        paddingRight: 15,
      });

      categoryRenderer.grid.template.setAll({
        stroke: am5.color(0xf15f5f),
        location: 1,
      });

      let categoryAxis = chart[categoryAxes].push(
        am5xy.CategoryAxis.new(root, {
          maxDeviation: 0.3,
          categoryField: "categoryData",
          renderer: categoryRenderer,
          tooltip: am5.Tooltip.new(root, {}),
        })
      );

      let valueRenderer = am5xy[valueAxisRenderer].new(root, {
        strokeOpacity: 0.1,
      });

      let valueAxis = chart[valueAxes].push(
        am5xy.ValueAxis.new(root, {
          maxDeviation: 0.3,
          renderer: valueRenderer,
        })
      );

      let xAxis = null;
      let yAxis = null;
      let categoryField = null;
      let valueField = null;
      let categoryXY = null;
      let valueXY = null;
      if (vm.chartName == "column_chart_v") {
        xAxis = categoryAxis;
        yAxis = valueAxis;
        categoryField = "categoryXField";
        valueField = "valueYField";
        categoryXY = "categoryX";
        valueXY = "valueY";
      } else {
        xAxis = valueAxis;
        yAxis = categoryAxis;
        categoryField = "categoryYField";
        valueField = "valueXField";
        categoryXY = "categoryY";
        valueXY = "valueX";
      }

      series = chart.series.push(
        am5xy.ColumnSeries.new(root, {
          name: "Series 1",
          xAxis: xAxis,
          yAxis: yAxis,
          [valueField]: "value",
          [categoryField]: "categoryData",
          tooltip: am5.Tooltip.new(root, {
            labelText: "{valueY}",
          }),
        })
      );

      series.columns.template.setAll({
        cornerRadiusTL: 5,
        cornerRadiusTR: 5,
        strokeOpacity: 0,
      });
      series.columns.template.adapters.add("fill", function (fill, target) {
        return chart.get("colors").getIndex(series.columns.indexOf(target));
      });

      series.columns.template.adapters.add("stroke", function (stroke, target) {
        return chart.get("colors").getIndex(series.columns.indexOf(target));
      });

      categoryAxis.data.setAll(data);
      series.data.setAll(data);
      series.appear(1000);
    },
  },
  watch: {
    datalist: {
      handler: function (newVal, oldVal) {
        this.jsonData = newVal;
        this.createChart(this.jsonData);
      },
      deep: true,
    },
  },
  mounted() {
    this.jsonData = this.datalist;
  },
};
</script>

<style scoped>
#chartdiv {
  width: 100%;
  height: 500px;
}
button {
  margin: 10px;
  background-color: antiquewhite;
  border-radius: 10px;
}
</style>