<template>
  <div>
    <q-table
      title="Kalkulationstabelle"
      :columns="columns"
      :data="test"
      :visible-columns="visibleColumn"
      :dense="$q.screen.lt.md"
    >
      <template v-slot:top-right>
        <q-select
          v-model="visibleColumn"
          multiple
          filled
          dense
          options-dense
          display-value="Sichtbarkeit"
          emit-value
          map-options
          :options="[...columns, ...column_calc, ...column_prices]"
          option-value="name"
          options-cover
        />
      </template>
      <template v-slot:body-cell-price_calc="price_calc">
        <q-table
          :columns="column_calc"
          :data="price_calc.value"
          dense
          :visible-columns="visibleColumn"
          row-key="id"
          flat
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th auto-width />
              <q-th v-for="(col, index) in props.cols" :key="col + index" :props="props">
                {{ col }}
              </q-th>
            </q-tr>
          </template>

          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td auto-width>
                <q-btn
                  size="sm"
                  color="accent"
                  round
                  dense
                  @click="props.expand = !props.expand"
                  :icon="props.expand ? 'mdi-chevron-up' : 'mdi-chevron-down'"
                />
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                <div v-if="col.name == 'min_prices'">
                  <div
                    v-for="(min_price, index) in col.value"
                    :key="col.name + index"
                    class="row justify-between"
                  >
                    <div class="col">
                      <q-badge color="primary">{{ min_price.percentage }}%</q-badge>
                    </div>
                    <div class="col" style="text-align: end;">
                      {{ parseFloat(min_price.price).toFixed(3) }}€
                    </div>
                  </div>
                </div>
                <div v-else-if="col.name == 'prices'">
                  <q-table
                    dense
                    hide-header
                    :columns="column_prices"
                    :data="col.value"
                    :visible-columns="visibleColumn"
                    flat
                  >
                    <template v-slot:body="prices_props">
                      <q-tr :props="prices_props">
                        <q-td
                          v-for="col in prices_props.cols"
                          :key="col.name"
                          :props="prices_props"
                        >
                          {{ col.value }}
                        </q-td>
                        <q-td>
                          <q-btn
                            color="negative"
                            round
                            size="xs"
                            icon="mdi-delete"
                            @click="deletePrice(prices_props.row)"
                            v-if="!prices_props.row.to_delete"
                          />
                          <q-btn color="positive" size="xs" label="Speichern" v-else />
                        </q-td>
                      </q-tr>
                    </template>
                    <template v-slot:bottom>
                      <div class="full-width row justify-end">
                        <q-btn
                          size="xs"
                          icon-right="add"
                          color="positive"
                          label="Preis hinzufügen"
                          @click="addPrice(col.value)"
                        />
                      </div>
                    </template>
                    <template v-slot:no-data class="justify-end">
                      <div class="full-width row justify-end">
                        <q-btn
                          size="xs"
                          icon-right="add"
                          color="positive"
                          label="Preis hinzufügen"
                          @click="addPrice(col.value)"
                        />
                      </div>
                    </template>
                  </q-table>
                </div>
                <div v-else>
                  {{ col.value }}
                </div>
              </q-td>
            </q-tr>
            <q-tr v-show="props.expand" :props="props">
              <q-td colspan="100%">
                <div
                  v-for="(ingredient, index) in props.row.ingredients"
                  :key="`${props.key}_${index}`"
                  class="full-width row justify-evenly q-py-xs"
                >
                  <q-select
                    class="col q-px-sm"
                    label="Getränk"
                    filled
                    dense
                    :options="test"
                    option-label="name"
                    v-model="ingredient.drink"
                    @input="calc_min_prices(props.row)"
                  />
                  <q-input
                    class="col q-px-sm"
                    label="Volume in L"
                    type="number"
                    filled
                    dense
                    v-model="ingredient.volume"
                    @change="calc_min_prices(props.row)"
                    step="0.01"
                    min="0"
                  />
                </div>
                <div class="full-width row justify-end q-py-xs">
                  <q-btn
                    size="sm"
                    icon-right="add"
                    color="positive"
                    label="Zutat hinzufügen"
                    @click="addIngredient(props.row.ingredients)"
                    @change="calc_min_prices(props.row)"
                  />
                </div>
              </q-td>
            </q-tr>
          </template>
          <template v-slot:bottom>
            <div class="full-width row justify-end">
              <q-btn
                color="positive"
                icon-right="add"
                label="Abgabe hinzufügen"
                size="xs"
                @click="addVolume(price_calc.value)"
              />
            </div>
          </template>
        </q-table>
      </template>
    </q-table>
  </div>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, ref } from '@vue/composition-api';
import { Store } from 'vuex';
import { StateInterface } from '../../../store';
import { DrinkInterface } from '../store/drinks';
import { v4 } from 'uuid';
export default defineComponent({
  name: 'CalculationTable',
  setup(_, { root }) {
    const store = <Store<StateInterface>>root.$store;
    const state = <DrinkInterface>store.state.drink;
    const drinks = ref();
    onBeforeMount(() => {
      void store
        .dispatch('drink/getDrinks')
        .then(() => (drinks.value = drinks.value = state.drinks));
    });

    const columns = [
      {
        name: 'name',
        label: 'Getränkename',
        field: 'name'
      },
      {
        name: 'article_id',
        label: 'Artikelnummer',
        field: 'article_id'
      },
      {
        name: 'drink_kind',
        label: 'Kategorie',
        field: 'drink_kind'
      },
      {
        name: 'volume_package',
        label: 'Inhalt in l des Gebinde',
        field: 'volume_package'
      },
      {
        name: 'package_size',
        label: 'Gebindegröße',
        field: 'package_size'
      },
      {
        name: 'cost_price_package_netto',
        label: 'Preis Netto/Gebinde',
        field: 'cost_price_package_netto',
        format: (val: number) => `${val.toFixed(3)}€`
      },
      {
        name: 'cost_price_pro_volume',
        label: 'Preis mit 19%/Liter',
        field: 'cost_price_pro_volume',
        format: (val: number) => `${val.toFixed(3)}€`
      },
      {
        name: 'price_calc',
        label: 'Preiskalkulation',
        field: 'price_calc'
      }
    ];
    const column_calc = [
      {
        name: 'volume',
        label: 'Abgabe in l',
        field: 'volume',
        format: (val: number) => `${val} L`
      },
      {
        name: 'min_prices',
        label: 'Minimal Preise',
        field: 'min_prices'
      },
      {
        name: 'prices',
        label: 'Preise',
        field: 'prices'
      }
    ];
    const column_prices = [
      {
        name: 'price',
        label: 'Preis',
        field: 'price',
        format: (val: number) => `${val.toFixed(2)}€`
      },
      {
        name: 'description',
        label: 'Beschreibung',
        field: 'description'
      }
    ];
    const test = ref([
      {
        name: 'Elbhang Rot',
        article_id: 41807,
        drink_kind: 'Bier',
        volume_package: 50,
        package_size: 1,
        cost_price_package_netto: 97,
        cost_price_pro_volume: 2.309,
        price_calc: [
          {
            id: v4(),
            volume: 0.5,
            min_prices: [
              {
                percentage: 100,
                price: 1.15
              },
              {
                percentage: 250,
                price: 2.875
              },
              {
                percentage: 300,
                price: 3.45
              }
            ],
            prices: [
              { price: 2, description: '', to_delete: false },
              { price: 1.4, description: 'Club intern', to_delete: false },
              {
                price: 1.6,
                description: 'Club extern',
                to_delete: false
              }
            ]
          }
        ]
      },
      {
        name: 'Sinalco Cola',
        article_id: 443,
        drink_kind: 'AFG',
        volume_package: 1,
        package_size: 12,
        cost_price_package_netto: 7.28,
        cost_price_pro_volume: 0.722,
        price_calc: [
          {
            id: v4(),
            volume: 0.2,
            min_prices: [
              {
                percentage: 100,
                price: 0.14
              },
              {
                percentage: 250,
                price: 0.35
              },
              {
                percentage: 300,
                price: 0.42
              }
            ],
            prices: [
              {
                price: 1,
                description: 'klein',
                to_delete: false
              },
              { price: 0.5, description: 'klein club intern', to_delete: false }
            ]
          },
          {
            id: v4(),
            volume: 0.4,
            min_prices: [
              {
                percentage: 100,
                price: 0.289
              },
              {
                percentage: 250,
                price: 0.722
              },
              {
                percentage: 300,
                price: 0.866
              }
            ],
            prices: [
              {
                price: 1.8,
                description: 'groß',
                to_delet: false
              },
              { price: 1, description: 'groß club intern', to_delete: false }
            ]
          }
        ]
      }
    ]);
    const visibleColumn = ref([
      'name',
      'drink_kind',
      'cost_price_pro_volumne',
      'price_calc',
      'volume',
      'min_prices',
      'prices',
      'price',
      'description'
    ]);

    function deletePrice(row) {
      console.log(row);
      row.to_delete = true;
    }
    function addPrice(table) {
      console.log(table);
      table.push({
        price: 20,
        description: 'test',
        to_delete: false
      });
    }

    function addVolume(table) {
      table.push({
        id: v4(),
        volume: null,
        min_prices: [
          {
            percentage: 100,
            price: null
          },
          {
            percentage: 250,
            price: null
          },
          {
            percentage: 300,
            price: null
          }
        ],
        prices: [],
        ingredients: []
      });
    }

    function addIngredient(ingredients) {
      ingredients.push({ drink: null, volume: null });
    }
    function calc_min_prices(row) {
      console.log(row.ingredients);
      row.volume = 0;
      let cost_price = 0;
      row.ingredients.forEach(ingredient => {
        row.volume = row.volume + Number.parseFloat(ingredient.volume);
        cost_price = Number.parseFloat(ingredient.volume) * ingredient.drink.cost_price_pro_volume;
      });
      console.log(row.volume, cost_price);
      row.min_prices.forEach(min_price => {
        min_price.price = (cost_price * min_price.percentage) / 100;
      });
    }

    return {
      drinks,
      columns,
      test,
      column_calc,
      column_prices,
      visibleColumn,
      deletePrice,
      addPrice,
      addVolume,
      addIngredient,
      calc_min_prices
    };
  }
});
</script>

<style scoped></style>
