ClearBowl/front/components/Calculator/CalculatorForm.vue
2020-01-08 17:37:42 +01:00

135 lines
4.7 KiB
Vue

<template>
<div>
<h3 style="margin-bottom: 10px">Składniki</h3>
<Form ref="ingredients" :model="ingredients">
<FormItem
v-for="(item, index) in ingredients.items"
:key="index"
label="Składnik"
:prop="'items.' + index + '.value'">
<Row style="display: flex; justify-items: center">
<AutoComplete
v-model="item.name"
@on-select="appendIngredient(item, $event)"
@on-search="handleSearch"
placeholder="Nazwa składnika">
<Option v-for="sugg in suggestions" :value="sugg.name" :key="sugg.id">{{ sugg.name }}
</Option>
</AutoComplete>
<InputNumber class="input" v-model="item.weight"
:min="1"
:formatter="value => `${value} g`"
:parser="value => value.replace(' g', '')"
style="margin-left: 3px; width: 20%"/>
<Button @click="handleRemoveIngredient(index)" style="margin-left: 3px">Usuń</Button>
</Row>
</FormItem>
<FormItem>
<Row>
<Button type="dashed" long @click="handleAddIngredient" icon="md-add">Dodaj składnik
</Button>
</Row>
</FormItem>
</Form>
<Row style="margin-bottom: 20px">
<span><b>Wartości odżywcze:</b></span>
<ul>
<span>Kcal: {{nutrition.kcal}}</span>
</ul>
<ul>
<span>Węglowodany: {{nutrition.carbohydrates}}</span>
</ul>
<ul>
<span>Białka: {{nutrition.protein}}</span>
</ul>
<ul>
<span>Tłuszcze: {{nutrition.fat}}</span>
</ul>
</Row>
<Button type="primary" @click="calculate">Oblicz</Button>
<Button type="error" @click="resetForm">Resetuj</Button>
</div>
</template>
<script>
export default {
name: "CalculatorForm",
data() {
return {
active: false,
modal_loading: false,
suggestions: [],
ingredients_idx: 1,
ingredients: {
items: []
},
nutrition: {
kcal: 0,
carbohydrates: 0,
protein: 0,
fat: 0
}
};
},
methods: {
resetForm() {
this.modal_loading = false;
this.$refs.ingredients.resetFields();
this.ingredients_idx = 1;
this.ingredients = {
items: []
};
this.suggestions = []
this.nutrition.kcal = 0;
this.nutrition.carbohydrates = 0;
this.nutrition.protein = 0;
this.nutrition.fat = 0;
},
handleAddIngredient() {
this.ingredients_idx++;
this.ingredients.items.push({
value: '',
index: this.ingredients_idx
});
},
appendIngredient(item, val, instance) {
item.id = this.suggestions.find(obj => obj.name === val).id
},
handleRemoveIngredient(index) {
this.ingredients.items.splice(index, 1);
},
handleSearch(value) {
this.$axios.get('/product', {
params: {
limit: 5,
search: value
}
})
.then((res) => {
this.suggestions = res.data.data.products.data
})
},
calculate() {
const ingredients_list = this.ingredients.items.map(ing => ({
id: ing.id,
weight: ing.weight || 1
}));
this.$axios.post('/calculate', {products: ingredients_list})
.then((response) => {
this.nutrition = response.data.data.nutrition;
})
.catch((error) => {
console.log(error);
this.$Message.error('Błąd!');
});
}
}
};
</script>
<style scoped>
.input {
width: 15%;
}
</style>