const HourAllocationDataTable = {
    templateUrl : 'js/app/components/kkspecial/hour-allocation-datatable.html',
    create : function( params )
    {
        const app = this.app,
            self = this,
            $container = $( this.container ),
            ws = params.getAll();

        let dTable = null;

        this.render( { ws: ws } );


        $( this.container ).on( 'click', '[data-type="workshift-row"]', function()
        {
            let workshift = null,
                workshiftRow = null,
                oldRowData = null,
                appointmentId = $( this ).attr( 'data-appointment-id' ),
                employeeId = $( this ).attr( 'data-employee-id' );

            for ( let wi = 0; wi < ws.length; wi++ )
            {
                if ( ws[ wi ].appointment_id == appointmentId && ws[ wi ].profile_id == employeeId )
                {
                    workshift = ws[ wi ];
                    break;
                }
            }

            if ( !workshift )
            {
                return false;
            }

            workshiftRow = dTable.row( '#ws-' + appointmentId + '-' + employeeId );
            if ( !workshiftRow )
            {
                return false;
            }

            oldRowData = workshiftRow.data();

            let $modalRoot = $container.find( '[data-id="modal-kkspecial-edit-workshift"]' ).first();

            $modalRoot.find( '[data-id="section-loader"]' ).first().hide();
            $modalRoot.find( '[data-id="section-workshift-form"]' ).first().show();

            console.log( oldRowData, workshift );

            $modalRoot.find( '[data-id="input-workshift-hourly-rate"]' ).first().val( parseFloat( workshift.hourly_rate ) );
            $modalRoot.find( '[data-id="input-workshift-gross-hour"]' ).first().val( parseFloat( workshift.gross_hour ) );
            $modalRoot.find( '[data-id="input-workshift-pause-hour"]' ).first().val( parseFloat( workshift.pause_hour ) );
            $modalRoot.find( '[data-id="input-workshift-net-hour"]' ).first().val( parseFloat( workshift.net_hour ) );
            $modalRoot.find( '[data-id="input-workshift-wage"]' ).first().val( ( parseFloat( workshift.net_hour ) * parseFloat( workshift.hourly_rate ) ).toFixed( 2 ) );
            $modalRoot.find( '[data-id="input-workshift-additional-pay"]' ).first().val( parseFloat( workshift.additional_pay ).toFixed( 2 ) );
            $modalRoot.find( '[data-id="input-workshift-notice"]' ).first().val( workshift.notice ? workshift.notice : ''  );
            $modalRoot.find( '[data-id="user-address"]' ).first().html( workshift.member.getName() + '<br />' + workshift.member.getAddress() );
            $modalRoot.find( '[data-id="user-notice"]' ).first().html( workshift.member.kk_notice ? workshift.member.kk_notice : '---' );
            $modalRoot.find( '[data-id="appointment-subject"]' ).first().html( workshift.appointment_subject + ', ' + workshift.appointment_momentStart.format( 'DD.MM.YYYY [-] hh:mm' ) );
            $modalRoot.find( '[data-id="user-hour-max"]' ).first().html( self.nf( workshift.member.kk_hourMax, 2 ) + '&nbsp;h' );
            $modalRoot.find( '[data-id="user-hourly-rate"]' ).first().html( self.nf( workshift.member.kk_hourlyRate, 2 ) + '&nbsp;€' );
            $modalRoot.find( '[data-id="section-loader"]' ).first().hide();
            $modalRoot.on( 'shown.bs.modal', function()
            {
                $modalRoot.find( '[data-id="input-workshift-gross-hour"]' ).first().off( "change" );
                $modalRoot.find( '[data-id="input-workshift-pause-hour"]' ).first().off( "change" );

                $modalRoot.find( '[data-id="input-workshift-hourly-rate"],[data-id="input-workshift-gross-hour"],[data-id="input-workshift-pause-hour"]' ).on( "change", function()
                {
                    let newNetValue = parseFloat( $modalRoot.find( '[data-id="input-workshift-gross-hour"]' ).first().val() ) -
                                      parseFloat( $modalRoot.find( '[data-id="input-workshift-pause-hour"]' ).first().val() );

                    const workshiftHourlyRate  = parseFloat( $modalRoot.find( '[data-id="input-workshift-hourly-rate"]' ).first().val() );

                    $modalRoot.find( '[data-id="input-workshift-net-hour"]' ).first().val( newNetValue .toFixed( 2 ));
                    $modalRoot.find( '[data-id="input-workshift-wage"]' ).first().val( ( newNetValue * workshiftHourlyRate ).toFixed( 2 ) );
                });

                $modalRoot.find( '[data-id="btnSaveWorkshift"]' ).first().off( "click" );
                $modalRoot.find( '[data-id="btnSaveWorkshift"]' ).first().click( function()
                {
                    $(this).off( "click" );

                    $modalRoot.find( '[data-id="section-workshift-form"]' ).first().hide();
                    $modalRoot.find( '[data-id="section-loader"]' ).first().show();

                    app.rpc.call(
                        'Special',
                        'updateWorkshift',
                        {
                            groupId : app.user.activeGroupId,
                            appointmentId : appointmentId,
                            profileId : employeeId,
                            hourlyRate : parseFloat( $modalRoot.find( '[data-id="input-workshift-hourly-rate"]' ).first().val() ),
                            grossHour : parseFloat( $modalRoot.find( '[data-id="input-workshift-gross-hour"]' ).first().val() ),
                            pauseHour : parseFloat( $modalRoot.find( '[data-id="input-workshift-pause-hour"]' ).first().val() ),
                            netHour : parseFloat( $modalRoot.find( '[data-id="input-workshift-net-hour"]' ).first().val() ),
                            additionalPay : parseFloat($modalRoot.find( '[data-id="input-workshift-additional-pay"]' ).first().val() ),
                            notice : $modalRoot.find( '[data-id="input-workshift-notice"]' ).first().val()
                        },
                        function( resp )
                        {
                            if ( resp && resp.hasOwnProperty( 'code' ) && resp.code == 200 )
                            {
                                app.UI.toastSuccess( 'Daten erfolgreich aktualisiert' );

                                if ( resp.hasOwnProperty( 'data' ) && resp.data.hasOwnProperty( 'workshift' ) )
                                {
                                    let total = ( parseFloat( resp.data.workshift.hourly_rate ) * parseFloat(resp.data.workshift.net_hour ) ) + parseFloat( resp.data.workshift.additional_pay );

                                    oldRowData[ 4 ] = self.nf( parseFloat( resp.data.workshift.hourly_rate ), 2 );
                                    oldRowData[ 5 ] = self.nf( parseFloat( resp.data.workshift.gross_hour ), 2 );
                                    oldRowData[ 6 ] = self.nf( parseFloat(resp.data.workshift.pause_hour ), 2 );
                                    oldRowData[ 7 ] = self.nf( parseFloat(resp.data.workshift.net_hour ), 2 );
                                    oldRowData[ 8 ] = self.nf( parseFloat(resp.data.workshift.net_hour)  * parseFloat( resp.data.workshift.hourly_rate ), 2 );
                                    oldRowData[ 9 ] = self.nf( parseFloat( resp.data.workshift.additional_pay ), 2 );
                                    oldRowData[ 10 ] = self.nf( total, 2 );
                                    oldRowData[ 11 ] = resp.data.workshift.notice;

                                    $container.find( '[data-notice-cell-id="ws-' + appointmentId + '-' + employeeId + '"]' ).first().attr( 'title', resp.data.workshift.notice ? resp.data.workshift.notice : '' );
                                    workshift.hourly_rate =  parseFloat( resp.data.workshift.hourly_rate );
                                    workshift.gross_hour = parseFloat( resp.data.workshift.gross_hour );
                                    workshift.pause_hour = parseFloat( resp.data.workshift.pause_hour );
                                    workshift.net_hour = parseFloat( resp.data.workshift.net_hour );
                                    workshift.additional_pay = parseFloat( resp.data.workshift.additional_pay );
                                    workshift.notice = resp.data.workshift.notice;

                                    workshiftRow.data( oldRowData ).draw();

                                }
                            }
                            else
                            {
                                app.UI.toastError();
                            }

                            $modalRoot.modal( 'hide' );
                        }
                    );
                });
            });
            $modalRoot.on( 'hidden.bs.modal', function()
            {
                $modalRoot.modal( 'dispose' );
            });
            $modalRoot.modal( 'show' );

        });

        dTable = $( this.container ).find( '.datatable' ).DataTable( {
            pageLength: 50,
            responsive: true,
            dom: '<"html5buttons"B>lTfgitp',
            language : {
                search      : 'Suche',
                emptyTable  : 'Keine Einträge vorhanden.',
                zeroRecords : 'Keine Einträge vorhanden.',
                info        : 'Zeige _START_ bis _END_ von _TOTAL_ Einträgen',
                lengthMenu : 'Zeige _MENU_ Einträge',
                paginate : {
                    first : 'Erste',
                    previous : 'Vorherige',
                    next : 'Nächste',
                    last : 'Letzte'
                },
            },
            buttons: [
                { extend: 'copy'},
                {extend: 'csv'},
                {
                    extend: 'excel',
                    title: 'Stundenverrechnung',
                    exportOptions: {
                        format : {
                            body : function ( data, row, column, node )
                            {
                                if ( typeof data !== 'undefined' )
                                {
                                    if ( data != null )
                                    {
                                        if ( column === 3 || column === 4 || column === 5 || column === 6 || column === 7 || column === 8 || column === 9 )
                                        {
                                            data = data.toString().replace( ',', '.' );
                                        }
                                    }
                                }
                                return data;
                            }
                        }
                    }
                },
                {
                    extend: 'pdf',
                    title: 'Stundenverrechnung',
                    orientation : 'landscape'
                },
                {
                    extend: 'print',
                    customize: function (win){
                        $(win.document.body).addClass('white-bg');
                        $(win.document.body).css('font-size', '10px');

                        $(win.document.body).find('table')
                            .addClass('compact')
                            .css('font-size', 'inherit');
                    }
                }
            ]

        });
    },

    destroy : function()
    {

    }
};

export { HourAllocationDataTable };