<template id="listDataTable">
    <div class="listdatatable" data-effect="fadeIn">
        <div class="row">
            <div class="col-lg-12" style="margin-top: 0">
                <div class="hpanel hblue">
                    <div class="pull-right">
                        <div class="btn-group">
                            <prime-button :label="$t('label.pdf')" class="p-button-text p-button-danger p-button-sm"
                                          icon="pi pi-file-pdf" @click="downloadPdf()"/>
                            <prime-button :label="$t('label.excel')" class="p-button-text p-button-success p-button-sm"
                                          icon="pi pi-file-excel" @click="downloadExcel()"/>
                            <prime-button :label="$t('label.xml')" class="p-button-text p-button-info p-button-sm"
                                          icon="pi pi-share-alt" @click="downloadXml()"/>
                            <prime-button :label="$t('label.csv')" class="p-button-text p-button-help p-button-sm"
                                          icon="pi pi-book" @click="downloadCsv()"/>
                            <prime-button :label="$t('label.txt')" class="p-button-text p-button-plain p-button-sm"
                                          icon="pi pi-file" @click="downloadTxt()"/>
                            <prime-button :label="$t('label.insert')" class="p-button-success p-button-sm"
                                          data-position="rigth" icon="pi pi-plus" @click="callInsert()">
                            </prime-button>
                        </div>
                    </div>

                    <div class="panel-heading hbuilt">
                        {{ title }}
                    </div>

                    <div class="panel-body">
                        <prime-data-table
                            :value="paginator.list" :paginator="true" :rows="paginator.maxResults"
                            :lazy="true" :loading="loading" @page="onPage($event)"
                            :totalRecords="paginator.total" class="p-datatable-sm"
                            :scrollable="true" scrollDirection="both" stripedRows showGridlines
                            selectionMode="single" dataKey="id" v-model:selection="entityLookup">
                            <prime-column v-if="showColumnAction" class="column-action" :header="$t('label.actions')"
                                          frozen>
                                <template #body="slotProps">
                                    <prime-button v-if="slotProps.data.visibleMenuClone"
                                                  :disabled="slotProps.data.disabledMenuClone"
                                                  icon="pi pi-clone"
                                                  class="p-button-rounded p-button-help p-mr-2 button-action"
                                                  v-tooltip="$t('label.clone')"
                                                  @click="callClone(slotProps.data)"/>

                                    <prime-button v-if="slotProps.data.visibleMenuChange"
                                                  :disabled="slotProps.data.disabledMenuChange"
                                                  icon="pi pi-pencil"
                                                  class="p-button-rounded p-button-warning p-mr-2 button-action"
                                                  v-tooltip="$t('label.change')"
                                                  @click="callChange(slotProps.data)"/>

                                    <prime-button v-if="slotProps.data.visibleMenuConsult"
                                                  :disabled="slotProps.data.disabledMenuConsult"
                                                  icon="pi pi-eye"
                                                  class="p-button-rounded p-button-info p-mr-2 button-action"
                                                  v-tooltip="$t('label.consult')"
                                                  @click="callConsult(slotProps.data)"/>

                                    <prime-button v-if="slotProps.data.visibleMenuDelete"
                                                  :disabled="slotProps.data.disabledMenuDelete"
                                                  icon="pi pi-trash"
                                                  class="p-button-rounded p-button-danger button-action"
                                                  v-tooltip="$t('label.delete')"
                                                  @click="callDelete(slotProps.data)"/>
                                </template>
                            </prime-column>

                            <prime-column v-if="showColumnActionDynamic" class="column-action-speeddial" header=""
                                          frozen>
                                <template #body="slotProps">
                                    <prime-speeddial :model="menuActionDynamic(slotProps.data)"
                                                     show-icon="pi pi-bars"
                                                     direction="right"
                                                     :tooltip-options="{position: 'top'}"/>
                                </template>
                            </prime-column>

                            <prime-column v-for="column in columns" :key="column.field" :field="column.field"
                                          :style="`'width': ${column.size}`" :bodyStyle="column.style"
                                          :headerStyle="column.style" :header="column.title">

                                <template #body="slotProps" v-if="column.type === 'MONEY'">
                                    <label class="money">{{ formatCurrency(slotProps.data[column.field]) }}</label>
                                </template>
                            </prime-column>

                            <template #empty>
                                {{ $t('message.noRecordFound') }}
                            </template>
                        </prime-data-table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import PrimeDataTable from "primevue/datatable"
import PrimeColumn from 'primevue/column'
import PrimeSpeeddial from 'primevue/speeddial'
import PrimeButton from 'primevue/button'
import {useLoading} from "vue3-loading-overlay";

const INSERT = 'INSERT';
const CLONE = 'CLONE';
const CHANGE = 'CHANGE';
const CONSULT = 'CONSULT';
const DELETE = 'DELETE';

export default {
    components: {
        PrimeDataTable,
        PrimeColumn,
        PrimeSpeeddial,
        PrimeButton
    },
    name: "ListDatatable",
    props: {
        title: {type: String, required: true},
        path: {type: String, required: true},
        routerNameData: {type: String, required: true},
        paginator: {},
        search: {},
        showColumnAction: {type: Boolean, default: true},
        showColumnActionDynamic: {type: Boolean, default: false},
        modelValue: {type: [String, Number]},
    },
    created() {
        this.load()
    },
    data() {
        return {
            columns: {},
            accessMenu: {},
            loading: false,
        }
    },
    computed: {
        entityLookup: {
            get() {
                return this.$store.getters.entityLookup
            },
            set(newValue) {
                return this.$store.dispatch('setEntityLookup', newValue)
            }
        },
    },
    methods: {
        menuActionDynamic(item) {
            let menu = []
            this.$emit("onMenuActionDynamic", {menu, item})
            return menu
        },
        load() {
            this.loading = true
            this.$http.get(this.path + '/object/columnList').then((res) => this.columns = res.data)
            this.$http.get(this.path + '/object/accessMenu').then((res) => this.accessMenu = res.data)
            this.loading = false
        },
        onPage(event) {
            this.loading = true
            // this.paginator.first = event.first
            // this.paginator.maxResults = event.rows
            this.$emit('onPage', event)
            this.loading = false
        },
        downloadPdf() {
            const loader = useLoading()
            loader.show({height: 200, width: 200})

            this.$http.post(`${this.path}/pdf`, this.search,
                {
                    method: "POST",
                    responseType: "blob",
                }
            ).then(res => {
                    if (res.data.size !== 0) {
                        let blob = new Blob([res.data], {
                            type: "application/pdf"
                        });
                        let link = document.createElement("a");
                        link.href = window.URL.createObjectURL(blob);
                        link.download = "report";
                        link.click();
                    }
                }
            ).catch(error => console.log(error)
            ).finally(() => loader.hide());
        },
        downloadExcel() {
            const loader = useLoading()
            loader.show({height: 200, width: 200})

            this.$http.post(`${this.path}/excel`, this.search,
                {
                    method: "POST",
                    responseType: "blob",
                }
            ).then(res => {
                    if (res.data.size !== 0) {
                        let blob = new Blob([res.data], {
                            type: "application/vnd.ms-excel"
                        });
                        let link = document.createElement("a");
                        link.href = window.URL.createObjectURL(blob);
                        link.download = "document";
                        link.click();
                    }
                }
            ).catch(error => console.log(error)
            ).finally(() => loader.hide());
        },
        downloadXml() {
            const loader = useLoading()
            loader.show({height: 200, width: 200})

            this.$http.post(`${this.path}/xml`, this.search,
                {
                    method: "POST",
                    responseType: "blob",
                }
            ).then(res => {
                    if (res.data.size !== 0) {
                        let blob = new Blob([res.data], {
                            type: "application/xml"
                        });
                        let link = document.createElement("a");
                        link.href = window.URL.createObjectURL(blob);
                        link.download = "document.xml";
                        link.click();
                    }
                }
            ).catch(error => console.log(error)
            ).finally(() => loader.hide());
        },
        downloadTxt() {
            const loader = useLoading()
            loader.show({height: 200, width: 200})

            this.$http.post(`${this.path}/txt`, this.search,
                {
                    method: "POST",
                    responseType: "blob",
                }
            ).then(res => {
                    if (res.data.size !== 0) {
                        let blob = new Blob([res.data], {
                            type: "text/plain"
                        });
                        let link = document.createElement("a");
                        link.href = window.URL.createObjectURL(blob);
                        link.download = "document";
                        link.click();
                    }
                }
            ).catch(error => console.log(error)
            ).finally(() => loader.hide());
        },
        downloadCsv() {
            const loader = useLoading()
            loader.show({height: 200, width: 200})

            this.$http.post(`${this.path}/csv`, this.search,
                {
                    method: "POST",
                    responseType: "blob",
                }
            ).then(res => {
                    if (res.data.size !== 0) {
                        let blob = new Blob([res.data], {
                            type: "text/csv"
                        });
                        let link = document.createElement("a");
                        link.href = window.URL.createObjectURL(blob);
                        link.download = "document";
                        link.click();
                    }
                }
            ).catch(error => console.log(error)
            ).finally(() => loader.hide());
        },
        callInsert() {
            this.$router.push({
                name: this.routerNameData,
                params: {...this.$route.params},
                query: {action: INSERT}
            })
        },
        callClone(entity) {
            this.$router.push({
                name: this.routerNameData,
                params: {"id": entity.id, ...this.$route.params},
                query: {action: CLONE, id: entity.id}
            })
        },
        callChange(entity) {
            this.$router.push({
                name: this.routerNameData,
                params: {"id": entity.id, ...this.$route.params},
                query: {action: CHANGE, id: entity.id}
            })
        },
        callConsult(entity) {
            this.$router.push({
                name: this.routerNameData,
                params: {"id": entity.id, ...this.$route.params},
                query: {action: CONSULT, id: entity.id}
            })
        },
        callDelete(entity) {
            this.$router.push({
                name: this.routerNameData,
                params: {"id": entity.id, ...this.$route.params},
                query: {action: DELETE, id: entity.id}
            })
        },
        formatCurrency(value) {
            return parseFloat(value || '0').toLocaleString('pt-BR', {
                style: 'currency',
                currency: 'BRL',
                currencyDisplay: 'symbol'
            });
        }
    }
}
</script>

<style lang="scss">

.listdatatable {
    padding: 5px 15px 5px 15px;
    min-width: 320px;
    line-height: 1em;
    font-size: 14px !important;

    .hpanel {
        background-color: unset;
        border: none;
        box-shadow: none;
        /* margin-bottom: 25px; */
        /* margin-top: 20px; */
    }

    .hpanel.hblue .panel-body {
        border-top: 2px solid #3498db;
        border-top-color: rgb(52, 152, 219);
    }

    .hpanel .panel-body {
        background: #fff;
        padding: 0px;
        position: relative;
    }

    .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;
    }

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

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

    .panel-body {
        padding: 15px;
    }

    .export-file .dropdown-item:focus, .list-datatable .export-file .dropdown-item:hover {
        background-color: lightgray !important;
    }

    .p-datatable-tbody > tr > td {
        padding: 4px 10px !important;
    }

    .p-datatable-tbody > tr > td {
        padding: 4px 10px !important;
    }

    .p-datatable-scrollable-wrapper, .list-datatable .p-datatable-scrollable-view, .list-datatable .p-datatable-scrollable-body {
        min-height: 200px !important;
    }

    .b-dropdown > button.btn.dropdown-toggle.btn-secondary.btn-sm {
        background-color: transparent;
        border: transparent;
    }

    .dropdown-item {
        font-size: 14px;
        padding: 10px;
    }

    .p-button {
        height: 30px !important;
        margin-left: 5px;
    }

    .p-button.button-action {
        border-radius: 50%;
        margin: 2px;
        width: 30px !important;
    }

    .btn-group, .btn-group-vertical {
        position: relative;
        display: inline-block;
        vertical-align: middle;
        margin: 2px 5px;

        .p-button {
            //min-width: 100px !important;
        }
    }

    span, td {
        font-size: 14px;
    }

    .p-paginator.p-paginator-bottom button {
        height: 25px;
    }

    .column-action {
        text-align: center;
        min-width: 180px;
    }

    .p-datatable .p-column-header-content, .p-column-title {
        width: 100%;
    }

    .p-datatable .p-datatable-thead > tr > th {
        background: #eeeeee;
    }

    .p-datatable.p-datatable-striped .p-datatable-tbody > tr:nth-child(even) {
        background: #f8f8f8;
    }

    .money {
        width: 100%;
    }

    .column-action-speeddial {
        text-align: center;
        min-width: 70px;
    }

    .p-speeddial .p-button.p-component {
        border-radius: 50%;
        margin: 8px;
        width: 30px !important;
    }
}
</style>
