$(document).ready(function(){

    var
        $table = $('#table-line'),
        $tableToExcel = $('#table2excel'),
        $tableContent = $('<tbody>'),
        $tableToExcelContent = $('<tbody>'),
        $tableBody = $table.find('tbody').first(),
        $tableToExcelBody = $tableToExcel.find('tbody').first(),
        activeLines = [],
        currentActiveLine,
        currencyFields = ['admoney', 'salemoney', 'usdollarmoney', 'localmoney', 'AdMoney', 'OrderSum', 'Price'],
        notFormatFields = ['Timestamp', 'Basket', 'ViewID'],
        dateTimeFields = ['Timestamp', 'period'],
        trClassConfirmed = 'confirmed',
        trClassRejected = 'rejected',
        trClassApproved = 'approved',
        ordersStatuses = ['approved', 'confirmed', 'rejected'];
        
    // Шаблон содержимого ячейки Basket
    var templateBasketContent = _.template('\n'+
    '       <div class="b-basket-content">   \n' +
    '       <table>   \n' +
    '           <tbody>   \n' +
    '           <% _.each(data, function(item) { %>   \n' +
    '               <tr>   \n' +
    '                   <td><a class="basket-link" href="<%=item.URL %>" target="_blank"><%=item.Title %></a></td>   \n' +
    '                   <td><span class="quantity"><%=item.Quantity %></span></td>   \n' +
    '                   <td><span class="price"><%=formatPrice(item.Price) %></span></td>   \n' +
    '               </tr>   \n' +
    '           <% }) %>  \n' +
    '           </tbody>   \n' +
    '       </table>   \n' +
    '       </div>  \n' +
    '');
    
    // Шаблон ячейки Время-Дата
    var templateTimestampContent = _.template('\n'+
    '           <b><%=data.time %></b><br />   \n' +
    '           <span><%=data.date %></span><br />   \n' +
    '');
    
    
    // Шаблон ячейки status
    var templateOrderStatusContent = _.template('\n'+
    '           <span class="order-id" data-order-id="<%=data.orderId %>" data-feed-id="<%=data.feedId %>">   \n' +
    '               <input type="checkbox" name="order-id" <%=data.confirmed %> <%=data.approved %>>   \n' +
    '           </span>   \n' +
    '');
    
    // Шаблон ячейки OrderID
    var templateOrderIDContent = _.template('\n'+
    '           <span class="order-id" data-order-id="<%=data.orderId %>" data-feed-id="<%=data.feedId %>">   \n' +
    '               <a class="orderid-link" href="orderid/<%=data.feedId %>/<%=data.orderId %>" target="_blank"><%=data.orderId %></a>   \n' +
    '           </span>   \n' +
    '');
    
    // Шаблон ячейки ViewID
    var templateViewIDContent = _.template('\n'+
    '           <a class="viewid-link" href="viewid/<%=data.feedId %>/<%=data.viewId %>" target="_blank"><%=data.viewId %></a>   \n' +
    '');
    
    
    function valueFormat(value)
    {
        var
            isCurrencyValue = currencyFields.indexOf(currentActiveLine) > -1,
            isNonFormatValue = notFormatFields.indexOf(currentActiveLine) > -1,
            format = d3.format(',.0f');
    
        if (currentActiveLine == 'AdMoney') format = d3.format(',.2f');
        if (currentActiveLine == 'ctr')     format = d3.format(',.2f');
        
        if (isCurrencyValue)            return format(value) + ' грн.';
        if (currentActiveLine == 'ctr') return format(value) + ' %';
        if (isNonFormatValue)           return value;
        
        return format(value);
    }
    
    function getDateValue(dataDate)
    {
        return dataDate.split(' ')[0];
    }
    
    function getHourMinValue(dataDate)
    {
        var
            timeVal = dataDate.split(' ')[1].split(':'),
            timeValCorrected = timeVal[0]+':'+timeVal[1];
        return timeValCorrected;
    }
    
    function RenderInterval(dataLineChartStat)
    {
        var
            dataTable = dataLineChartStat,
            dataPeriod = dataLineChartStat['period'],
            dataTableForSort = [],
            $selectedField = $('thead th b.selected', $table),
            sortField = false,
            isDesc = true;
        
        // Определение поля для сортировки строк в таблице:
        if ($selectedField.length > 0) {
            sortField = $selectedField.attr('id');
            isDesc = $selectedField.hasClass('desc');
        }
        if (!sortField) {
            switch(dataLineChartStat.report) {
                case 'common':
                    sortField = 'period';
                    isDesc = true;
                break;
                case 'transactions':
                    sortField = 'Timestamp';
                    isDesc = true;
                break;
                default:
                    sortField = 'period';
                    isDesc = true;
                break;
            }
        }
        //console.log('AAA sortField = ', sortField, '  isDesc = ', isDesc);
        
        // Подготовка данных для сортировки:
        dataPeriod.forEach(function(dataTableItem, ind){
            var dataTableSortItem = {};
            dataTableSortItem['period'] = dataTableItem;
            activeLines.forEach(function(activeLine){
                dataTableSortItem[activeLine] = dataTable[activeLine][ind];
            });
            dataTableForSort.push(dataTableSortItem);
        });
        
        // Сортировка данных для таблицы:
        dataTableForSort.sort(function(a,b){
            if (dateTimeFields.indexOf(sortField) > -1) {
                var
                    aT = new Date(a[sortField]),
                    bT = new Date(b[sortField]);

                return (isDesc) ? bT-aT : aT-bT;
            } else {
                return (isDesc) ? b[sortField]-a[sortField] : a[sortField]-b[sortField];
            }
        });

        // Отрисовка таблицы:
        dataTableForSort.forEach(function(item){
            
            if (dataLineChartStat.report == 'transactions') {
                
                var
                    feedId = item['period'][1],
                    orderId = item['period'][0],
                    ordersStatus = dataLineChartStat.ordersStatus,
                    orderStatus = (ordersStatus[feedId] && ordersStatus[feedId][orderId]) ? ordersStatus[feedId][orderId] : null,
                    trClass;
                
                if (!orderStatus) {
                    trClass = trClassConfirmed;
                } else {
                    if (orderStatus.approved) {
                        trClass = trClassApproved;
                    }
                    else if (!orderStatus.confirmed) {
                        trClass = trClassRejected;
                    }
                    else {
                        trClass = trClassConfirmed;
                    }
                }
                
                $row = $('<tr class="transaction-item ' + trClass + '">');
                $row.append($('<td class="status">').append(templateOrderStatusContent({
                    data: {
                        feedId: feedId,
                        orderId: orderId,
                        confirmed: (orderStatus && !orderStatus.confirmed) ? '' : 'checked',
                        approved: (orderStatus && orderStatus.approved) ? 'disabled' : '',
                    }
                })));
                $row.append($('<td class="OrderID">').append(templateOrderIDContent({
                    data: {
                        feedId: feedId,
                        orderId: orderId,
                    }
                })));
                
                $rowExcel = $('<tr class="order-item ' + trClass + '" data-feed-id="' + feedId + '" data-order-id="' + orderId + '">');
                $rowExcel.append($('<td>').html(item['period']));
                
            } else {
                $row = $('<tr>');
                $row.append($('<td>').html(item['period']));
            }
           
            activeLines.forEach(function(line){
                if (line == 'Basket') {
                    var dataBasket = item[line];
                    currentActiveLine = 'Price';
                    $row.append($('<td class="'+ line +'">').append(templateBasketContent({data: dataBasket, formatPrice: valueFormat})));
                } else if (line == 'Timestamp') {
                    $row.append($('<td class="'+ line +'">').append(templateTimestampContent({
                        data: {date: getDateValue(item[line]), time: getHourMinValue(item[line])}
                    })));
                    $rowExcel.append($('<td class="Timestamp">').append(item[line]));
                } else if (line == 'ViewID') {
                    $row.append($('<td class="'+ line +'">').append(templateViewIDContent({
                        data: {feedId: item['period'][1], viewId: item['ViewID']}
                    })));
                } else {
                    currentActiveLine = line;
                    $row.append($('<td class="'+ line +'">').html(valueFormat(item[line])));
                    if (dataLineChartStat.report == 'transactions') {
                        $rowExcel.append($('<td>').html(valueFormat(item[line])));
                    }
                }
            });
            $row.appendTo($tableContent);
            if (dataLineChartStat.report == 'transactions') {
                $rowExcel.appendTo($tableToExcelContent);
            }
        });
        
        // Добавляем строку "Итого" для отчета 'common':
        if (dataLineChartStat.report == 'common') {
        
            $row = $('<tr class="total">');
            $row.append($('<td>').html("Итого"));
            
            activeLines.forEach(function(item){
                currentActiveLine = item;
                var isNotSumValue = notFormatFields.indexOf(currentActiveLine) > -1;

                if (!isNotSumValue) {
                    var totalValue = 0;
                    
                    if (currentActiveLine == 'ctr') {
                        var totalViews = 0;
                        var totalClicks = 0;
                        for(var i = dataPeriod.length-1; i >= 0; i--) {
                            totalViews += dataTable['Views'][i];
                            totalClicks += dataTable['Clicks'][i];
                        }
                        totalValue = (totalViews != 0) ? (totalClicks/totalViews*100).toFixed(2) : 0;
                    } else {
                        for(var i = dataPeriod.length-1; i >= 0; i--) {
                            totalValue += dataTable[item][i];
                        }
                    }
                    
                } else {
                    totalValue = '';
                }

                $row.append($('<td>').html(valueFormat(totalValue)));
            });
            $row.appendTo($tableContent);
        }
        
        // Добавляем строку "Всего заказов" для отчета 'transactions':
        if (dataLineChartStat.report == 'transactions') {
        
            $row = $('<tr class="total-orders all">');
            $row.append($('<td>'));
            $row.append($('<td>').html("Всего заказов: " + dataPeriod.length));
            
            $rowExcel = $('<tr class="total-all">');
            $rowExcel.append($('<td class="count">').html("<b>Всего заказов: " + dataPeriod.length + '</b>'));
            
            activeLines.forEach(function(item){
                currentActiveLine = item;
                var isNotSumValue = notFormatFields.indexOf(currentActiveLine) > -1;

                if (!isNotSumValue) {
                    var totalValue = 0;
                    for(var i = dataPeriod.length-1; i >= 0; i--) {
                        totalValue += dataTable[item][i];
                    }
                } else {
                    totalValue = '';
                }

                $row.append($('<td class="'+ item +'">').html(valueFormat(totalValue)));
                
                if (['ViewID', 'Basket'].indexOf(currentActiveLine)<0) {
                    $rowExcel.append($('<td>').html('<b>' + valueFormat(totalValue) + '</b>'));
                }
            });
            $row.appendTo($tableContent);
            $rowExcel.appendTo($tableToExcelContent);
            
            // Добавляем total-строки для статусов заказов:
            ordersStatuses.forEach(function(item){
                $row = $('<tr class="total-orders ' + item + '">');
                $row.append($('<td>'));
                $row.append($('<td class="count">').html("Заказов: <span></span>"));
                
                $rowExcel = $('<tr class="total-orders ' + item + '">');
                $rowExcel.append($('<td class="count">').html("<b>Заказов: <span></span>"));
                
                activeLines.forEach(function(activeLine){
                    $row.append($('<td class="'+ activeLine +'">'));
                    if (['ViewID', 'Basket'].indexOf(activeLine)<0) {
                        $rowExcel.append($('<td class="'+ activeLine +'">'));
                    }
                });
                
                $row.appendTo($tableContent);
                $rowExcel.appendTo($tableToExcelContent);
            });
            
        }
        
    }
    
    $.extend({
        TableStat: {
            Render: function(dataLineChartStat) {
                //console.log('AAA TableStat render: ', dataLineChartStat);
                
                // Формируем список переключателей (категорий) activeLines:
                activeLines = [];
                $('thead.metric.sortable th b.cat', $table).each(function(){
                    activeLines.push($(this).attr('id'));
                });
                //console.log('AAA activeLines: ', activeLines);

                if (dataLineChartStat.type == 'interval') {
                    RenderInterval(dataLineChartStat);
                }

                if (dataLineChartStat.report == 'transactions') {
                    RenderInterval(dataLineChartStat);
                }

                $tableBody.html('').append($tableContent.children());
                $tableToExcelBody.html('').append($tableToExcelContent.children());
            },
            // Определяем список категорий, отмеченных галочками в таблице:
            CheckedCategories: function() {
                var listCats = [];
                $('thead.metric.sortable th input[type="checkbox"]', $table).each(function(){
                    if ($(this).is(":checked")) {
                        listCats.push($(this).data('field'));
                    }
                });
                return listCats;
            },
            // Пересчитываем кол-во заказов по статусам:
            OrdersStatusReCalc: function() {
                
                // Добавляем total-строки для статусов заказов:
                ordersStatuses.forEach(function(item){
                    var
                        $trStatus = $('tr.transaction-item.'+ item, $table),
                        $trTotalStatus = $('tr.total-orders.'+ item, $table),
                        $trTotalStatusToExcel = $('tr.total-orders.'+ item, $tableToExcel);
                    
                    $('td.count span', $trTotalStatus).html($trStatus.length);
                    $('td.count span', $trTotalStatusToExcel).html($trStatus.length);
                    
                    activeLines.forEach(function(activeLine){
                        currentActiveLine = activeLine;
                        var isNotSumValue = notFormatFields.indexOf(activeLine) > -1;
                        if (!isNotSumValue) {
                            var totalValue = 0;
                            $trStatus.each(function(){
                                var $this = $(this);
                                totalValue += parseFloat($('td.'+ activeLine, $this).html().replace(',',''));
                            });
                            $('td.'+ activeLine, $trTotalStatus).html(valueFormat(totalValue));
                            $('td.'+ activeLine, $trTotalStatusToExcel).html('<b>' + valueFormat(totalValue) + '</b>');
                        }
                    });
                    
                });
                
            },
            
        }
    });

});

