(function () {

    const SUBSTAT_TYPE_HOUR = 'hours';
    const SUBSTAT_TYPE_OS_VERSION = 'versions';
    const SUBSTAT_TYPE_DEVICE_MODEL = 'model';
    const CSS_CLASS_SORT_ASC = 'headerSortDown';
    const CSS_CLASS_SORT_DESC = 'headerSortUp';

    var uri = new URI();

    var Page = function (i) {

        this._page = i;
    };
    Page.prototype.page = function () {

        return this._page;
    };
    Page.prototype.url = function () {

        return uri.removeSearch('page').addSearch('page', this.page()).toString();
    };

    // Statistic class
    var Stats = function () {

        this.params = {};
        this.refresh = function () {

            var currency = window.Cookie.get('stat_currency');
            currency = currency ? currency : $('a.switch_currency[data-default=1]').data('currency');
            currency = currency ? currency : $('a.switch_currency').first().data('currency');

            this.params = {
                'mode': $('input[name=mode]').val(),
                'date_from': $('input[name=date_from]').val(),
                'date_to': $('input[name=date_to]').val(),
                'period': $("select[name='period']").val(),
                'source': $("select[name='sources[]']").val(),
                'status': $("select[name='status[]']").val(),
                'offer': $("select[name^='offers']").val(),
                'subid1': $("select[name='sub[]']").val(),
                'subid2': $("select[name='sub2[]']").val(),
                'subid3': $("select[name='sub3[]']").val(),
                'subid4': $("select[name='sub4[]']").val(),
                'subid5': $("select[name='sub5[]']").val(),
                'subname': $("input[name=sub_name]").val(),
                'currency': currency,
                'browser': $("input[name=browser]").val(),
                'os': $("input[name=os]").val(),
                'country': $("input[name=country]").val() ? $("input[name=country]").val() : $("select[name='countries[]']").val(),
                'limit': parseInt($("input[name=per_page]").val()),
                'skip': 0,
                'page': parseInt($("input[name=page]").val()),
                'totalCount': null,
                'timezone': $("select[name=timezone]").val(),
                'smart_id': $("select[name='smart_id[]']").val(),
                'goal': $("select[name='goal[]']").length ? $("select[name='goal[]']").val() : null,
                'sort': $("input[name=sort]").val()
            };
            return this.params;
        };

        this.url = function () {

            return window.simpleTmpl('ajax-url')({}).trim();
        };

        this.href = function (params) {
            $.each(params, function(key, value) {
                if(typeof value === 'object') {
                    $.each(value, function(innerKey, innerValue) {
                        uri.removeSearch(key).addSearch(key + '[]', innerValue);
                    });
                } else {
                    uri.removeSearch(key).addSearch(key, value);
                }
            });
            return uri.toString();
        };

        this.pushUrl = function(params, force) {
            var title = $('title').text(),
                urlHref = force ? uri.search(params).toString() : this.href(params);
            history.pushState(title, title, urlHref);
        };

        this.subIdSearchUrl = function () {

            return window.simpleTmpl('ajax-subid-url')({}).trim();
        };

        this.ajaxLoader = function () {

            return window.simpleTmpl('ajax-loader')({});
        };

        this.loadStat = function (data) {

            return window.simpleTmpl('statistic-template').call(this, data);
        };

        this.loadStatRow = function (title, stat, total) {

            return window.simpleTmpl('statistic-template-row').call(this, {
                title: title,
                stat: stat,
                total: total ? total : false
            });
        };

        this.getSubParams = function (type, object) {

            var params = this.refresh();

            params.mode = type;
            switch (type) {
                case SUBSTAT_TYPE_HOUR:
                    params.date_from = params.date_to = $(object).data('date');
                    break;
                case SUBSTAT_TYPE_OS_VERSION:
                    params.os = $(object).data('os');
                    break;
                case SUBSTAT_TYPE_DEVICE_MODEL:
                    params.device = $(object).data('device');
                    break;
                default:
                    params.mode = null;
                    break;
            }
            return params;
        };

        this.getPagination = function () {

            uri = new URI();
            var data = [];
            if (this.params.totalCount > this.params.limit) {
                for (var i = 0; i < Math.floor(this.params.totalCount / this.params.limit) + (this.params.totalCount % this.params.limit > 0 ? 1 : 0); i++) {
                    data.push(new Page(i + 1));
                }
            }

            return data;
        };
    };

    Stats.prototype.getStats = function (callbacks) {

        var self = this;

        $.ajax({
            url: self.url(),
            data: {params: self.refresh()},
            type: 'GET',
            dataType: 'json',
            beforeSend: function () {
                $('div.wrapper-stats').html(self.ajaxLoader());
                if (callbacks && callbacks.beforeSend) {
                    callbacks.beforeSend();
                }
            },
            error: function () {
                $('div.wrapper-stats').html(window.Lang.get('trans.error_load_stats'));
            }
        }).done(function (data) {

            if (data.error) {
                $('div.wrapper-stats').html(data.error);
            } else {
                self.params.totalCount = data.total && data.total.totalCount ?
                    data.total.totalCount :
                    (data.totalCount ? data.totalCount : null)
                ;
                $('div.wrapper-stats').html(self.loadStat(data));
                self.sortable();

                if ($('#chart').length) {
                    var pad = function(str) { return '00'.substring(0, '00'.length - str.length) + str; };
                    var chartData = [];
                    for (var i in data.stats) {
                        var date = i;
                        if (data.stats[i].hasOwnProperty('info') && data.stats[i].info.hasOwnProperty('slice')) {
                            var slice = data.stats[i].info.slice;
                            date = slice.year + '-' + pad('' + slice.month) + '-' + pad('' + slice.day);
                        }
                        date = (new Date(date)).dateFormat();
                        chartData.push({
                            date: date,
                            hosts: data.stats[i].traffic.uniq,
                            leads: window['config']['affiliate']['use_only_approved'] ? data.stats[i].actions.confirmed.count : data.stats[i].actions.total.count,
                            revenue: window['config']['affiliate']['use_only_approved'] ? data.stats[i].actions.confirmed.revenue : data.stats[i].actions.total.revenue
                        });
                    }
                    self.initChart(chartData);
                } else if($("#dashboard_chart").length) {
                    $.getScript("/limitless/assets/js/plugins/visualization/echarts/echarts.js", function() {
                        require.config({
                            paths: {
                                echarts: '/limitless/assets/js/plugins/visualization/echarts'
                            }
                        });


                        // Configuration
                        // ------------------------------

                        require(
                            [
                                'echarts',
                                'echarts/theme/limitless',
                                'echarts/chart/bar',
                                'echarts/chart/line'
                            ],


                            // Charts setup
                            function (ec, limitless) {

                                var stacked_lines = ec.init(document.getElementById('dashboard_chart'), limitless);

                                var stacked_lines_options = {

                                    // Setup grid
                                    grid: {
                                        x: 55,
                                        x2: 45,
                                        y: 35,
                                        y2: 25
                                    },

                                    // Add tooltip
                                    tooltip: {
                                        trigger: 'axis'
                                    },

                                    // Add legend
                                    legend: {
                                        data: ['Conversions', 'Hosts', 'Revenue']
                                    },

                                    // Enable drag recalculate
                                    calculable: false,

                                    // Hirozontal axis
                                    xAxis: [{
                                        type: 'category',
                                        boundaryGap: false,
                                        axisLine: {
                                            onZero: false
                                        },
                                        data: []
                                    }],

                                    // Vertical axis
                                    yAxis: [
                                        {
                                            name: 'Conversions & Clicks',
                                            type: 'value'
                                        },
                                        {
                                            name: 'Revenue',
                                            type: 'value'
                                        }
                                    ],

                                    // Add series
                                    series: [
                                        {
                                            name: 'Hosts',
                                            type: 'line',
                                            stack: 'Hosts',
                                            itemStyle: {normal: {areaStyle: {type: 'default'}}},
                                            yAxisIndex: 0,
                                            data: []
                                        },
                                        {
                                            name: 'Conversions',
                                            type: 'line',
                                            stack: 'Conversions',
                                            itemStyle: {normal: {areaStyle: {type: 'default'}}},
                                            yAxisIndex: 0,
                                            data: []
                                        },
                                        {
                                            name: 'Revenue',
                                            type: 'line',
                                            stack: 'Revenue',
                                            itemStyle: {normal: {areaStyle: {type: 'default'}}},
                                            yAxisIndex: 1,
                                            data: []
                                        },
                                    ]
                                };

                                var pad = function(str) { return '00'.substring(0, '00'.length - str.length) + str; };
                                var dates = {};
                                var keys = [];
                                for (var i in data.stats) {
                                    var date = i;
                                    if (data.stats[i].hasOwnProperty('info') && data.stats[i].info.hasOwnProperty('slice')) {
                                        var slice = data.stats[i].info.slice;
                                        date = slice.year + '-' + pad('' + slice.month) + '-' + pad('' + slice.day);
                                    }
                                    date = (new Date(date)).dateFormat();
                                    keys.push(date);
                                    dates[date] = {
                                        u: data.stats[i].traffic.uniq,
                                        a: window['config']['affiliate']['use_only_approved'] ? data.stats[i].actions.confirmed.count : data.stats[i].actions.total.count,
                                        r: window['config']['affiliate']['use_only_approved'] ? data.stats[i].actions.confirmed.revenue : data.stats[i].actions.total.revenue
                                    };
                                }
                                keys.sort();
                                for (var i = 0; i < keys.length; i++) {
                                    stacked_lines_options.xAxis[0].data.push(keys[i]);
                                    stacked_lines_options.series[0].data.push(dates[keys[i]].u);
                                    stacked_lines_options.series[1].data.push(dates[keys[i]].a);
                                    stacked_lines_options.series[2].data.push(dates[keys[i]].r);
                                }

                                stacked_lines.setOption(stacked_lines_options);

                                window.onresize = function () {
                                    setTimeout(function () {
                                        stacked_lines.resize();
                                    }, 200);
                                }
                            }
                        );
                    });
                }

                if (callbacks && callbacks.success) {
                    callbacks.success(data);
                }
            }
        });
    };

    Stats.prototype.objGetListOffers = {
        ajax: {
            url: "/publisher/stats/ajax/offer/liveall",
			type: 'POST',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    'query': params.term,
                    'length': 100
                };
            },
            processResults: function (data, page) {
				
                if (data.length) {
                    var out = [];
                    $.each(data, function (i, item) {
				//		data[i].title;
                        item.intId = item.offer_id;
                        item.id = item.offer_id;
                        item.title = item.title;
                        out.push(item);
						
                    });
					
                    return {
                        results: out
                    };
                }
                return {
                    results: []
                };
            },
            cache: true
        },
        minimumInputLength: 1,
        templateResult: formatOffer,
        templateSelection: formatOfferSelection,
        escapeMarkup: function (markup) {
			
            return markup;
        } // let our custom formatter work
    };


    Stats.prototype.subStat = function (type) {

        var self = this;

        return function () {

            var $link = $(this);
            var $row = $link.closest('tr');
            if ($row.next().is('tr.tr-sub')) {
                $row.nextAll('tr.tr-sub').remove();
                self.sortable();
                return;
            }
            $.ajax({
                url: self.url(),
                data: {params: self.getSubParams(type, $link)},
                type: 'GET',
                dataType: 'json',
                beforeSend: function () {
                    $link.after(self.ajaxLoader());
                },
                error: function () {
                    $row.after(self.loadStatRow(window.Lang.get('trans.error_load_stats'), null, false));
                    $link.next().remove();
                }
            }).done(function (data) {

                if (data.error) {
                    $row.after(self.loadStatRow(data.error, null, false));
                } else {
                    for (var i in data.stats) {
                        $row.after(self.loadStatRow(i, data.stats[i]));
                        $row = $row.next();
                    }
                    self.sortable();
                }
                $link.next().remove();

            });
        };
    };

    Stats.prototype.setCurrency = function () {

        $('a.switch_currency').parent().find('span').removeClass('label-info');
        $('a.switch_currency[data-currency=' + this.params.currency + ']').find('span').addClass('label-info');
    };

    Stats.prototype.switchCurrency = function () {

        var self = this;
        return function () {
            var currency = $(this).data('currency');
            window.Cookie.set('stat_currency', currency);

            self.getStats();
            self.setCurrency();
        };
    };

    Stats.prototype.initChart = function (dataProvider) {

        var initChartData = function () {
            chart.dataProvider = dataProvider;
            chart.validateData();
        };

        if (AmCharts.isReady) {
            initChartData()
        } else {
            AmCharts.ready(initChartData);
        }
    };

    Stats.prototype.subIdSelect = function () {

        return {
            ajax: {
                url: 'ajax/offer/sub',
                dataType: 'json',
				type: 'POST',
                delay: 250,
                data: function (params) {
                    return {
                        q: params.term, // search term
                        page: params.page,
                        table: this.table || $(this).data("ajax--table")
                    };
                },
                processResults: function (data, page) {
                    return {
						
                        results: data
                    };
                },
                cache: true
            },
            minimumInputLength: 1,
            templateResult: function (item) {
                return item.id ? item.id : null;
            },
            templateSelection: function (item) {
                return item.id ? item.id : item.text;
            },
            escapeMarkup: function (markup) {
                return markup;
            } // let our custom formatter work
        };
    };

    Stats.prototype.sortable = function (refresh) {
        var self = this;

        $("div.wrapper-stats").on('mouseover', 'table.table-stats tbody td', function () {
            var el = $(this),
                pos = el.index();
            el.parent().find("th, td").addClass("td-hover");
            $("div.wrapper-stats table tr.main_table td").filter(":nth-child(" + (pos + 1) + ")").addClass("td-hover");

            el.addClass('td-hover-center');

        }).on('mouseout', 'table.table-stats tbody td', function () {
            $("div.wrapper-stats table tr.main_table td").removeClass('td-hover').removeClass('td-hover-center');
        });

        if (['offers', 'smartlinks', 'city', 'subs'].indexOf(this.params.mode) >= 0 && !refresh) {
            var $sortColumns = $("table.tablesorter").find('th[data-sort]');
            $sortColumns.on('click', function(e) {
                e.preventDefault();
                var $objLink = $(this),
                    activeClass = '',
                    sort = $objLink.data('sort'),
                    field = sort;

                if ($objLink.hasClass(CSS_CLASS_SORT_DESC)) {
                    activeClass = CSS_CLASS_SORT_ASC;
                } else {
                    activeClass = CSS_CLASS_SORT_DESC;

                    if (field.indexOf(',') > -1) {
                        var fieldSplit = field.split(','),
                            newField = [];
                        for (var k in fieldSplit) {
                            newField.push('-' + fieldSplit[k]);
                        }
                        field = newField.join(",");
                    } else {
                        field = '-' + field;
                    }
                }

                $("input[name=sort]").val(field);
                self.pushUrl({'sort': field});
                self.getStats({
                    success: function() {
                        $('[data-sort]').removeClass(CSS_CLASS_SORT_ASC).removeClass(CSS_CLASS_SORT_DESC);
                        $('[data-sort='+ sort + ']').addClass(activeClass);
                        self.sortable(true);
                    }
                });
            });
        }

        var obj = $("table.tablesorter");
        var c = 0;
        var $thByTrLevel = [];
        var lvl = 0;
        var skipInLevels = [];
        var maxThChild = null;
        var myHeaders = {};
        var parseThForSort = function($th, level) {
            if(!level) {
                level = 0;
            }
            if (!skipInLevels[level]) {
                skipInLevels[level] = 0;
            }
            for(var k in $th[level]) {
                if (skipInLevels[level] > k) {
                    continue;
                }
                if ((maxThChild === null || maxThChild <= 0) && level !== 0) {
                    maxThChild = null;
                    return;
                } else if (maxThChild !== null) {
                    maxThChild--;
                }
                skipInLevels[level]++;
                var $this = $th[level][k],
                    colspan = $this.attr('colspan');
                if (colspan && colspan > 1) {
                    if (maxThChild === null) {
                        console.log('colspan', colspan, (level + 1));
                        maxThChild = colspan;
                    }
                    parseThForSort($th, (level + 1));
                    continue;
                }
                if ($this.hasClass('nosort') || $this.attr('data-sort')) {
                    myHeaders[c] = {sorter: false};
                } else if ($this.hasClass('text-sorter')) {
                    myHeaders[c] = {sorter: 'text'};
                } else if ($this.hasClass('attribute-sorter')) {
                    myHeaders[c] = {sorter: 'sort-attr'};
                } else {
                    myHeaders[c] = {sorter: 'money'};
                }

                if(!$this.attr('data-sort')) {
                    $this.off('click');
                }

                $this.attr('data-custom-sort', c);
                c++;
            }
        };
        obj.find('thead tr').each(function() {
            var $tr = $(this);
            $tr.find('th').each(function() {
                var $this = $(this);
                if (!$thByTrLevel[lvl]) {
                    $thByTrLevel[lvl] = [$this];
                } else {
                    $thByTrLevel[lvl].push($this);
                }
            });
            lvl++;
        });
        parseThForSort($thByTrLevel);

        obj.tablesorter({
            headers: myHeaders, debug: true,
            textExtraction: function(node) {
                var cell_value = $(node).text();
                var sort_value = $(node).data('value');
                sort_value = typeof sort_value === "number" ? sort_value.toString() : sort_value;
                return (sort_value) ? sort_value : cell_value;
            }
        });

        if (refresh) {
            obj.trigger('update');
        }

        $("[data-toggle=popover]").popover({html: true});

    };

    $(document).ready(function () {

        var stat = new Stats();
        stat.getStats();
        stat.setCurrency();

        $('.switch_currency').on('click', stat.switchCurrency());

        $('div.wrapper-stats')
            .on('click', 'a.date_to_hour', stat.subStat(SUBSTAT_TYPE_HOUR))
            .on('click', 'a.date_to_versions', stat.subStat(SUBSTAT_TYPE_OS_VERSION))
            .on('click', 'a.device_to_model', stat.subStat(SUBSTAT_TYPE_DEVICE_MODEL))
        ;
        $("select.select2-ajax-sub").select2(stat.subIdSelect());
        $("select.select2-ajax-offers").select2(stat.objGetListOffers);

        // data range
        if($('#date-range').length > 0) {
            $('#date-range').dateRangePicker({
                startOfWeek: 'monday',
                format: 'DD-MM-YYYY',
                showShortcuts: true,
                language: 'en',
                hoveringTooltip: false,
                shortcuts: {
                    'prev-days': [3, 5, 7],
                    'prev': ['week', 'month', 'year'],
                    'next-days': null,
                    'next': null
                }
            }).bind('datepicker-change', function (event, obj) {
                $('input[name="date_from"]').val(moment(obj.date1).format("DD-MM-YYYY"));
                $('input[name="date_to"]').val(moment(obj.date2).format("DD-MM-YYYY"));
            }).val($('input[name="date_from"]').val() + ' to ' + $('input[name="date_to"]').val());
        } else {
            $(".datepicker").datepicker({
                format: 'dd-mm-yyyy'
				
            });
        }




        $(".js-smartlink-filter").on("select2:select", function(e) {
            var $this = $(this);

            var isSingleChoose = $(".js-smartlink-filter").find("option[value=" + e.params.data.id + "]").closest(".js_single_choose").length;
            if(isSingleChoose) {
                $(".js-smartlink-filter option:not('option[value=" + e.params.data.id + "]')").prop("selected", false);
            } else {
                $(".js-smartlink-filter .js_single_choose option").prop("selected", false);
            }
            $this.trigger('change.select2');
        });


    });
})();

function formatOffer(item) {
    return item.title ? '(' + item.intId + ') ' + item.title : item.text ;
}

function formatOfferSelection(item) {
    return item.title ? '(' + item.intId + ') ' + item.title : item.text;
}
