<template>
  <div>
    <q-table
      title="Kalkulationstabelle"
      :columns="columns"
      :data="drinks"
      :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-volumes="volumes">
        <q-table
          :columns="column_calc"
          :data="volumes.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 in props.cols" :key="col.name" :props="props">
                {{ col.label }}
              </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;
                    console.log(volumes);
                  "
                  :icon="props.expand ? 'mdi-chevron-up' : 'mdi-chevron-down'"
                  v-if="volumes.row.cost_price_pro_volume == null"
                />
              </q-td>
              <q-td key="volume" :props="props">
                {{ props.row.volume }}L
                <q-popup-edit
                  buttons
                  label-cancel="Abbrechen"
                  label-set="Speichern"
                  v-model="props.row.volume"
                  @save="updateVolume(props.row, volumes.row)"
                >
                  <q-input
                    dense
                    filled
                    v-model.number="props.row.volume"
                    type="number"
                    suffix="L"
                  />
                </q-popup-edit>
              </q-td>
              <q-td key="min_prices" :props="props">
                <div
                  v-for="(min_price, index) in props.row.min_prices"
                  :key="`min_prices` + 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>
              </q-td>
              <q-td key="prices" :props="props">
                <price-table
                  :columns="column_prices"
                  :data="props.row.prices"
                  :row="props.row"
                  :visible-columns="visibleColumn"
                />
              </q-td>
            </q-tr>
            <q-tr v-show="props.expand" :props="props">
              <q-td colspan="100%">
                <div
                  v-for="ingredient in props.row.ingredients"
                  :key="`volume:${props.row.id},ingredient:${ingredient.id}`"
                  class="full-width row justify-evenly q-py-xs"
                >
                  <div
                    class="full-width row justify-evenly q-py-xs"
                    v-if="ingredient.drink_ingredient"
                  >
                    <q-select
                      class="col q-px-sm"
                      label="Getränk"
                      filled
                      dense
                      :options="drinks"
                      option-label="name"
                      v-model="ingredient.drink_ingredient"
                      @input="calc_min_prices(props.row)"
                    />
                    <q-input
                      class="col q-px-sm"
                      label="Volume in L"
                      type="number"
                      filled
                      dense
                      v-model.number="ingredient.volume"
                      @change="calc_min_prices(props.row)"
                      step="0.01"
                      min="0"
                    />
                  </div>
                  <div v-else-if="ingredient.name">
                    {{ ingredient.name }} {{ ingredient.price }}
                  </div>
                </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, props.row.id)"
                    @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"
                v-if="volumes.row.cost_price_pro_volume"
              >
                <q-menu anchor="center middle" self="center middle">
                  <div class="row justify-around q-pa-sm">
                    <q-input dense label="Liter" type="number" v-model.number="newVolume.volume" />
                  </div>
                  <div class="row justify-between q-pa-sm">
                    <q-btn label="Abbrechen" @click="cancelAddVolume" v-close-popup />
                    <q-btn
                      label="Speichern"
                      color="primary"
                      @click="addVolume(volumes.row)"
                      v-close-popup
                    />
                  </div>
                </q-menu>
              </q-btn>
            </div>
          </template>
        </q-table>
      </template>
    </q-table>
  </div>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, ref, computed } from '@vue/composition-api';
import store, { calc_min_prices } from '../store/altStore';
import { v4 } from 'uuid';
import PriceTable from 'src/plugins/pricelist/components/CalculationTable/PriceTable.vue';
export default defineComponent({
  name: 'CalculationTable',
  components: { PriceTable },
  setup(_, { root }) {
    onBeforeMount(() => {
      store.actions.getDrinks();
    });

    const columns = [
      {
        name: 'name',
        label: 'Getränkename',
        field: 'name'
      },
      {
        name: 'article_id',
        label: 'Artikelnummer',
        field: 'article_id'
      },
      {
        name: 'drink_type',
        label: 'Kategorie',
        field: 'type',
        format: (val: FG.DrinkType) => `${val.name}`
      },
      {
        name: 'volume_package',
        label: 'Inhalt in l des Gebinde',
        field: 'volume'
      },
      {
        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 | null) => (val ? `${val.toFixed(3)}€` : '')
      },
      {
        name: 'cost_price_pro_volume',
        label: 'Preis mit 19%/Liter',
        field: 'cost_price_pro_volume',
        format: (val: number | null) => (val ? `${val.toFixed(3)}€` : '')
      },
      {
        name: 'volumes',
        label: 'Preiskalkulation',
        field: 'volumes'
      }
    ];
    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'
      },
      {
        name: 'public',
        label: 'Öffentlich',
        field: 'public'
      }
    ];
    const visibleColumn = ref([
      'name',
      'drink_kind',
      'cost_price_pro_volumne',
      'volumes',
      'volume',
      'min_prices',
      'prices',
      'price',
      'description',
      'public'
    ]);
    const emptyVolume = {
      id: -1,
      volume: 0,
      min_prices: [
        { percentage: 100, price: 0 },
        { percentage: 250, price: 0 },
        { percentage: 300, price: 0 }
      ],
      prices: [],
      ingredients: []
    };
    const newVolume = ref(emptyVolume);
    function addVolume(drink: FG.Drink) {
      store.actions.setVolume(newVolume.value, drink);
      cancelAddVolume();
    }
    function cancelAddVolume() {
      setTimeout(() => {
        newVolume.value = emptyVolume;
      }, 200);
    }
    function updateVolume(volume: FG.DrinkPriceVolume, drink: FG.Drink) {
      console.log(volume);
      store.actions.updateVolume(volume, drink);
    }

    function addIngredient(ingredients: FG.Ingredient[]) {
      ingredients.push({ id: -1, volume_id: 0, drink_ingredient: null, extra_ingredient: null });
    }

    return {
      drinks: computed(() => store.state.drinks),
      columns,
      column_calc,
      column_prices,
      visibleColumn,
      addVolume,
      cancelAddVolume,
      newVolume,
      updateVolume,
      addIngredient,
      calc_min_prices,
      console
    };
  }
});
</script>

<style scoped></style>
