import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicket
import com.gridnine.xtrip.common.model.booking.air.Tax
import com.gridnine.xtrip.common.util.MiscUtil
import com.gridnine.xtrip.common.util.TextUtil

//CREATING STYLES
createStyle(name: 'baseStyle', fontBold: true,  h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight:12)
createStyle(name: 'bigHeader', parent: 'baseStyle', fontHeight:18)
createStyle(name: 'midHeader', parent: 'baseStyle',h_alignment: 'LEFT')
createStyle(name: 'smallHeader', parent:'baseStyle', fontHeight:8, h_alignment: 'RIGHT')
createStyle(name: 'smallHeaderCenter', parent: 'smallHeader', h_alignment: 'CENTER')
createStyle(name: 'tableHeader', parent: 'baseStyle', fontHeight:11, leftBorder:'MEDIUM', rightBorder:'MEDIUM', topBorder:'MEDIUM', bottomBorder:'MEDIUM')
createStyle(name: 'tableContent', parent: 'baseStyle', fontHeight:11, fontBold: false, leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN')
createStyle(name: 'textData', parent: 'tableContent')
createStyle(name: 'textDataBold', parent: 'tableContent', fontBold: true)
createStyle(name: 'dateData', format: 'm/d/yy', parent: 'tableContent')
createStyle(name: 'dateDataBold', format: 'm/d/yy', parent: 'tableContent', fontBold: true)
createStyle(name: 'numberData', format: '#,##0.00', parent: 'tableContent')
createStyle(name: 'emptyNumberData', parent: 'tableContent')
createStyle(name: 'numberDataBold', format: '#,##0.00', parent: 'tableContent', fontBold: true)

//ADDITIONAL FUNCTIONS
class Formula {
    String formula
    Formula(){}
    Formula(String formula){
        this.formula = formula
    }

    static Formula getSumFormulaByRow (String start, String end) {
        return new Formula('SUM(' + start + ':' + end + ')')
    }
    static Formula getSumFormulaByCell (String... index) {
        def formula = ''
        for (int i=0; i<index.size(); i++) {
            if (i == 0) {
                formula += index[i]
            } else {
                formula += ',' + index[i]
            }
        }
        return new Formula('SUM(' + formula + ')')
    }
}

def cellFill = { value ->
    if (value != null) {
        if (value instanceof Number) {
            number(value,'numberData')
        } else if (value instanceof Date) {
            date(value,'dateData')
        } else if (value instanceof Formula){
            formula(value.formula,'numberData')
        } else {
            text(value, 'textData')
        }
    } else {
        text('', 'textData')
    }
}

def cellFillBold = { value ->
    if (value != null) {
        if (value instanceof Number) {
            number(value,'numberDataBold')
        } else if (value instanceof Date) {
            date(value,'dateDataBold')
        } else {
            text(value, 'textDataBold')
        }
    } else {
        text('', 'textDataBold')
    }
}

def nextColumnEmptyContent = {
    cellFill('')
    nextColumn()
}

def reportHeader = {
    rowHeight(20)
    nextColumn()
    text('Продажа а/б', 'bigHeader', 9, 1)
    2.times {nextRow()}
    text('Владелец БСО', 'baseStyle', 4, 1)
    5.times {nextColumn()}
    text('Период расчетов:' + parameters.REPORT_PERIOD, 'midHeader', 9, 1)
    nextRow()
    text('Код взаиморасчетов', 'baseStyle', 4, 1)
    nextRow()
    text('Регион перевозок', 'baseStyle', 4, 1)
    nextRow()
}

def createSumFormulaForColumn = { int rowShift->
    return Formula.getSumFormulaByRow(cellIndex(rowShift, 0), cellIndex(-2, 0))
}

def reportEnd = {
    12.times {nextColumn()}
    int rowShift = -(allTickets.size()+1)
    cellFill(createSumFormulaForColumn(rowShift))
    2.times {nextColumn()}
    9.times {
        cellFill(createSumFormulaForColumn(rowShift))
        nextColumn()
    }
    nextRow()
}


def fillTableHeaderSell = {String content ->

    text(content, 'tableHeader')
    nextColumn()
}

def tableHeader = {
    rowHeight(15)
    columnWidth(10)
    fillTableHeaderSell('№ п/п')
    columnWidth(20)
    fillTableHeaderSell('Отв.перевозчик')
    columnWidth(15)
    fillTableHeaderSell('Вид БСО')
    columnWidth(25)
    fillTableHeaderSell('№ билета системный')
    columnWidth(10)
    fillTableHeaderSell('№ уч.')
    columnWidth(18)
    fillTableHeaderSell('Дата продажи')
    columnWidth(5)
    fillTableHeaderSell('')
    columnWidth(15)
    fillTableHeaderSell('Дата вылета')
    columnWidth(20)
    fillTableHeaderSell('Базовый тариф')
    columnWidth(20)
    fillTableHeaderSell('Маршрут')
    columnWidth(25)
    fillTableHeaderSell('Тариф за ед. изм.')
    columnWidth(15)
    fillTableHeaderSell('Вес/кол-во')
    columnWidth(15)
    fillTableHeaderSell('Тариф')
    columnWidth(12)
    fillTableHeaderSell('% ком')
    columnWidth(15)
    fillTableHeaderSell('Комиссия')
    columnWidth(15)
    fillTableHeaderSell('АГС')
    columnWidth(15)
    fillTableHeaderSell('ТН')
    columnWidth(15)
    fillTableHeaderSell('Такса SA')
    columnWidth(15)
    fillTableHeaderSell('Штраф')
    columnWidth(18)
    fillTableHeaderSell('Сборы МЕСТО')
    columnWidth(15)
    fillTableHeaderSell('% ком')
    columnWidth(20)
    fillTableHeaderSell('Комиссия сборов')
    columnWidth(15)
    fillTableHeaderSell('Итого')
    nextRow()
}


def tableBody = {
    int row = 0
    allTickets.each { AirTicketsTemplateReportTicket ticket ->
        nextColumnEmptyContent()
        cellFill(ticket.carriersLine)
        nextColumn()
        cellFill(ticket.validatingCarrierNumber)
        nextColumn()
        cellFill(ticket.ticketNumber)
        nextColumn()
        nextColumnEmptyContent()
        cellFill(ticket.issueDate)
        nextColumn()
        nextColumnEmptyContent()
        cellFill(ticket.departureDate)
        nextColumn()
        nextColumnEmptyContent()
        cellFill(ticket.routeLine)
        nextColumn()
        2.times {nextColumnEmptyContent()}
        cellFill(ticket.equivalentFare)
        nextColumn()
        cellFill(ticket.vendorCommissionRate)
        nextColumn()
        cellFill(ticket.vendorCommissionValue)
        nextColumn()
        BigDecimal agsTax = BigDecimal.ZERO
        ticket.taxes.each {Tax tax ->
            if (TextUtil.isSame(tax.code, 'AGS')) {
                agsTax = MiscUtil.sum(agsTax, tax.equivalentAmount)
            }
        }
        cellFill(agsTax)
        nextColumn()
        cellFill(ticket.fuelChargeAmount)
        nextColumn()
        nextColumnEmptyContent()
        cellFill(ticket.penalty)
        nextColumn()
        3.times {nextColumnEmptyContent()}
        cellFill(Formula.getSumFormulaByCell(cellIndex(row, -10), cellIndex(row, -7), cellIndex(row, -6), cellIndex(row, -5)))
        nextRow()
        row++
    }
}

def reportBody = {
    tableHeader()
    tableBody()
}

page{'Sell registry'} {
    warn 'report version = ' + '0.1.0'

    reportHeader()
    reportBody()
    reportEnd()
}