<template>
    <div>
        <b-alert v-for="(error, index) in errors" :key="index" variant="danger" show>
            {{ Object.values(error)[0] }}
        </b-alert>
        <b-form @submit.prevent="onSubmit">
            <b-row>
                <b-col v-for="(widget, index) in nonTranslatableWidgets" :key="index" :cols="12" :md="widget.cols > 6 ? 12 : 6" :lg="widget.cols">
                    <component v-if="showWidget(widget)" :is="readonly ? widget.viewGroupTag : widget.groupTag" :widget="widget" :properties="properties" :errors.sync="errors" :crud-type="readonly ? 'show' : (item == null ? 'create' : 'edit')" v-model="form[widget.name]" :data="form" />
                </b-col>
            </b-row>

            <b-card v-if="translatableWidgets.length > 0" no-body>
                <b-row>
                    <b-col v-if="!readonly">
                        <b-tabs fill small card pills>
                            <b-tab @click="onShowTranslationButton" :title="mainLocale.name">
                                <b-row>
                                    <b-col v-for="(widget, index) in translatableWidgets" :key="'tr' + mainLocale.locale + '_' + index" :cols="12" :md="widget.cols > 6 ? 12 : 6" :lg="widget.cols">
                                        <component v-if="showWidget(widget)" :is="readonly ? widget.viewGroupTag : widget.groupTag" :widget="widget" :properties="properties" :errors.sync="errors" :crud-type="readonly ? 'show' : (item == null ? 'create' : 'edit')" :field-locale="mainLocale.locale" v-model="form.sanjab_translations[mainLocale.locale][widget.name]" />
                                    </b-col>
                                </b-row>
                            </b-tab>
                        </b-tabs>
                    </b-col>
                    <b-col id="translations_tab" v-show="readonly">
                        <b-tabs v-model="currentLocaleTab" fill small card pills>
                            <b-tab v-for="(localeName, locale) in locales" :key="locale" :title="localeName">
                                <b-row>
                                    <b-col v-for="(widget, index) in translatableWidgets" :key="'tr' + locale + '_' + index" :cols="12" :md="widget.cols > 6 ? 12 : 6" :lg="widget.cols">
                                        <component v-if="showWidget(widget)" :is="readonly ? widget.viewGroupTag : widget.groupTag" :widget="widget" :properties="properties" :errors.sync="errors" :crud-type="readonly ? 'show' : (item == null ? 'create' : 'edit')" :field-locale="locale" v-model="form.sanjab_translations[locale][widget.name]" :data="form.sanjab_translations[locale]" />
                                    </b-col>
                                </b-row>
                            </b-tab>
                        </b-tabs>
                    </b-col>
                </b-row>
            </b-card>

            <b-button v-if="readonly" variant="warning" :href="sanjabUrl('/modules/' + properties.route + '/' + item.id + '/edit')" :title="sanjabTrans('edit')" v-b-tooltip>
                <b-spinner v-if="loading" small></b-spinner>
                {{ sanjabTrans('edit') }}
            </b-button>
            <b-button v-if="!readonly" variant="success" type="submit" :disabled="loading">
                <b-spinner v-if="loading" small></b-spinner>
                {{ sanjabTrans('save') }}
            </b-button>
            <b-button v-if="readonly == false && formUrl == null" @click="onSubmit('continue')" variant="primary" type="button" :disabled="loading">
                <b-spinner v-if="loading" small></b-spinner>
                {{ sanjabTrans('save_and_edit_this') }}
            </b-button>
            <b-button v-if="readonly == false && formUrl == null && (item == null || item.id == null)" @click="onSubmit('add_more')" variant="warning" type="button" :disabled="loading">
                <b-spinner v-if="loading" small></b-spinner>
                {{ sanjabTrans('save_and_add_more') }}
            </b-button>
        </b-form>
    </div>
</template>

<script>
    export default {
        props: {
            widgets: {
                type: Array,
                default: () => []
            },
            properties: {
                type: Object,
                default: () => {return {};}
            },
            item: {
                type: Object,
                default: null
            },
            successUrl: {
                type: String,
                default: null
            },
            formUrl: {
                type: String,
                default: null
            },
            formMethod: {
                type: String,
                default: null
            },
            readonly: {
                type: Boolean,
                default: false
            }
        },
        created () {
            this.fixFormData();
        },
        mounted () {
            this.loadForm();
        },
        data() {
            return {
                form: {},
                errors: {},
                loading: true,
                currentLocaleTab: 0,
                showTranslation: false
            };
        },
        methods: {
            onSubmit(type = 'continue') {
                var self = this;
                self.loading = true;
                axios({
                    method: self.formMethod ? self.formMethod : (self.item ? 'put' : 'post'),
                    url: self.formUrl ? self.formUrl : (self.item ? sanjabUrl('/modules/' + self.properties.route + '/' + self.item.id) : sanjabUrl('/modules/' + self.properties.route)),
                    data: self.form
                }).then(function (response) {
                    self.loading = false;
                    if (self.$listeners && self.$listeners.onSuccess) {
                        self.$emit('onSuccess');
                    } else if (self.successUrl) {
                        if (self.successUrl != window.location.href) {
                            window.location.href = self.successUrl;
                        } else {
                            window.location.reload();
                        }
                    } else {
                        if (type == 'continue') {
                            if (self.item && self.item.id) {
                                window.location.reload();
                            } else {
                                window.location.href = sanjabUrl('/modules/' + self.properties.route + '/' + response.data.id + '/edit');
                            }
                        } else if (type == 'add_more') {
                            window.location.href = sanjabUrl('/modules/' + self.properties.route + '/create');
                        } else {
                            window.location.href = sanjabUrl('/modules/' + self.properties.route);
                        }
                    }
                }).catch(function (error) {
                    self.loading = false;
                    console.error(error);
                    if (error.response.status == 422) {
                        self.errors = error.response.data.errors;
                        $("body, html").animate({'scroll-top': 0})
                    } else {
                        sanjabHttpError(error.response.status);
                    }
                });
            },
            showWidget (widget) {
                if (this.form.__sanjab_last_time_refreshed == null || Math.floor(Date.now() / 1000) > this.form.__sanjab_last_time_refreshed) {
                    this.form.__sanjab_last_time_refreshed = Math.floor(Date.now() / 1000);
                    this.form = Object.assign({}, this.form);
                }
                return ((this.readonly && widget.onView) || (this.readonly == false && ((this.item == null && widget.onCreate) || (this.item != null && widget.onEdit))))
                        && (widget.showIf == null || eval(widget.showIf.replace(/([^this\.]|^)form/g, '$1this.form')));
            },
            loadForm() {
                if (this.item) {
                    this.form = this.item;
                    this.fixFormData();
                    this.loading = false;
                    this.$forceUpdate();
                    setTimeout(() => $(".bmd-form-group input, .bmd-form-group textarea").trigger("blur").trigger("change"), 50);
                } else {
                    this.loading = false;
                }
            },
            fixFormData() {
                for (var i in this.widgets) {
                    if (this.widgets[i].translation == false) {
                        if (this.form[this.widgets[i].name] == undefined) {
                            this.form[this.widgets[i].name] = this.widgets[i].value;
                        }
                    }
                }
                if (typeof this.form.sanjab_translations !== 'object') {
                    this.form.sanjab_translations = {};
                    for (var i in this.allLocales) {
                        this.form.sanjab_translations[i] = {};
                    }
                }
                for (var i in this.allLocales) {
                    for (var j in this.widgets) {
                        if (this.widgets[j].translation) {
                            if (this.form.sanjab_translations[i][this.widgets[j].name] == undefined) {
                                this.form.sanjab_translations[i][this.widgets[j].name] = this.widgets[j].value;
                            }
                        }
                    }
                }
            },
            onShowTranslationButton() {
                if ($("#translations_tab").is(":visible")) {
                    $("#translations_tab").fadeOut();
                } else {
                    $("#translations_tab").fadeIn();
                }
            }
        },
        computed: {
            nonTranslatableWidgets() {
                return this.widgets.filter((widget) => widget.translation == false);
            },
            translatableWidgets() {
                return this.widgets.filter((widget) => widget.translation == true);
            },
            allLocales() {
                return window.sanjab.config.locales;
            },
            locales() {
                var locales = {};
                for (var i in window.sanjab.config.locales) {
                    if (i != this.mainLocale.locale || this.readonly) {
                        locales[i] = window.sanjab.config.locales[i];
                    }
                }
                return locales;
            },
            mainLocale() {
                if (typeof window.sanjab.config.locales[window.sanjab.app.locale] === 'undefined') {
                    return {locale: Object.keys(window.sanjab.config.locales)[0], name: window.sanjab.config.locales[Object.keys(window.sanjab.config.locales)[0]]};
                }
                return {locale: window.sanjab.app.locale, name: window.sanjab.config.locales[window.sanjab.app.locale]};
            }
        },
    }
</script>
