<script setup>
  import { computed, onMounted, ref } from 'vue';
  import { Bar } from 'vue-chartjs'
  import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, LinearScale, CategoryScale, ArcElement } from 'chart.js'
  ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale, ArcElement)

  const props = defineProps({
    label: {
        type: String,
        required: true
    },
    data: {
        type: Array,
        required: true
    },
    dataModel: {
        type: Array,
    },
    targetFind: {
      type: String
    },
    targetLabel: {
      type: String
    }
  })

  const chartData = ref(null);
  const dataMap = ref([]);
  onMounted(() => {

    props.data.forEach(item => {
        const index = dataMap.value.findIndex((e) => e.label === item);

        if(index === -1) {
            if(props.dataModel) {
                const itemModel = props.dataModel.find((e) => e[props.targetFind] === item);
                dataMap.value.push({
                    label: (props.targetLabel) ? itemModel[props.targetLabel] : item,
                    data: 1,
                    ...itemModel
                })
            } else {
                dataMap.value.push({
                    label: item,
                    data: 1,
                    color: 'green'
                });
            }
        } else {
            dataMap.value[index].data += 1;
        }
    });

    chartData.value = {
      labels: dataMap.value.map((e) => (e.label.length > 12) ? e.label.substring(0, 11) : e.label),
      position: 'bottom',
      datasets: [{ 
        label: props.label,
        data: dataMap.value.map((e) => e.data),
        backgroundColor: dataMap.value.map((e) => e.color),
      }],
    }
  })

  const id = computed(() => {
    return `my-chart-${props.label}`
  })

  
    const chartOptions = {
      responsive: true,  
    }
</script>

<template>
    <Bar
      :id=id
      v-if="chartData"
      :options="chartOptions"
      :data="chartData"
    />
</template>

<style scoped>

</style>