<template>
  <div>
    <v-toolbar>
      <v-toolbar-title>Gesamtübersicht</v-toolbar-title>
      <v-spacer />
      <v-toolbar-items>
        <v-text-field
          v-model="filter"
          style="margin-top: 3px"
          append-icon="search"
          outlined
          :rules="[isNumber]"
        ></v-text-field>
      </v-toolbar-items>
    </v-toolbar>
    <div v-for="year in years" :key="years.indexOf(year)">
      <v-card style="margin-top: 3px" v-if="isFiltered(year)">
        <v-card-title>{{ year }}</v-card-title>
        <Table v-bind:user="user" v-bind:year="year" />
        <v-container fluid>
          <v-col>
            <v-row>
              <v-col>
                <v-label>Vorjahr:</v-label>
              </v-col>
              <v-col>
                <v-chip
                  outlined
                  :text-color="getLastColor(user.creditList[year][1].last)"
                  >{{ (user.creditList[year][1].last / 100).toFixed(2) }}
                </v-chip>
              </v-col>
              <v-col>
                <v-label>Gesamt:</v-label>
              </v-col>
              <v-col>
                <v-chip
                  outlined
                  x-large
                  :text-color="
                    getLastColor(
                      getAllSum(
                        user.creditList[year][2].sum,
                        user.creditList[year][1].last
                      )
                    )
                  "
                >
                  {{
                    (
                      getAllSum(
                        user.creditList[year][2].sum,
                        user.creditList[year][1].last
                      ) / 100
                    ).toFixed(2)
                  }}
                </v-chip>
              </v-col>
            </v-row>
          </v-col>
        </v-container>
      </v-card>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Table from '../finanzer/Table'
export default {
  name: 'CreditOverview',
  components: { Table },
  data() {
    return {
      isNumber: value => Number.isInteger(parseInt(value === '' ? 0 : value)) || "Muss eine Zahl sein.",
      filter: ''
    }
  },
  methods: {
    getLastColor(value) {
      return value < 0 ? 'red' : 'green'
    },
    getAllSum(sum, lastYear) {
      return lastYear + sum
    },
    isFiltered(value) {
      return value.toString().includes(this.filter)
    }
  },
  computed: {
    ...mapGetters({
      user: 'user/user'
    }),
    years() {
      let years = []
      if (this.user) {
        for (let year in this.user.creditList) {
          years.unshift(parseInt(year))
        }
      }
      return years
    }
  }
}
</script>

<style scoped></style>
