<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 * as am5percent from "@amcharts/amcharts5/percent";
import am5themes_Animated from "@amcharts/amcharts5/themes/Animated";
import chartDataTransform from "./chartDataTransform";

export default {
  props: {
    datalist: {
      type: Array,
      default: [],
    },
    chartName: {
      type: String,
    },
    selectedFieldArr: {
      type: Array,
      default: [],
    },
    selectedCal: {
      type: String,
      default: "default",
    },
  },
  data() {
    return {
      jsonData: [],
      chartType: null,
    };
  },
  components: {},
  methods: {
    // 그룹 선택으로 인한 데이터 필터링 함수
    changeSelectSubGroup: function (event) {
      this.selectedSubGroup = event.target.value;
      // 필터 적용 함수 호출
      const filterDataList = chartDataTransform.setFilteringData(
        this.datalist,
        this.subGroupArr,
        this.selectedSubGroup
      );
      this.transformData(filterDataList);
    },
    changeSubGroupData: function (val) {
      if (Array.isArray(val)) {
        this.subGroupArr = [];
        this.subGroupArr = val
          .map((data) => data.group)
          .filter((value, index, self) => self.indexOf(value) === index)
          .map((column, index) => {
            return {
              index: index,
              columnNm: column,
            };
          });
        // subGroupArr sort 처리
        this.subGroupArr.sort((a, b) =>
          a.columnNm < b.columnNm ? -1 : a.columnNm > b.columnNm ? 1 : 0
        );
      }
    },
    //y 객체 배열 생성
    createYData: function () {
      this.selectedFieldArr = this.createDataObj.valueAxis.map((field) => {
        return {
          valNm: field.columnNm,
          valIndex: field.columnIdx,
        };
      });
    },
    // 데이터 생성 함수
    // dataList를 받아와 차트에 표현할 데이터로 가공
    transformData: function (val) {
      if (this.selectedCal === "default") {
        this.chartJsondData = val;
        this.createChart();
        return;
      }
      // 전체 데이터를 그룹화하여 가공 (All Data)
      this.groupsResult = chartDataTransform.dataGrouping(
        val,
        this.selectedFieldArr
      );
      if (!this.isSelectGroup) {
        // groupSubArr에 group의 key를 중복을 제거하고 담음
        this.changeSubGroupData(this.datalist);
      }
      // }
      // 데이터 가공 함수
      this.chartJsondData = chartDataTransform.calculateSetting(
        this.groupsResult,
        this.selectedCal
      );

      this.createChart();
    },
    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 () {
      let vm = this;
      let data = vm.chartJsondData;

      let income = Object.keys(data[0])[1];
      let expenses = Object.keys(data[0])[2];

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

      let chart = root.container.children.push(
        am5xy.XYChart.new(root, {
          panX: false,
          panY: false,
          wheelX: "panX",
          wheelY: "zoomX",
          paddingLeft: 0,
          layout: root.verticalLayout,
        })
      );

      chart.set(
        "scrollbarX",
        am5.Scrollbar.new(root, {
          orientation: "horizontal",
        })
      );

      let xRenderer = am5xy.AxisRendererX.new(root, {
        minorGridEnabled: true,
        minGridDistance: 60,
      });
      let xAxis = chart.xAxes.push(
        am5xy.CategoryAxis.new(root, {
          categoryField: "categoryData",
          renderer: xRenderer,
          tooltip: am5.Tooltip.new(root, {}),
        })
      );
      xRenderer.grid.template.setAll({
        location: 1,
      });

      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,
          }),
        })
      );

      let series1 = chart.series.push(
        am5xy.ColumnSeries.new(root, {
          name: income,
          xAxis: xAxis,
          yAxis: yAxis,
          valueYField: income,
          categoryXField: "categoryData",
          tooltip: am5.Tooltip.new(root, {
            pointerOrientation: "horizontal",
            labelText: "{name} in {categoryX}: {valueY} {info}",
          }),
        })
      );

      series1.columns.template.setAll({
        tooltipY: am5.percent(10),
        templateField: "columnSettings",
      });

      series1.data.setAll(data);

      let series2 = chart.series.push(
        am5xy.LineSeries.new(root, {
          name: expenses,
          xAxis: xAxis,
          yAxis: yAxis,
          valueYField: expenses,
          categoryXField: "categoryData",
          tooltip: am5.Tooltip.new(root, {
            pointerOrientation: "horizontal",
            labelText: "{name} in {categoryX}: {valueY} {info}",
          }),
        })
      );

      series2.strokes.template.setAll({
        strokeWidth: 3,
        templateField: "strokeSettings",
      });

      series2.data.setAll(data);

      series2.bullets.push(function () {
        return am5.Bullet.new(root, {
          sprite: am5.Circle.new(root, {
            strokeWidth: 3,
            stroke: series2.get("stroke"),
            radius: 5,
            fill: root.interfaceColors.get("background"),
          }),
        });
      });

      chart.set("cursor", am5xy.XYCursor.new(root, {}));

      let legend = chart.children.push(
        am5.Legend.new(root, {
          centerX: am5.p50,
          x: am5.p50,
        })
      );
      legend.data.setAll(chart.series.values);

      series1.appear(1000);
      chart.appear(1000, 300);

      root._logo.dispose(); //amChart 로고 삭제
    },
  },
  watch: {
    datalist: {
      handler: function (newVal, oldVal) {
        this.transformData(newVal);
      },
      deep: true,
    },
    selectedCal: {
      handler: function () {
        this.transformData(this.datalist);
      },
    },
  },
  mounted() {
    this.datalist = this.createDataObj.data_list;
    this.chartName = this.createDataObj.chart_knd;
    this.isMultiData = this.createDataObj.multidata_use_yn;
    this.selectedCal = this.createDataObj.chart_cal;

    this.transformData(this.datalist);
  },
};
</script>

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