<template>
  <div
    class="db--chart"
  >
    <Bar
      :data="myData"
      :options="chartOptions"
    />
    <div class="chart--legend">
      <div
        v-for="(legend, idx) in legends"
        :key="`bar-chart-legend-${idx}`"
        class="legend"
      >
        <span class="line" />
        <p>{{ legend }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
  /***********************
   *     import
   ************************/
  import { Bar } from "vue-chartjs"
  import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, LineController, LineElement, PointElement, ArcElement, CategoryScale, LinearScale } from 'chart.js';
import dayjs from "#build/dayjs.imports.mjs";

  /***********************
   *     plugins inject
   ************************/
  // props
  const props = defineProps({
    chartItem: {
      type: Object,
      default: () => {}
    },
  })

  ChartJS.register(
    Title,
    Tooltip,
    Legend,
    BarElement,
    LineController,
    LineElement,
    PointElement,
    CategoryScale,
    ArcElement,
    LinearScale,
  )

  /***********************
   *     data & created
   ************************/

  const colorset = ref([
    '#FF531E',
    '#44C5FF',
    '#FF00C7',
    '#AF70FF',
    '#4862FF',
    '#55E074',
  ]);

  const legends = ref([]);

  const chartOptions = ref({
    layout: {
      padding: {
        top: 0,
      },
    },
    responsive: true,
    maintainAspectRatio: false,
    duration: 1000,
    plugins: {
      legend: {
        display: false,
      },
      datalabels: {
        display: false,
      },
      tooltip: {
        displayColors : false,
        callbacks: {
          title : function(tooltipItem, data){
            return tooltipItem[0].label.substr(0,10) + " " + tooltipItem[0].label.substr(11)
          },
          titleFont: { // 타이틀 영역 폰트 스타일
            size: 10,
            weight:500,
            family:'Inter',
          },
          titleColor : '#f00', // 타이틀 영역 폰트 컬러
          titleAlign : 'right', // 타이틀 영역 align (left, center, right)
          titleMarginBottom : 3,
        },
      },
    },
    scales: {
      x: {
        beginAtZero: true,
        stacked: true,
        title: {
          text: "",
          align: "end",
          display: false,
          font: {
            color: "#666",
            size: 12,
            weight: "500",
          },
        },
        grid: {
          display: false,
          drawTicks: false,
          drawBorder: false,
          color: "transparent",
        },
        ticks: {
          padding: 20,
          font: {
            size: function(context){
              const clientW = document.querySelector("body").clientWidth;
              if(clientW <= 1930){
                return 11
              }else if(clientW >= 2550 && clientW < 3840){
                return 17
              }else if(clientW >= 3840){
                return 22
              }
            },
            weight: "400",
          },
          color: "#838FAC",
          align:'center',
        },
      },
      y: {
        border: {
          display: false,
        },
        beginAtZero: true,
        stacked: false,
        title: {
          display: false,
          text: "",
        },
        ticks: {
          display: true,
          padding: 10,
          font: {
            size: function(context){
              const clientW = document.querySelector("body").clientWidth;
              if(clientW <= 1930){
                return 11
              }else if(clientW >= 2550 && clientW < 3840){
                return 17
              }else if(clientW >= 3840){
                return 22
              }
            },
            weight: "400",
          },
          color: "#b1b1b1",
        },
        min:0
      },
    },
    animation: {
      duration: 0,
    },
  })

  const myData = computed(() =>  fnGetChartDate(props.chartItem));

  /***********************
   *     Methods
   ************************/
  const fnGetChartDate = (chartItem) => {
    const chartData = { labels: [], datasets: [],}

    const { items } = chartItem;

    if(!chartItem || !items || items.length < 1) {
      return chartData;
    }

    const labels = []
    const datasets = items.reduce((acc, curr, i) => {
      Object.keys(curr).forEach((key) => {
        if(key == 'INIT_TIME') labels.push(dayjs(curr.INIT_TIME).format('HH:mm')); 
        else {
          if(acc[key]) acc[key].push(curr[key]);
          else acc[key] = [curr[key]];
        }
      }) 

      return acc;
    }, {})

    legends.value = Object.keys(datasets);
    chartData.labels = labels;
    chartData.datasets = legends.value.map((key, idx) => {
      return {
        label: key,
        borderWidth : 2,
        pointBackgroundColor: colorset.value[idx],
        borderColor: colorset.value[idx],
        pointRadius : 0,
        hoverRadius : 0,
        pointStyle : "circle",
        data: datasets[key],
        type: "line",
        fill : false,
      }
    })

    return chartData;
  }
</script>