$(document).ready(function(){
    
            
    // Выбор дат для Stat http://t1m0n.name/air-datepicker/docs/index-ru.html
    var
        nowDate = new Date(),
        isChangePeriod = false,
        $dateFrom = $('#date-value-1'),
        $dateTo = $('#date-value-2'),
        $periodSelect = $('.form-control.stat-period'),
        isStartDatesSelected = false,
        datepicker1 = $dateFrom.datepicker({
            dateFormat: "yyyy-mm-dd",
            autoClose: true,
            maxDate: nowDate,
            onSelect: function(fd, d, picker) {
                if (isStartDatesSelected) {
                    datepicker2.update('minDate', d);
                    if (!isChangePeriod) {
                        setPeriodSelectEmpty();
                        requestDataPeriod();
                    }
                }
            },
        }).data('datepicker'),
        datepicker2 = $dateTo.datepicker({
            dateFormat: "yyyy-mm-dd",
            autoClose: true,
            maxDate: nowDate,
            onSelect: function(fd, d, picker) {
                if (isStartDatesSelected) {
                    datepicker1.update('maxDate', d);
                    if (!isChangePeriod) {
                        setPeriodSelectEmpty();
                        requestDataPeriod();
                    }
                }
            },
        }).data('datepicker'),
        $chartStat = $('#chart-graph-stat'),
        $chartTable = $('#table-stat'),
        $loading = $('.b-feeds-stat_data-loading'),
        $chartStatInfo = $('.chart-graph-stat-info'),
        $chartStatError = $('.chart-graph-stat-error'),
        $chartStatErrorMessage = $('.chart-graph-stat-error .message'),
        periodStatsData,
        //campaignStatsData,
        $exportExcelButton = $("#btnExport"),
        dataLineChartStat;
    
    
    // Установка стартовых значений дат:
    if ($('.b-feeds-stat_controls').length) {
        datepicker1.selectDate(new Date($dateFrom.val()));
        datepicker2.selectDate(new Date($dateTo.val()));
    }
    isStartDatesSelected = true;
    
    
    // Получение данных для отрисовки графика Stat при старте:
    if ($('#period-stats').val()) {
        periodStatsData = JSON.parse($('#period-stats').val());
    }
    /*
    if ($('#campaign-stats').val()) {
        campaignStatsData = JSON.parse($('#campaign-stats').val());
    }
    */
    // Устанавливаем данные по периоду в качестве стартовых:
    dataLineChartStat = periodStatsData;
    //console.log('AAA dataLineChartStat = ', dataLineChartStat);
    if (!dataLineChartStat) {
        ShowInfo();
    } else {
        // Отрисовка графика и таблицы по стартовым данным:
        if (dataLineChartStat.status == 'Error') {
            ShowError();
        } else {
            renderLineChart();
            renderHourTable();
        }
    }
    
    
    // Смена периода:
    $periodSelect.on('change', function(){
        var
            period = $(this).val(),
            fromDay,
            toDay;
            
        // Установка значений периода в дате:
        switch(period) {
            case 'today':
                fromDay = nowDate;
                toDay = nowDate;
            toDay;
            break;
            case 'yesterday':
                var yesterdayDate = new Date();
                yesterdayDate.setDate(yesterdayDate.getDate()-1);
                fromDay = yesterdayDate;
                toDay = yesterdayDate;
            break;
            case '7days':
                var prev7day = new Date();
                prev7day.setDate(prev7day.getDate()-7);
                fromDay = prev7day;
                toDay = nowDate;
            break;
            case '30days':
                var prev30day = new Date();
                prev30day.setDate(prev30day.getDate()-30);
                fromDay = prev30day;
                toDay = nowDate;
            break;
            case 'current_month':
                var firstDay = new Date(nowDate.getFullYear(), nowDate.getMonth(), 1);
                fromDay = firstDay;
                toDay = nowDate;
            break;
            case 'prev_month':
                var firstDay = new Date(nowDate.getFullYear(), nowDate.getMonth()-1, 1);
                var lastDay = new Date(nowDate.getFullYear(), nowDate.getMonth(), 0);
                fromDay = firstDay;
                toDay = lastDay;
            break;
            case 'year':
                var firstDay = new Date(nowDate.getFullYear(), 0, 1);
                fromDay = firstDay;
                toDay = nowDate;
            break;
            default:
                //datepicker1.clear();
                //datepicker2.clear();
            break;
        }
        
        isChangePeriod = true;
        datepicker1.selectDate(fromDay);
        datepicker2.selectDate(toDay);
        isChangePeriod = false;
        
        requestDataPeriod();
    });
    
    // Сортировка по колонкам внутри таблицы:
    var $tableHeadCols = $('#table-line thead.metric.sortable th b');
    $tableHeadCols.on('click', function(){
        var
            $this = $(this);
        
        if ($this.hasClass('not-sorted')) {
            return false;
        }
        
        $tableHeadCols.removeClass('selected');
        $this.addClass('selected').toggleClass('desc');

        /*
        if ($this.hasClass('main-cat')) {
            dataLineChartStat = ($this.hasClass('date')) ? periodStatsData : campaignStatsData;
            $tableHeadColsChecks.attr("disabled", $this.hasClass('campaign'));
        }
        */
        renderHourTable();
    });
    
    // Клик на checkbox в названии поля таблицы:
    var $tableHeadColsChecks = $('#table-line thead.metric.sortable th input[type="checkbox"]');
    $tableHeadColsChecks.on('change', function(){
        renderLineChart();
    });
    
    // Отрисовка графика:
    function renderLineChart()
    {
        if(dataLineChartStat && $chartStat.length>0) {
            $.ChartStat.DateStat(dataLineChartStat);
            return false;
        }
    }
    
    // Отрисовка таблицы:
    function renderHourTable()
    {
        if(dataLineChartStat) {
            $.TableStat.Render(dataLineChartStat);
            $chartTable.show();
        } else {
            $chartTable.hide();
        }     
    }
    
    // Запрос данных за временной период:
    function requestDataPeriod()
    {
        var dataRequest = {period: [$dateFrom.val(),$dateTo.val()]};
        EnableLoadingState(true);
        
        $.ajax({
            url: $periodSelect.attr('data-link'),
            method: 'POST',
            data: dataRequest,
            success: function(res) {
                EnableLoadingState(false);
                if (res == null) {
                    console.log("AAA requestDataStat success res: NULL");
                    ShowInfo();
                } else if (res.status == 'Error') {
                    console.log("AAA requestDataStat error");
                    ShowError();
                } else {
                    //console.log("AAA requestDataStat SUCCESS res: ", res);
                    ShowChartData();
                    
                    //periodStatsData = res.period;
                    //campaignStatsData = res.campaign; 
                    periodStatsData = res;
                    dataLineChartStat = periodStatsData;
                    
                    //$('.main-cat').addClass('selected');
                    renderLineChart();
                    renderHourTable();
                    
                    $.TableStat.OrdersStatusReCalc();
                }
            },
            error: function (e) {
                console.log('error: ', e);
                EnableLoadingState(false);
            }
        });
    }
    
    function setPeriodSelectEmpty()
    {
        $periodSelect.val('');
    }
    
    function setPeriodSelectEmpty()
    {
        $periodSelect.val('');
    }
    
    function EnableLoadingState(isLoading)
    {
        if (isLoading) {
            $loading.show();
        } else {
            $loading.hide();
        }
    }
    
    function ShowInfo()
    {
        $chartStatInfo.show();
        $chartStatError.hide();
        $chartStat.hide();
        $chartTable.hide();
    }
    
    function ShowError()
    {
        $chartStatError.show();
        $chartStatInfo.hide();
        $chartStat.hide();
        $chartTable.hide();
    }
    
    function ShowChartData()
    {
        $chartStatInfo.hide();
        $chartStatError.hide();
        $chartStat.show();
        $chartTable.show();
    }
    
    // Выгрузка таблицы в Excel
    $exportExcelButton.click(function(){
        
        var
            $tableToExcel = $("#table2excel"),
            $tableToExcelCopy = $tableToExcel.clone(),
            activeStatus = $('.b-filter__switch.category-orders .b-filter__switch-item.m-filter__switch-item_active').data('order-category');
        
        if (activeStatus == 'all') {
            $('thead tr.orders-title.confirmed, thead tr.orders-title.rejected', $tableToExcelCopy).remove();
            $('tbody tr.total-orders', $tableToExcelCopy).remove();
            
            // Добавляем сколонку статуса:
            $('thead tr th.Timestamp', $tableToExcelCopy).after('<th><b>Статус</b></th>');
            $('tbody tr.order-item', $tableToExcelCopy).each(function(){
                var
                    $this = $(this),
                    orderStatusTitle;
                    
                if ($this.hasClass('confirmed')) orderStatusTitle = 'Подтверждён';
                if ($this.hasClass('rejected')) orderStatusTitle = 'Отклонён';
                
                $('td.Timestamp', $this).after('<td>' + orderStatusTitle + '</td>');
            });
            $('tbody tr.total-all td.count', $tableToExcelCopy).after('<td></td>');
        }
        if (activeStatus == 'confirmed') {
            $('thead tr.orders-title.all, thead tr.orders-title.rejected', $tableToExcelCopy).remove();
            $('tbody tr.rejected', $tableToExcelCopy).remove();
            $('tbody tr.total-all, tbody tr.total-orders.approved, tbody tr.total-orders.rejected', $tableToExcelCopy).remove();
        }
        if (activeStatus == 'rejected') {
            $('thead tr.orders-title.all, thead tr.orders-title.confirmed', $tableToExcelCopy).remove();
            $('tbody tr.confirmed', $tableToExcelCopy).remove();
            $('tbody tr.total-all, tbody tr.total-orders.approved, tbody tr.total-orders.confirmed', $tableToExcelCopy).remove();
        }
        
        $tableToExcelCopy.table2excel({
            exclude: ".noExl",
            name: "Worksheet Name",
            filename: $tableToExcelCopy.data('content') + '.xls'
        });
    });
    
    // Обработка контролов для таблицы transactions:
    (function(){
        
        var
            $tableStat = $('table.transactions'),
            $ordersSwitcher = $('.b-filter__switch.category-orders .b-filter__switch-item'),
            switcherActiveClass = 'm-filter__switch-item_active';
        
        OrdersStatusReCalc();
        
        // Переключение статусов заказов в таблице:
        $ordersSwitcher.on('click', function() {
            var $this = $(this);
            
            if (!$this.hasClass(switcherActiveClass)) {
                $ordersSwitcher.removeClass(switcherActiveClass);
                $this.addClass(switcherActiveClass);
                $tableStat.removeClass('all').removeClass('approved').removeClass('confirmed').removeClass('rejected');
                $tableStat.addClass($this.data('order-category'));
            }
        });
        
        var
            $popupBg = $('.l-popup'),
            $popup = $('.b-popup__window.order-regected-comment', $popupBg),
            $popupContent = $('.b-popup-content', $popup),
            $popupClose = $('.button-close', $popup),
            $popupApply = $('button.apply', $popup),
            $popupCancel = $('button.cancel', $popup),
            $popupComment = $('.b-popup-comment', $popup);
        
        // Закрыввем попап по клику на Х:
	$popupClose.on('click', function(){
            ClosePopup();
	});
        $popupCancel.on('click', function(){
            ClosePopup();
	});
	// Закрыввем попап по клику извне:
	$popup.on('click', function(event){
            event.stopPropagation();
	});
	$popupBg.on('click', function(){
            ClosePopup();
	});
        
        function ShowPopup(dataPopup)
	{
            $popupBg.addClass('open-popup');
            $popup.show();
            $popupContent.attr("data-feed-id", dataPopup.feedId);
            $popupContent.attr("data-order-id", dataPopup.orderId);
	}
	
	function ClosePopup(isApply = false)
	{
            $popupBg.removeClass('open-popup');
            $popup.hide();
            var
                feedIdValue = $popupContent.attr("data-feed-id"),
                orderIdValue = $popupContent.attr("data-order-id");
            
            $popupContent.attr("data-feed-id", null);
            $popupContent.attr("data-order-id", null);
            $popupComment.val('');
            if (!isApply) {
                var $orderInput = $('tbody tr.transaction-item td.status span[data-feed-id="' + feedIdValue + '"][data-order-id="' + orderIdValue + '"] input', $tableStat);
                $orderInput.prop("checked", true);
            }
            $popupApply.off('click');
	}
        
        // Клик на галочку подтверждения заказа:
        $tableStat.on('change', 'td.status input', function(e) {

            var
                $this = $(this),
                $spanWrap = $this.parent('span.order-id'),
                action = $tableStat.data('link'),
                $orderTr = $this.parents('tr'),
                data = {
                    'toggle_confirmed': 1,
                    'confirmed': $this.prop( "checked" ) ? 1 : 0,
                    'feedId': $spanWrap.data('feed-id'),
                    'orderId': $spanWrap.data('order-id'),
                },
                $tableToExcel = $("#table2excel"),
                $orderTrExcel = $('tbody tr.order-item[data-feed-id="' + $spanWrap.data('feed-id') + '"][data-order-id="' + $spanWrap.data('order-id') + '"]', $tableToExcel);

            
            // Popup с комментарием к отклонению заказа:
            if (!data.confirmed) {
                var dataPopup = {
                    'feedId': $spanWrap.data('feed-id'),
                    'orderId': $spanWrap.data('order-id'),
                }
                ShowPopup(dataPopup);
                $popupApply.on('click', function(){
                    data.comment = $popupComment.val();
                    RequestChangeConfirmed($this, action, data, $orderTr, $orderTrExcel);
                    ClosePopup(true);
                });
            } else {
                /*
                $this.prop("disabled", true);
                $.ajax(action, {
                    type: 'POST',
                    data: data,
                    success: function(data) {
                        console.log('AAA success ', data);
                        if (data.result) {
                            $orderTr.removeClass('confirmed').removeClass('rejected');
                            $orderTr.addClass((data.confirmed) ? 'confirmed' : 'rejected');

                            $orderTrExcel.removeClass('confirmed').removeClass('rejected');
                            $orderTrExcel.addClass((data.confirmed) ? 'confirmed' : 'rejected');

                        } else {
                            $this.prop("checked", !$this.prop( "checked" ))
                        }
                        $this.prop("disabled", false);
                        OrdersStatusReCalc();
                    },
                    error: function(rew, status, err) {
                        console.log(status, err);
                        $this.prop("disabled", false);
                    }
                });
                */
                RequestChangeConfirmed($this, action, data, $orderTr, $orderTrExcel);
            }
            return false;
        });
        
        function RequestChangeConfirmed($this, action, data, $orderTr, $orderTrExcel) {
            $this.prop("disabled", true);
            $.ajax(action, {
                type: 'POST',
                data: data,
                success: function(data) {
                    console.log('AAA success ', data);
                    if (data.result) {
                        $orderTr.removeClass('confirmed').removeClass('rejected');
                        $orderTr.addClass((data.confirmed) ? 'confirmed' : 'rejected');

                        $orderTrExcel.removeClass('confirmed').removeClass('rejected');
                        $orderTrExcel.addClass((data.confirmed) ? 'confirmed' : 'rejected');

                    } else {
                        $this.prop("checked", !$this.prop( "checked" ));
                    }
                    $this.prop("disabled", false);
                    OrdersStatusReCalc();
                },
                error: function(rew, status, err) {
                    console.log(status, err);
                    $this.prop("checked", !$this.prop( "checked" ));
                    $this.prop("disabled", false);
                }
            });
        }

        // Клик на Утвердить заказы:
        /*
        $('a.btn.approve').on('click', function(){
            
            if (!confirm("Утвердить заказы за выбранный период?")) return false;

            var
                action = $tableStat.data('link'),
                $ordersItems = $('tbody > tr.transaction-item:not(.total-orders) td.OrderID span.order-id', $tableStat),
                dataOrders = [],
                data = {
                'approved': 1,
                    'orders': dataOrders,
                };

            $ordersItems.each(function(){
                var
                    $this = $(this),
                    dataItem = {
                        feedId: $this.data('feed-id'),
                        orderId: $this.data('order-id'),
                        confirmed: ($('input', $this).prop('checked')) ? 1 : 0,
                        approved: 1
                    };
                dataOrders.push(dataItem);
            });

            $.ajax(action, {
                type: 'POST',
                data: data,
                success: function(data) {
                    console.log(status, data);
                    if (data.result) {
                        dataOrders.forEach(function(item, i){
                            var
                                $inputItem = $('tbody td.OrderID span.order-id[data-order-id="' + item.orderId + '"][data-feed-id="' + item.feedId + '"] input', $tableStat),
                                $orderTr = $inputItem.parents('tr');
                            
                            $inputItem.prop("disabled", true);
                            $orderTr.removeClass('confirmed').removeClass('rejected').addClass('approved');
                        });
                        OrdersStatusReCalc();
                    }
                },
                error: function(rew, status, err) {
                    console.log(status, err);
                }
            });
            
            return false;
        });
        */
        
        // Пересчет кол-ва заказов по группам
        function OrdersStatusReCalc()
        {
            $.TableStat.OrdersStatusReCalc();
        }
        
    })();
    
    
});