<template>
  <div>
    <q-table
      class="full-width"
      title="Getränke"
      :columns="columns_drinks"
      :rows="drinks"
      row-key="name"
      :visible-columns="visibleColumn"
      :filter="search"
      :filter-method="filter"
    >
      <template #top-right>
        <div class="row q-gutter-sm">
          <search-input
            v-model="search"
            :keys="[...columns_drinks, ...columns_volumes, ...columns_prices]"
          />
          <q-select
            v-model="visibleColumn"
            multiple
            filled
            dense
            options-dense
            display-value="Sichtbarkeit"
            emit-value
            map-options
            :options="[...columns_drinks, ...columns_volumes, ...columns_prices]"
            option-value="name"
            options-cover
          />
        </div>
      </template>
      <template #body-cell-volumes="props">
        <q-td :props="props">
          <q-table
            :columns="columns_volumes"
            :rows="props.row.volumes"
            hide-header
            :hide-bottom="props.row.volumes.length < 5"
            flat
            :visible-columns="visibleColumn"
          >
            <template #body-cell-prices="props_volumes">
              <q-td :props="props_volumes">
                <q-table
                  :columns="columns_prices"
                  :rows="props_volumes.row.prices"
                  hide-header
                  :hide-bottom="props_volumes.row.prices.length < 5"
                  flat
                  :visible-columns="visibleColumn"
                >
                  <template #body-cell-public="props_prices">
                    <q-td :props="props_prices">
                      <q-toggle v-model="props_prices.row.public" disable />
                    </q-td>
                  </template>
                </q-table>
              </q-td>
            </template>
          </q-table>
        </q-td>
      </template>
      <template #body-cell-picture="drinks_props">
        <q-td :props="drinks_props" style="min-width: 256px">
          <q-img
            loading="lazy"
            :src="
              drinks_props.row.uuid
                ? `/api/pricelist/picture/${drinks_props.row.uuid}?size=256`
                : 'no-image.svg'
            "
            placeholder-src="no-image.svg"
            fit="contain"
            style="max-height: 300px"
          >
            <template #error>
              <div class="absolute-full flex flex-center bg-negative text-white">
                Cannot load image
              </div>
            </template>
          </q-img>
        </q-td>
      </template>
    </q-table>
  </div>
</template>
<script lang="ts">
import { defineComponent, onBeforeMount, computed, ref } from 'vue';
import { usePricelistStore } from '../store';
import { useMainStore } from 'src/stores';
import SearchInput from './SearchInput.vue';
import { filter, Search } from '../utils/filter';
import { sort } from '../utils/sort';
export default defineComponent({
  name: 'Pricelist',
  components: { SearchInput },
  filters: {
    setVolume(volume: number) {
      if (volume * 10 > 1) {
        return `${volume}l`;
      }
      return `${volume * 100}cl`;
    },
    setCurrency(price: number) {
      return `${price.toFixed(2)}€`;
    },
  },
  props: {
    public: {
      type: Boolean,
      default: false,
    },
  },
  setup() {
    let user: string | null;
    onBeforeMount(() => {
      void store.getDrinks();
      try {
        user = mainStore.currentUser.userid;
      } catch {
        user = null;
      }

      if (user) {
        store.getPriceCalcColumn(user);
      }
    });
    const store = usePricelistStore();
    const drinks = computed(() => store.drinks);
    const columns_drinks = [
      {
        name: 'picture',
        label: 'Bild',
        align: 'center',
      },
      {
        name: 'name',
        label: 'Getränk',
        field: 'name',
        align: 'center',
        sortable: true,
      },
      {
        name: 'drink_type',
        label: 'Kategorie',
        field: 'type',
        format: (val: FG.DrinkType) => `${val.name}`,
        sortable: true,
        sort: (a: FG.DrinkType, b: FG.DrinkType) => sort(a.name, b.name),
      },
      {
        name: 'volumes',
        label: 'Preise',
        field: 'volumes',
        align: 'center',
      },
    ];
    const columns_volumes = [
      {
        name: 'volume',
        label: 'Inhalt',
        field: 'volume',
        format: (val: number) => `${val.toFixed(3)}L`,
        align: 'left',
      },
      {
        name: 'prices',
        label: 'Preise',
        field: 'prices',
      },
    ];
    const columns_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 canBeVisible = createVisibleColumns();
    const _visibleColumns = ref(canBeVisible);
    const visibleColumn = computed({
      get: () => {
        if (user) {
          return store.pricecalc_columns;
        } else {
          return _visibleColumns.value;
        }
      },
      set: (val) => {
        if (user) {
          store.updatePriceCalcColumn(user, val);
        } else {
          _visibleColumns.value = val;
        }
      },
    });
    const mainStore = useMainStore();

    function createVisibleColumns() {
      const retVal: Array<string> = [];
      columns_drinks.forEach((drink) => retVal.push(drink.name));
      columns_volumes.forEach((volume) => retVal.push(volume.name));
      columns_prices.forEach((price) => {
        if (user || price.name !== 'public') retVal.push(price.name);
      });
      return retVal;
    }
    const search = ref<Search>({ label: '', value: '', key: '' });

    return {
      columns_drinks,
      columns_volumes,
      columns_prices,
      drinks,
      visibleColumn,
      search,
      filter,
    };
  },
});
</script>
