<template>
    <v-sheet width="100%">
        <template v-if="(app.platform == 'b2b') && ($user.role.id == 5)">

            <v-sheet 
                v-if="app.dataSession.Registreusers.processing || (app.dataSession.Registreusers.request_count < 1)" 
                class="d-flex justify-center"
            >
                <div v-if="false">
                    {{ __('Se încarcă....') }}
                </div>
            </v-sheet>
                        
            <v-alert type="warning" outlined v-else-if="(departamenteaccesibile.length == 0)" class="ma-2">
                <span>
                    {{ __('Nu aveți acces la niciun departament.') }}
                </span>
            </v-alert>
        </template>
        
        <v-data-table
            dense
            disable-filtering
            disable-pagination
            fixed-header
            hide-default-footer
            hide-default-header
            multi-sort
            :headers="columns"
            :items="datatableitems"
            :height="height"
            :width="tableWidth + 100"
            :mobile-breakpoint="0"
            class="cs-datatable"
        >
            <template #header="{props}">
                <customer-register-table-header 
                    :headers="props.headers"
                    :app="app"
                    :departamenteaccesibile="departamenteaccesibile"
                    :allow_upload_row_files="allow_upload_row_files"
                />
            </template>

            <template #body="{ items }">
                <customer-register-table-body 
                    :app="app"
                    :items="items"
                    :allow_upload_row_files="allow_upload_row_files"
                /> 
            </template>

        </v-data-table>
    </v-sheet>
</template>

<script>
    export default {
        props: {
            app: {required: true},
            registru: {required: true},
            customerregistru: {required: true},
            height: {required: true},
        },

        computed: {
            controller() {
                return this.app.classes.Customerregistru;
            },

            filteroptions() {
                return this.app.classes.Customerregistru.filtermenu.filteroptions;
            },

            sortoptions() {
                return this.app.classes.Customerregistru.sortmenu.sortoptions;
            },

            allow_upload_row_files() {
                return 1 * this.customerregistru.props.registru.allow_upload_row_files == 1;
            },

            datatableitems() {
                let r = [];

                _.each(this.customerregistru.rows, row => {

                    let item = {};

                    _.each(this.columnwithvalues, col => {
                        
                        let element = _.find(row.values, v => 1 * v.column_id == 1 * col.value.replace('value_', ''));

                        item[col.value] = {
                            text: (!! element ? element.value : '-'),
                            column: {...col, files_count: row.files_count},
                            row_id: row.id,
                            createdby: row.createdby,
                            customer: row.customer,
                            created_at: row.created_at,
                        }
                    })

                    r.push(item);
                })

                r = _.filter(r, item => {

                    let result = true;
                    
                    _.each(item, column => {
                                     
                        if(this.app.platform == 'b2b' && column.column.type == 'STATUS' && column.text == 'protected')
                        {
                            result = false;
                        }
                        
                        if(this.filteroptions.status != 'all' && column.column.type == 'STATUS' && column.text != this.filteroptions.status )
                        {
                            result = false;
                        }

                        if(this.filteroptions.stare != 'all' && column.column.type == 'STARE' && column.text != this.filteroptions.stare )
                        {
                            result = false;
                        }

                        if(this.filteroptions.departament_id != 'all' && column.column.type == 'DEPARTAMENT' && 1 * column.text != 1 * this.filteroptions.departament_id )
                        {
                            result = false;
                        }


                        if(this.$user.role.id == 5)
                        {
                            if(column.column.type == 'DEPARTAMENT')
                            {
                                let value = 1 * column.text;
                                let exists = _.find(this.departamenteaccesibile, item => item == value);

                                if( ! exists )
                                {
                                    result = false;
                                }
                            }
                        }
                    });

                    return result;
                })

                if(this.sortoptions.column_id)
                {
                    r = _.orderBy(r, [item => item['value_' + this.sortoptions.column_id].text], [this.sortoptions.direction])
                }

                _.each(r, (item, i) => {
                    let nrcrt = 1 + i; 
                    item.value_nrcrt.text = nrcrt + '. ';
                    item.value_nrcrt.column.type = 'NRCRT';
                })
                
                return r;
            },

            columns() {
                let r = this.customerregistru.columns;

                _.each(r, column => {

                    if(column.type == 'STATUS')
                    {
                        column.caption = this.__('Vizibilitate');
                    }
    
                    if(1 * column.is_group == 0)
                    {
                        column.value = 'value_' + column.id;
                    }
                    else
                    {
                        _.each(column.children, child => {
                            child.value = 'value_' + child.id;
                        })
                    }
                    
                });
                
                return [
                    {
                        id: 'nrcrt',
                        caption: '#',
                        column_type: 'single',
                        is_group: 0,
                        type: 'NRCRT',
                        width: 180,
                        value: 'value_nrcrt',
                    },
                    ...r
                ];
            },

            columnwithvalues() {
                let r = [];

                _.each(this.columns, column => {

                    if(_.has(column, 'value'))
                    {
                        r.push(column);
                    }

                    _.each(column.children, child => {
                        if(_.has(child, 'value'))
                        {
                            r.push( child);
                        }
                    })

                });

                return r;
            },

            tableWidth() {
                let r = 0;
                _.each(this.columns, column => {
                    r += (1 * column.width + 2);
                    _.each(column.children, child => {
                        r += (1 * child.width + 2);
                    })
                })
                return r;
            },

            departamenteaccesibile() {
                if(this.app.dataSession.Registreusers.items.length == 0)
                {
                    return [];
                }
                return _.map(this.app.dataSession.Registreusers.items[0].departamente, item => 1 * item);
            }
        },

        watch: {
            'customerregistru.id': function(newid, oldid) {
                this.GetDepartamenteAccesibile();
            }
        },

        methods: {
            GetDepartamenteAccesibile() {

                console.log(this.$user.full_name, this.$user.role.slug);

                if(1 * this.$user.role.id == 5)
                {
                    this.app.dataSession.Registreusers.GetByCustomerRegistruIdAndUserId(this.customerregistru.id, this.$user.id);
                    let i = setInterval( () => {
                        if(! this.app.dataSession.Registreusers.processing )
                        {
                            clearInterval(i);
                        }
                    }, 350);

                }
            }
        },

        created() {
            this.GetDepartamenteAccesibile();
        },

        components: {
            CsCenteredAlert: require('@CsVueComp/sheets/CsCenteredAlert').default,
        },

        name: 'CustomerRegisterTable',
    }
</script>