import com.gridnine.xtrip.common.model.booking.air.Tax
import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicket
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 createSummFormulaForColumn = {int rowShift->
    return Formula.getSumFormulaByRow(cellIndex(rowShift, 0), cellIndex(-1, 0))
}

def reportEnd = {
    text('Итого по реестру', 'baseStyle', 10, 1)
    10.times {nextColumn()}
    int rowShift = -(allTickets.size())
    cellFill(createSummFormulaForColumn(rowShift))
    2.times {nextColumn()}
    6.times {
        cellFill(createSummFormulaForColumn(rowShift))
        nextColumn()
    }
}

def fillTableHeaderRef = {String content ->
    text(content, 'tableHeader')
    nextColumn()
}


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

def tableBody = {
    int row = 0
    allTickets.each { AirTicketsTemplateReportTicket ticket ->
        nextColumnEmptyContent()
        cellFill(ticket.carriersLine)
        nextColumn()
        cellFill(ticket.validatingCarrierNumber)
        nextColumn()
        cellFill(ticket.ticketNumber)
        nextColumn()
        cellFill(ticket.relatedTicketIssueDate)
        nextColumn()
        cellFill(ticket.issueDate)
        nextColumn()
        nextColumnEmptyContent()
        cellFill(ticket.departureDate)
        nextColumn()
        nextColumnEmptyContent()
        cellFill(ticket.routeLine)
        nextColumn()
        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()
        cellFill(Formula.getSumFormulaByCell(cellIndex(row, -3), cellIndex(row, -4), cellIndex(row, -7)))
        nextColumn()
        nextColumnEmptyContent()//TODO EMD

        nextRow()
        row++
    }
}

def reportBody = {
    tableHeader()
    tableBody()
}

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

    reportHeader()
    reportBody()
    reportEnd()
}