// Imports
import com.gridnine.xtrip.common.l10n.model.LocaleHelper
import com.gridnine.xtrip.common.model.booking.agencymemo.AgencyMemoProductType
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.helpers.PersonalLocalizableNameFormatter
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: 10, parent: 'title')
createStyle(name: 'header', h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight: 9)
createStyle(name: 'columnHeader', parent: 'header')
createStyle(name: 'rowHeader', parent: 'header')
createStyle(name: 'data', h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight: 9)
createStyle(name: 'dataText', parent: 'data')
createStyle(name: 'dataDate', format: 'm/d/yy', parent: 'data')
createStyle(name: 'dataNumber', h_alignment: 'RIGHT', format: '#,##0.00', parent: 'data')
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')

// Properties
def agency = EntityStorage.get().resolve(requestedParameter('agency'))?.entity

// 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 agencyName = {
    return agency ? ProfileHelper.getFullName(agency, LocaleHelper.getLocale('ru', 'RU'), false) : 'Не указано'
}

def agencyCode = {
    return agency ? SystemHelper.findMetadataAsString(agency.getMetadata(), MetadataKey.KEY_SU_AGENCY_CODE) : 'Не указано'
}

def chiefAccountantName = {
    def person = EntityStorage.get().resolve(requestedParameter('chief accountant'))?.entity
    def format = new PersonalLocalizableNameFormatter(PersonalLocalizableNameFormatter.SIMPLE)
    return person ? format.format(person, LocaleHelper.getLocale('ru', 'RU'), false) : '?'
}


page { 'Реестр на бонусное комиссионное вознаграждение' } {

    // 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)

    //Setup columns width
    columnWidth(25)
    nextColumn()
    columnWidth(20)
    nextColumn()
    columnWidth(15)
    nextColumn()
    columnWidth(25)

// Report header
    nextRow()
    text('Реестр на бонусное комиссионное вознаграждение', 'titleH1|ahl', 4, 1)
    nextRow()
    text('агента ПАО "Аэрофлот" ' + period(), 'titleH1|ahl')
    nextRow()
    text('Наименование агента', 'titleH2|ahl')
    nextColumn()
    text(agencyName(), 'titleH2')
    nextRow()
    text('Код агента', 'titleH2|ahl')
    nextColumn()
    text(agencyCode(), 'titleH2')
    2.times { nextRow() }

    //Currency
    3.times { nextColumn() }
    text('RUB', 'columnHeader|bold|ahr')
    nextRow()

// Table header
    text('№  ACM/ADM', 'columnHeader|wrap|ba|bold')
    nextColumn()
    text('IATA Agent № (валидатор)', 'columnHeader|wrap|ba|bold')
    nextColumn()
    text('Бонусное комиссионное вознаграждение', 'columnHeader|wrap|ba|bold')
    nextColumn()
    text('ИТОГО', 'columnHeader|wrap|ba|bold')
    rowHeight(50)
    nextRow()

// Table
    tickets {
        def supplierCode = EntityStorage.get().resolve(it.getSupplier()).getEntity().getCode()
        if (supplierCode == "SU") {
            def vendorAmount = it.getVendorEquivalentAmount()
            if (it.getType() == AgencyMemoProductType.ADM) {
                vendorAmount = MiscUtil.negate(vendorAmount)
            }
            text(it.getAirlineCode() + it.getSystemNumber(), 'dataText|wrap|ba')
            nextColumn()
            number(null, 'dataText|wrap|ba')
            nextColumn()
            number(vendorAmount, 'dataNumber|ba')
            nextColumn()
            number(vendorAmount, 'dataNumber|ba|ahr')
            nextRow()
        }
    }
    text('ИТОГО:', 'dataText|wrap|ba|ahl|bold')
    nextColumn()
    text('', 'dataText|ba')
    nextColumn()
    formula("SUM(C9:${cellIndex(-1, 0)})", 'dataNumber|ba')
    nextColumn()
    formula("SUM(D9:${cellIndex(-1, 0)})", 'dataNumber|ba')

    6.times { nextRow() }
    text('Главный бухгалтер', 'titleH2|bold|ahc')
    2.times { nextColumn() }
    text('', 'bb')
    nextColumn()
    text(chiefAccountantName(), 'titleH2|bold|ahr')
}