<template>
    <div class="data-master" style="padding: 5px">
        <div class="content" data-effect="fadeIn">
            <div class="hpanel hblue">
                <div class="panel-heading hbuilt">
                    <div class="panel-tools">
                        <a class="showhide">
                            <i class="fa fa-chevron-up"/>
                        </a>
                    </div>

                    {{ titlePage }}
                </div>

                <div class="panel-body">
                    <div class="p-fluid formgrid grid">
                        <slot></slot>
                    </div>
                </div>

                <div class="panel-footer" style="padding: 5px">
                    <table class="ui-panelgrid ui-widget" style="width: 100%;">
                        <tbody>
                        <tr>
                            <td style="text-align: left; width: 33%">
<!--                                <cc:renderFacet name="bottomLeft"/>-->
                            </td>

                            <td style="text-align: center; width: 33%">
                                <button v-if="workflow" variant="primary" target="_blank" style=" min-width: 100px">
                                    <i class="fa fa-area-chart"/> {{ $t('label.workflow') }}
                                </button>
                            </td>

                            <td style="text-align: right">
                                <jarch-button-cancel :label="labelButtonWarning" @click="returnPageList"/>
                                <jarch-button-save v-if="isInsert || isClone || isChange" type="button"
                                                   @click="callSave"/>
                                <jarch-button-delete v-else-if="isDelete" @click="callDelete"/>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import $ from 'jquery'
import {useLoading} from "vue3-loading-overlay";
import {mapActions, mapGetters} from "vuex";
import JarchButtonCancel from '../form/ButtonCancel'
import JarchButtonSave from '../form/ButtonSave'
import JarchButtonDelete from '../form/ButtonDelete'

export default {
    name: "DataMaster",
    components: {
        JarchButtonCancel, JarchButtonSave, JarchButtonDelete
    },
    props: {
        title: {type: String, required: true},
        icon: {type: String, required: false},
        path: {type: String, required: true},
        routerNameList: {type: String, required: true},
        action: {type: String, required: true},
        workflow: {type: Boolean, default: false},
    },
    data() {
        return {
            submitted: false,
            error: {}
        }
    },
    mounted() {
        this.setFieldErrors([])

        // Function for collapse hpanel
        $('.showhide').click(function (event) {
            event.preventDefault();
            const hpanel = $(this).closest('div.hpanel');
            const icon = $(this).find('i:first');
            const body = hpanel.find('div.panel-body');
            const footer = hpanel.find('div.panel-footer');
            body.slideToggle(300);
            footer.slideToggle(200);
            // Toggle icon from up to down
            icon.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
            hpanel.toggleClass('').toggleClass('panel-collapse');
            setTimeout(function () {
                hpanel.resize();
                hpanel.find('[id^=map-]').resize();
            }, 50);
        });

        this.load()
    },
    computed: {
        ...mapGetters(['entity', 'messages']),
        titlePage() {
            return this.$t('label.data') + " - " + this.title
        },
        descriptionPage() {
            return this.$t('label.keep') + " - " + this.title
        },
        isInsert() {
            return this.action === 'INSERT'
        },
        isClone() {
            return this.action === 'CLONE'
        },
        isChange() {
            return this.action === 'CHANGE'
        },
        isConsult() {
            return this.action === 'CONSULT'
        },
        isDelete() {
            return this.action === 'DELETE'
        },
        isDynamic() {
            return this.action === 'DYNAMIC'
        },
        labelButtonWarning() {
            if (this.isInsert || this.isClone || this.isChange || this.isDelete)
                return this.$t('label.cancel')
            else
                return this.$t('label.return')
        }
    },
    methods: {
        ...mapActions(['setInsertEntity', 'setFieldErrors']),
        async load() {

        },
        showMessageAndReturnPageList(loader) {
            loader.hide()

            this.$swal({
                title: this.$t('label.success'),
                text: this.$t('label.processSuccess'),
                icon: 'info',
                button: {
                    // text: "Processando...",
                    closeModal: false,
                },
                allowOutsideClick: false,
                closeOnClickOutside: false,
                closeOnEsc: false

            }).then(() => this.returnPageList())
        },
        showMessageErrors(loader, err) {
            loader.hide()
            if (err === undefined) {
                let summary = this.$t('label.error')
                let message = this.$t('label.errorImprevist')
                this.$toast.add({severity: 'error', summary: summary, detail: message, life: 5000})
                return
            } else if (err.response === undefined) {
                let summary = this.$t('label.error')
                let message = err
                this.$toast.add({severity: 'error', summary: summary, detail: message, life: 5000})
                return
            } else if (err.response.data === undefined) {
                let summary = this.$t('label.error')
                let message = err.response.data
                this.$toast.add({severity: 'error', summary: summary, detail: message, life: 5000})
                return
            }

            let fields = [];
            err.response.data.forEach(e => {
                    const pos = e.indexOf(':')
                    const existField = pos > -1
                    const field = existField ? e.substr(0, pos) : this.$t('label.validation')
                    const message = existField ? e.substr(pos + 1).trim() : e

                    if (existField)
                        fields.push(field)

                    this.$toast.add({severity: 'error', summary: field, detail: message, life: 5000})
                }
            )

            this.setFieldErrors(fields);
        },
        callSave() {
            const loader = useLoading()
            loader.show({height: 200, width: 200})

            this.$emit('onSave', {
                action: this.action,
                disabled: this.isConsult || this.isDelete,
                entity: this.entity
            })

            if (this.isInsert) {
                this.$http.post(`${this.path}`, this.entity)
                    .then(() => this.showMessageAndReturnPageList(loader))
                    .catch((err) => this.showMessageErrors(loader, err))
            } else if (this.isClone) {
                this.entity.id = null
                this.$http.post(`${this.path}`, this.entity)
                    .then(() => this.showMessageAndReturnPageList(loader))
                    .catch((err) => this.showMessageErrors(loader, err))
            } else if (this.isChange) {
                this.$http.put(`${this.path}`, this.entity)
                    .then(() => this.showMessageAndReturnPageList(loader))
                    .catch((err) => this.showMessageErrors(loader, err))
            }
        },
        callDelete() {
            const loader = useLoading()
            loader.show({height: 200, width: 200})

            this.$http.delete(`${this.path}/${this.entity.id}`)
                .then(() => this.showMessageAndReturnPageList(loader))
                .catch((err) => this.showMessageErrors(loader, err))
        },
        returnPageList() {
            this.$toast.removeAllGroups()
            this.$router.push({
                name: this.routerNameList,
                params: {...this.$route.params}
            })
        },
    }
}
</script>

<style lang="scss">
.data-master {
    font-size: 13px !important;
    font-weight: bold;

    .content {
        padding: 5px 20px 5px 20px;
        min-width: 320px;
    }

    .hpanel {
        background-color: unset;
        border: none;
        box-shadow: none;
    }

    .hpanel .hbuilt.panel-heading {
        border-bottom: none;
    }

    .hpanel.panel-collapse > .panel-heading, .hpanel .hbuilt {
        background: #fff;
        border: 1px solid #e4e5e7;
        padding: 10px 10px;
        border-radius: 2px;
    }

    .hpanel > .panel-heading {
        color: inherit;
        font-weight: 600;
        padding: 10px 4px;
        transition: all .3s;
        border: 1px solid transparent;
    }

    .panel-heading {
        padding: 10px 15px;
        border-bottom: 1px solid transparent;
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
    }

    .panel-tools {
        display: inline-block;
        float: right;
        margin-top: 0;
        padding: 0;
        position: relative;
    }

    .panel-tools a {
        margin-left: 5px;
        color: #9d9fa2;
        cursor: pointer;
    }

    .hpanel.hblue .panel-body {
        border-top: 2px solid #3498db;
    }

    .hpanel .panel-body {
        background: #fff;
        border: 1px solid #e4e5e7;
        border-radius: 2px;
        padding: 10px;
        position: relative;
    }

    .hpanel > .panel-footer {
        color: inherit;
        border: 1px solid #e4e5e7;
        border-top: none;
        font-size: 90%;
        background: #f7f9fa;
        padding: 10px 15px;
    }

    .hpanel > .panel-footer {
        color: inherit;
        border: 1px solid #e4e5e7;
        border-top: none;
        font-size: 90%;
        background: #f7f9fa;
    }

    .panel-footer {
        padding: 10px 15px;
        background-color: #f5f5f5;
        border-top: 1px solid #ddd;
        border-bottom-right-radius: 3px;
        border-bottom-left-radius: 3px;
    }

    .p-inputtext, .p-inputtext.p-inputtext-sm {
        font-size: 13px;
        padding: 4px;
    }

    .p-button {
        font-size: 13px;
        height: 30px;
        width: unset;
        margin-left: 10px;
        text-align: left;
    }
}
</style>
