<script setup>
import customParseFormat from "dayjs/plugin/customParseFormat";
import dayjs from "dayjs";
dayjs.extend(customParseFormat)


const supabase = useSupabaseClient()
const dataStore = useDataStore()
const profileStore = useProfileStore()

let incomeData = ref({})
let expenseData = ref({})

const setup = async () => {
  let incomeRawData = (await supabase.from("createddocuments").select().eq("tenant",profileStore.currentTenant).in('type',['invoices','cancellationInvoices'])).data
  let expenseRawData =(await supabase.from("incominginvoices").select().eq("tenant",profileStore.currentTenant)).data



  expenseRawData = expenseRawData.filter(i => i.date).map(i => {
    let amount = 0

    i.accounts.forEach(a => {
      amount += a.amountNet
    })

    amount = Number(amount.toFixed(2))

    return {
      id: i.id,
      date: dayjs(i.date).format("DD-MM-YY"),
      amount
    }

  })

  expenseRawData.forEach(i => {
    expenseData.value[i.date] ? expenseData.value[i.date] = Number((expenseData.value[i.date] + i.amount).toFixed(2)) : expenseData.value[i.date] = i.amount
  })

  let expenseMonths = {
    "01": 0,
    "02": 0,
    "03": 0,
    "04": 0,
    "05": 0,
    "06": 0,
    "07": 0,
    "08": 0,
    "09": 0,
    "10": 0,
    "11": 0,
    "12": 0,

  }
  Object.keys(expenseMonths).forEach(month => {
    let dates = Object.keys(expenseData.value).filter(i => i.split("-")[1] === month && i.split("-")[2] === dayjs().format("YY"))

    dates.forEach(date => {
      if(expenseMonths[month]){
        expenseMonths[month] = Number((expenseMonths[month] + expenseData.value[date]).toFixed(2))
      } else {
        expenseMonths[month] = expenseData.value[date]
      }
    })

  })

  expenseData.value = expenseMonths


  incomeRawData = incomeRawData.map(i => {
    let amount = 0

    i.rows.forEach(r => {
      if(r.mode !== "pagebreak" && r.mode !== "title" && r.mode !== "text"){
        amount += r.price * r.quantity * (1 - r.discountPercent/100)
      }
    })

    amount = Number(amount.toFixed(2))

    return {
      id: i.id,
      date: dayjs(i.documentDate).format("DD-MM-YY"),
      amount
    }
  })

  incomeRawData.forEach(i => {
    incomeData.value[i.date] ? incomeData.value[i.date] = Number((incomeData.value[i.date] + i.amount).toFixed(2)) : incomeData.value[i.date] = i.amount
  })

  let incomeMonths = {
    "01": 0,
    "02": 0,
    "03": 0,
    "04": 0,
    "05": 0,
    "06": 0,
    "07": 0,
    "08": 0,
    "09": 0,
    "10": 0,
    "11": 0,
    "12": 0,

  }
  Object.keys(incomeMonths).forEach(month => {
    let dates = Object.keys(incomeData.value).filter(i => i.split("-")[1] === month && i.split("-")[2] === dayjs().format("YY"))

    dates.forEach(date => {
      if(incomeMonths[month]){
        incomeMonths[month] = Number((incomeMonths[month] + incomeData.value[date]).toFixed(2))
      } else {
        incomeMonths[month] = incomeData.value[date]
      }
    })

  })

  incomeData.value = incomeMonths
}

const days = computed(() => {
  let days = []

  days = Object.keys(incomeData.value)

  let expenseDays = Object.keys(expenseData.value)

  expenseDays.forEach(expenseDay => {
    if(!days.find(i => i === expenseDay)){
      days.push(expenseDay)
    }
  })

  days = days.sort(function(a, b) {
    var keyA = dayjs(a, "DD-MM-YY"),
        keyB = dayjs(b, "DD-MM-YY");
    // Compare the 2 dates
    if (keyA.isBefore(keyB,'day')) {
      return -1;
    } else if(keyB.isBefore(keyA, 'day')) {
      return 1
    } else {
      return 0;
    }

  });



  return days
})

/*const chartData = computed(() => {
  return {
    labels: days.value,
    datasets: [
        {
            label: 'Einnahmen',
            data: [2, 1, 16, 3, 2],
            backgroundColor: 'rgba(20, 255, 0, 0.3)',
            borderColor: 'red',
            borderWidth: 2,
        }
    ]
  }
})*/


import { Line } from 'vue-chartjs'
const chartData = computed(() => {
  return {
    labels: ["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],
    datasets: [
      {
        label: 'Ausgaben',
        backgroundColor: '#f87979',
        borderColor: '#f87979',
        data: Object.keys(expenseData.value).sort().map(i => expenseData.value[i]),
        tension: 0.3,
      },{
        label: 'Einnahmen',
        backgroundColor: '#69c350',
        borderColor: '#69c350',
        data: Object.keys(incomeData.value).sort().map(i => incomeData.value[i]),
        tension: 0.3
      },
    ],
  }
})
const chartOptions = ref({
  responsive: true,
  maintainAspectRatio: false,
})

setup()
</script>

<template>
  <Line
      :data="chartData"
      :options="chartOptions"
  />
</template>

<style scoped>

</style>