// Imports
import com.gridnine.xtrip.common.l10n.model.LocaleHelper
import com.gridnine.xtrip.common.model.dict.MCOCategory
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.helpers.ProfileHelper
import com.gridnine.xtrip.common.model.helpers.SystemHelper
import com.gridnine.xtrip.common.model.system.MetadataKey
import com.gridnine.xtrip.common.util.MiscUtil

import java.text.SimpleDateFormat

// Styles
createStyle(name: 'title', h_alignment: 'CENTER', v_alignment: 'CENTER')
createStyle(name: 'titleH1', fontHeight: 12, parent: 'title')
createStyle(name: 'titleH2', fontHeight: 8, parent: 'title', fontBold: true)
createStyle(name: 'titleH3', fontHeight: 6, parent: 'title')
createStyle(name: 'header', h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight: 8)
createStyle(name: 'columnHeader', h_alignment: 'CENTER', parent: 'header')
createStyle(name: 'rowHeader', parent: 'header')
createStyle(name: 'data', h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight: 8)
createStyle(name: 'dataText', parent: 'data')
createStyle(name: 'dataDate', format: 'm/d/yy', parent: 'data')
createStyle(name: 'dataNumber', h_alignment: 'RIGHT', parent: 'data')
createStyle(name: 'dataTariff', format: '#,##0.00', parent: 'dataNumber')
createStyle(name: 'wrap', wrapText: true)
createStyle(name: 'ahl', h_alignment: 'LEFT')
createStyle(name: 'ahc', h_alignment: 'CENTER')
createStyle(name: 'ahr', h_alignment: 'RIGHT')
createStyle(name: 'avt', v_alignment: 'TOP')
createStyle(name: 'avc', v_alignment: 'CENTER')
createStyle(name: 'avb', v_alignment: 'BOTTOM')
createStyle(name: 'aac', h_alignment: 'CENTER', v_alignment: 'CENTER')
createStyle(name: 'bold', fontBold: true)
createStyle(name: 'italic', fontItalic: true)
createStyle(name: 'bt', topBorder: 'THIN')
createStyle(name: 'bl', leftBorder: 'THIN')
createStyle(name: 'bb', bottomBorder: 'THIN')
createStyle(name: 'br', rightBorder: 'THIN')
createStyle(name: 'ba', topBorder: 'THIN', leftBorder: 'THIN', bottomBorder: 'THIN', rightBorder: 'THIN')

// Closures
def period = {
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy")
    def periodBeginParameter = parameters['key-report-params']?.periodBegin
    def periodEndParameter = parameters['key-report-params']?.periodEnd
    return "с " +
            (periodBeginParameter ? sdf.format(periodBeginParameter) : "") +
            " по " +
            (periodEndParameter ? sdf.format(periodEndParameter) : "")
}

def currentYear = {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy")
    def periodEndParameter = parameters['key-report-params']?.periodEnd
    return periodEndParameter ? sdf.format(periodEndParameter) : ""
}

def agencyName = {
    def organization = EntityStorage.get().resolve(parameters['key-report-params']?.agency)?.entity
    return organization ? ProfileHelper.getFullName(organization, LocaleHelper.RU_LOCALE, false) : 'Не указано'
}

def agencyCode = {
    def organization = EntityStorage.get().resolve(parameters['key-report-params']?.agency)?.entity
    return organization ? SystemHelper.findMetadataAsString(organization.getMetadata(), MetadataKey.KEY_HZ_AGENCY_CODE) : 'Не указано'
}

page { parameters['isBaggage'] ? 'Реестр КПБ и EMD' : 'Реестр МСО и EMD' } {

    // Set portrait mode
    landscape(false)

    // Set narrow margins
    margin(0.25, 0.25, 0.75, 0.75)

    // Set scale
    scale(100)

    // Set preserve mode
    preserve(false)

// Report header
    nextRow()
    text(parameters['isBaggage'] ? 'Форма №6 / Form No 6' : 'Форма №5 / Form No 5', 'titleH3|ahl', 2, 1)
    nextRow()
    def title = parameters['isBaggage'] ?
            'РЕЕСТР ПО ПРОДАЖЕ И АННУЛИРОВАНИЮ КПБ (квитанции платного багажа) и ЕМD (оформленные как платный багаж)'
            : 'РЕЕСТР ПО ПРОДАЖЕ И АННУЛИРОВАНИЮ МСО и EMD (оформленные как штраф или сбор)'
    text(title + '\nSALE/CANCEL LIST (paper form) Domestic route', 'titleH2|ba', 9, 1)
    rowHeight(30)
    nextRow()

    text('Авиакомпания:\n' +
            'Airline:', 'titleH2|ba', 2, 1)
    2.times { nextColumn() }
    text('АО "АВИАКОМПАНИЯ "АВРОРА"', 'titleH2|ba', 2, 1)
    2.times { nextColumn() }
    text('Код:\n' +
            'Code:', 'titleH2|ba')
    nextColumn()
    text('ИЕ', 'titleH2|ba',)
    nextColumn()
    text('Отчет:\n' +
            'Report:', 'titleH2|ba')
    nextColumn()
    text('№', 'titleH2|ahl|ba', 2, 1)
    rowHeight(30)
    nextRow()

    text('Агент:\n' +
            'Agent:', 'titleH2|ba', 2, 1)
    2.times { nextColumn() }
    text(agencyName(), 'titleH2|ba|wrap', 2, 1)
    2.times { nextColumn() }
    text('Код:\n' +
            'Code:', 'titleH2|ba')
    nextColumn()
    text(agencyCode(), 'titleH2|ba')
    nextColumn()
    text('Период:\n' +
            'Period:', 'titleH2|ba')
    nextColumn()
    text(period(), 'titleH2|ba', 2, 1)
    rowHeight(30)
    2.times { nextRow() }

// Table header
    text('№ п.п.\n' +
            'RefNo', 'columnHeader|ba')
    nextColumn()
    text('№ документа МСО\n' +
            'DocumentNo', 'columnHeader|ba')
    nextColumn()
    text('Номер документа\n авиабилет-\nоснование\n' +
            'DocumentNo', 'columnHeader|ba')
    nextColumn()
    text('Дата продажи\n' +
            'Date of issue', 'columnHeader|ba')
    nextColumn()
    text('Тариф\n' +
            'Fare amount', 'columnHeader|ba')
    nextColumn()
    text('Такса\n' +
            'Taxes', 'columnHeader|ba')
    nextColumn()
    text('%\nкомиссии\n' +
            'Commis\nAmount', 'columnHeader|ba')
    nextColumn()
    text('Сумма\nкомиссии\n' +
            'Commis\nAmount', 'columnHeader|ba')
    nextColumn()
    text('Итого\n' +
            'Total', 'columnHeader|ba')
    rowHeight(50)
    nextRow()

    //Post header
    int pCounter = 1
    9.times {
        number(pCounter++, 'columnHeader|ba|avt')
        nextColumn()
    }
    rowHeight(30)
    nextRow()

// Table

    int counter = 1
    tickets {
        number(++counter, 'dataText|ba')
        nextColumn()
        text((it.validatingCarrierNumber ? it.validatingCarrierNumber + " " : "") +
                (it.ticketNumber ? it.ticketNumber : ""), 'dataText|ba')
        nextColumn()
        text((it.relatedTicketValidatingCarrierNumber ? it.relatedTicketValidatingCarrierNumber + " " : "") +
                (it.relatedTicketNumber ? it.relatedTicketNumber : ""), 'dataText|ba')
        nextColumn()
        date(it.issueDate, 'dataDate|ba')
        nextColumn()
        def tariff = it.mcoCategory == MCOCategory.PENALTY ? it.penalty : it.equivalentFare
        number(tariff, 'dataTariff|ba')
        nextColumn()
        number(it.taxesSum ? it.taxesSum : BigDecimal.ZERO, 'dataNumber|ba')
        nextColumn()
        number(it.vendorCommissionRate ? it.vendorCommissionRate : BigDecimal.ZERO, 'dataText|ba|ahc')
        nextColumn()
        BigDecimal commission = it.vendorCommissionValue ? it.vendorCommissionValue : BigDecimal.ZERO
        number(commission, 'dataNumber|ba')
        nextColumn()
        number(MiscUtil.sub(it.price, commission), 'dataNumber|ba')
        nextRow()
    }

    //Total
    nextRow()
    rowHeight(22)
    text('', 'dataText|ba')
    nextColumn()
    text('ВСЕГО:\n' +
            'Total:', 'dataText|ba|bold')
    nextColumn()
    2.times {
        text('', 'dataText|ba')
        nextColumn()
    }
    formula("SUM(E9:${cellIndex(-1, 0)})", 'dataTariff|ba|bold')
    nextColumn()
    number(BigDecimal.ZERO, 'dataNumber|ba|bold')
    nextColumn()
    text('', 'dataText|ba')
    nextColumn()
    formula("SUM(H9:${cellIndex(-1, 0)})", 'dataNumber|ba|bold')
    nextColumn()
    formula("SUM(I9:${cellIndex(-1, 0)})", 'dataNumber|ba|bold')
    nextRow()

    //Auto column width
    10.times {
        nextColumn()
        columnAutoWidth()
    }

    //Footer
    nextRow()
    3.times { nextColumn() }
    text('ПОДПИСИ СТОРОН', 'dataText|bold', 4, 1)
    2.times { nextRow() }
    rowHeight(100)
    nextColumn()
    text('ПЕРЕВОЗЧИК\n' +
            '\n' +
            '__________________________/                               /\n' +
            '\n' +
            '___________"_____________________' + currentYear() + ' год', 'dataText|ahl', 3, 1)
    4.times { nextColumn() }
    text('АГЕНТ\n' +
            '\n' +
            '__________________________/                               /\n' +
            '\n' +
            '___________"_____________________' + currentYear() + ' год', 'dataText|ahl', 4, 1)
    nextRow()

    //Manual column width correction
    columnWidth(6)
    7.times { nextColumn() }
    columnWidth(9); nextColumn()
    columnWidth(13)
}
