<template>
    <div>
        <Button v-if="$auth.loggedIn" type="primary" @click="active = true">Dodaj przepis</Button>
        <Modal v-model="active" @on-cancel="cancel">
            <p slot="header" style="text-align:center">
                <Icon type="ios-restaurant"/>
                <span>Dodawanie przepisu</span>
            </p>
            <div>
                <Form ref="form" :model="form" :rules="rules">
                    <FormItem label="Nazwa" prop="name">
                        <Input v-model="form.name" placeholder="Podaj nazwę przepisu"/>
                    </FormItem>
                    <FormItem label="Krótki opis" prop="description">
                        <Input v-model="form.description" type="textarea" placeholder="Podaj opis przepisu"/>
                    </FormItem>
                </Form>
                <h3>Składniki</h3>
                <Form ref="ingredients" :model="form.ingredients">
                    <FormItem
                            v-for="(item, index) in form.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: 25%"/>
                            <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>
                <h3>Przygotowanie</h3>
                <Form ref="preparation" :model="form.steps">
                    <FormItem
                            v-for="(item, index) in form.steps.items"
                            :key="index"
                            label="Krok"
                            :prop="'items.' + index + '.value'"
                            :rules="{required: true, message: 'Proszę podać opis kroku', trigger: 'blur'}">
                        <Row style="display: flex; justify-items: center">
                            <Input type="textarea" :rows="1" v-model="item.value" placeholder="Opis kroku"/>
                            <Button @click="handleRemovePreparationStep(index)" style="margin-left: 3px">Usuń</Button>
                        </Row>
                    </FormItem>
                    <FormItem>
                        <Row>
                            <Button type="dashed" long @click="handleAddPreparationStep" icon="md-add">Dodaj krok
                            </Button>
                        </Row>
                    </FormItem>
                </Form>
            </div>
            <div slot="footer">
                <Button type="error" @click="cancel">Anuluj</Button>
                <Button type="success" :loading="modal_loading" @click="ok">Zatwierdź</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    export default {
        name: 'AddRecipeModal',
        data() {
            const validateIngredients = (rule, value, callback) => {
                if (this.form.ingredients.items.length > 0) {
                    callback();
                } else {
                    callback(new Error('Podaj chociaż jeden składnik!'));
                }
                callback();
            };
            const validatePreparation = (rule, value, callback) => {
                if (this.form.steps.items.length > 0) {
                    callback();
                } else {
                    callback(new Error('Podaj chociaż jeden krok!'));
                }
                callback();
            };
            return {
                active: false,
                modal_loading: false,
                suggestions: [],
                ingredients_idx: 1,
                preparation_step_idx: 1,
                form: {
                    name: null,
                    description: null,
                    ingredients: {
                        items: []
                    },
                    steps: {
                        items: []
                    }
                },
                rules: {
                    name: [
                        {
                            required: true,
                            message: 'Proszę podać nazwę przepisu',
                            trigger: 'blur'
                        }
                    ],
                    description: [
                        {
                            required: true,
                            message: 'Proszę podać opis przepisu',
                            trigger: 'blur'
                        }
                    ]
                },
            };
        },
        methods: {
            cancel() {
                this.active = false;
                this.resetForm();
                this.$Message.error('Anulowano');
            },
            ok() {
                this.$refs.form.validate((valid) => {
                    if (!valid) {
                        this.$Message.error('Błąd');
                        return;
                    }

                    const recipe = {
                        'name': this.form.name,
                        'description': this.form.description,
                        'steps': this.form.steps.items.map(step => step.value),
                        'ingredients': this.form.ingredients.items.map(ing => ({id: ing.id, weight: ing.weight || 1}))
                    };


                    this.modal_loading = true;
                    this.$axios.post('/recipe', recipe)
                        .then(() => {
                            this.$Message.success('Sukces!');
                            this.active = false;
                            this.$emit('recipe-added');
                            this.resetForm();
                        })
                        .catch(() => {
                            this.$Message.error('Błąd!');
                            this.modal_loading = false;
                        });

                });
            },
            resetForm() {
                this.modal_loading = false;
                this.$refs.form.resetFields();
                this.$refs.ingredients.resetFields();
                this.ingredients_idx = 1;
                this.form.ingredients = {
                    items: []
                };
                this.$refs.preparation.resetFields();
                this.preparation_step_idx = 1;
                this.form.steps = {
                    items: []
                };
                this.suggestions = []
            },
            handleAddIngredient() {
                this.ingredients_idx++;
                this.form.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.form.ingredients.items.splice(index, 1);
            },
            handleAddPreparationStep() {
                this.preparation_step_idx++;
                this.form.steps.items.push({
                    value: '',
                    index: this.preparation_step_idx
                });
            },
            handleRemovePreparationStep(index) {
                this.form.steps.items.splice(index, 1);
            },
            handleSearch(value) {
                this.$axios.get('/product', {
                    params: {
                        limit: 5,
                        search: value
                    }
                })
                    .then((res) => {
                        this.suggestions = res.data.data.products.data
                    })
            }
        }
    };
</script>

<style scoped>
    .input {
        width: 15%;
    }
</style>
