$(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 (isNonFormatValue) {
            return value;
        }
    
        if (isCurrencyValue) {
            return format(value) + ' грн.';
        } else {
            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['ViewID'][0],
                    orderId = item['period'],
                    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: item['ViewID'][0],
                        orderId: item['period'],
                        confirmed: (orderStatus && !orderStatus.confirmed) ? '' : 'checked',
                        approved: (orderStatus && orderStatus.approved) ? 'disabled' : '',
                    }
                })));
                $row.append($('<td class="OrderID">').append(templateOrderIDContent({
                    data: {
                        feedId: item['ViewID'][0],
                        orderId: item['period'],
                        //confirmed: (orderStatus && !orderStatus.confirmed) ? '' : 'checked',
                        //approved: (orderStatus && orderStatus.approved) ? 'disabled' : '',
                    }
                })));
                
                $rowExcel = $('<tr class="order-item ' + trClass + '" data-feed-id="' + item['ViewID'][0] + '" data-order-id="' + item['period'] + '">');
                $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[line][0], viewId: item[line][1]}
                    })));
                } else {
                    currentActiveLine = line;
                    $row.append($('<td class="'+ line +'">').html(valueFormat(item[line])));
                    $rowExcel.append($('<td>').html(valueFormat(item[line])));
                }
            });
            $row.appendTo($tableContent);
            $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;
                    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>');
                        }
                    });
                    
                });
                
            },
            
        }
    });

});

