// Imports
import com.gridnine.xtrip.common.l10n.model.LocaleHelper
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.helpers.ProfileHelper
import com.gridnine.xtrip.common.model.booking.OperationBatch
import com.gridnine.xtrip.common.model.dict.AddressType
import com.gridnine.xtrip.common.model.dict.ContractType
import com.gridnine.xtrip.common.util.MiscUtil

import java.text.SimpleDateFormat

// Styles
createStyle(name: 'title', v_alignment: 'CENTER')
createStyle(name: 'titleH1', fontHeight: 16, parent: 'title')
createStyle(name: 'titleH1Center', h_alignment: 'CENTER', parent: 'titleH1')
createStyle(name: 'titleH1CenterBold', fontBold: true, parent: 'titleH1Center')
createStyle(name: 'titleH2', fontHeight: 14, parent: 'title')
createStyle(name: 'titleH2Center', h_alignment: 'CENTER', parent: 'titleH2')
createStyle(name: 'titleH2CenterBold', fontBold: true, parent: 'titleH2Center')
createStyle(name: 'titleH3', fontHeight: 10, parent: 'title')
createStyle(name: 'titleH3Center', h_alignment: 'CENTER', parent: 'titleH3')
createStyle(name: 'titleH3Right', h_alignment: 'RIGHT', parent: 'titleH3')
createStyle(name: 'header', fontHeight: 10, v_alignment: 'CENTER', topBorder: 'THIN', leftBorder: 'THIN', bottomBorder: 'THIN', rightBorder: 'THIN')
createStyle(name: 'columnHeader', wrapText: true, h_alignment: 'CENTER', parent: 'header')
createStyle(name: 'columnHeaderBold', fontBold: true, parent: 'columnHeader')
createStyle(name: 'rowHeader', h_alignment: 'RIGHT', parent: 'header')
createStyle(name: 'rowHeaderBold', fontBold: true, parent: 'rowHeader')
createStyle(name: 'data', fontHeight: 8, v_alignment: 'CENTER', topBorder: 'THIN', leftBorder: 'THIN', bottomBorder: 'THIN', rightBorder: 'THIN')
createStyle(name: 'dataText', parent: 'data')
createStyle(name: 'dataTextCenter', h_alignment: 'CENTER', parent: 'dataText')
createStyle(name: 'dataTextRight', h_alignment: 'RIGHT', parent: 'dataText')
createStyle(name: 'dataTextBold', fontBold: true, parent: 'dataText')
createStyle(name: 'dataTextCenterBold', fontBold: true, parent: 'dataTextCenter')
createStyle(name: 'dataTextRightBold', fontBold: true, parent: 'dataTextRight')
createStyle(name: 'dataDate', h_alignment: 'CENTER', format: 'm/d/yy', parent: 'data')
createStyle(name: 'dataNumber', h_alignment: 'RIGHT', format: '#,##0.00', parent: 'data')
createStyle(name: 'dataNumberBold', fontBold: true, parent: 'dataNumber')

// Properties
def periodBeginParameter = parameters['key-report-params']?.periodBegin
def periodEndParameter = parameters['key-report-params']?.periodEnd
def supplierParameter = parameters['supplier']
def agencyParameter = parameters['agency']
def subagencyParameter = parameters['subagency']
def consolidatedParameter = parameters['consolidated']
def productTypeParameter = parameters['productType']

// Closures
def agencyName = {
    
    def agency = EntityStorage.get().resolve(agencyParameter)?.entity
    return agency ? ProfileHelper.getFullName(agency, LocaleHelper.getLocale('ru', 'RU'), false) : 'Не указано'
}

def agencyAddressCodes = {
    
    def agency = EntityStorage.get().resolve(agencyParameter)?.entity
    return agency ? 'ИНН / КПП ' + (agency.registrationId ? agency.registrationId : '?') + ' / ' + (agency.kpp ? agency.kpp : '?') : 'ИНН / КПП ?/? '
}

def agencyAddressLegal = {
    
    def agency = EntityStorage.get().resolve(agencyParameter)?.entity
    return agency ? ProfileHelper.buildFullAddress(ProfileHelper.filterAddresses(agency.addresses, AddressType.LEGAL), LocaleHelper.getLocale('ru', 'RU'), false) : ''
}

def subagencyName = {
    
    def subagency = EntityStorage.get().resolve(subagencyParameter)?.entity
    return subagency ? ProfileHelper.getFullName(subagency, LocaleHelper.getLocale('ru', 'RU'), false) : 'Не указано'
}

def subagencyAddressCodes = {
    
    def subagency = EntityStorage.get().resolve(subagencyParameter)?.entity
    return subagency ? 'ИНН / КПП ' + (subagency.registrationId ? subagency.registrationId : '?') + ' / ' + (subagency.kpp ? subagency.kpp : '?') : 'ИНН / КПП ?/? '
}

def subagencyAddressLegal = {
    
    def subagency = EntityStorage.get().resolve(subagencyParameter)?.entity
    return subagency ? ProfileHelper.buildFullAddress(ProfileHelper.filterAddresses(subagency.addresses, AddressType.LEGAL), LocaleHelper.getLocale('ru', 'RU'), false) : ''
}

def contract = {
    
    def contracts = ProfileHelper.getContracts(subagencyParameter, agencyParameter, subagencyParameter, ContractType.SUBAGENCY, periodBeginParameter, periodEndParameter)
    def format = new SimpleDateFormat('dd.MM.yyyy')
    def number = contracts.size() > 0 ? ProfileHelper.getContractCustomerInfo(contracts.get(0), customer)?.number : null
    def issueDate = contracts.size() > 0 ? ProfileHelper.getContractCustomerInfo(contracts.get(0), customer)?.issueDate : null
    def result = ''
    
    result += number ? number : ''
    result += issueDate ? (result.length() > 0 ? ' от ' : '') + format.format(issueDate) : ''
    
    return result
}

def period = {
    
    def format = new SimpleDateFormat('dd.MM.yyyy')
    return String.format('%s по %s', periodBeginParameter ? format.format(periodBeginParameter) : '?', periodEndParameter ? format.format(periodEndParameter) : '?')
}

def value = { value ->
    
    return value != null && value.compareTo(BigDecimal.ZERO) != 0 ? value : null
}

// Page "Rеgistry"
page{it?.operationBatch?.toString()}{

    // Set scale
    scale(75)

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

    // Set defalt row height
    rowHeight(13.2)

    // Header
    rowHeight(15, false)

    def title = null

    // Initialization
    tickets{

        if(it.operationBatch == OperationBatch.SELL) {
            title = consolidatedParameter ? 'Реестр продаж' : 'Реестр продаж (' + productTypeParameter + ')'
        } else if(it.operationBatch == OperationBatch.REFUND) {
            title = consolidatedParameter ? 'Реестр возвратов' : 'Реестр возвратов (' + productTypeParameter + ')'
        } else if(it.operationBatch == OperationBatch.EXCHANGE) {
            title = consolidatedParameter ? 'Реестр обменов' : 'Реестр обменов (' + productTypeParameter + ')'
        } else if(it.operationBatch == OperationBatch.VOID) {
            title = consolidatedParameter ? 'Реестр аннуляций' : 'Реестр аннуляций (' + productTypeParameter + ')'
        }
    }

    text(title, 'titleH2CenterBold', 13, 1)
    2.times{nextRow()}
    text('Принципал (Агентство):', 'titleH3')
    4.times{nextColumn()}
    text(agencyName(), 'titleH3')
    nextRow()
    4.times{nextColumn()}
    text(agencyAddressCodes(), 'titleH3')
    nextRow()
    4.times{nextColumn()}
    text(agencyAddressLegal(), 'titleH3')
    nextRow()
    text('Комиссионер (Субагент):', 'titleH3')
    4.times{nextColumn()}
    text(subagencyName(), 'titleH3')
    nextRow()
    4.times{nextColumn()}
    text(subagencyAddressCodes(), 'titleH3')
    nextRow()
    4.times{nextColumn()}
    text(subagencyAddressLegal(), 'titleH3')
    nextRow()
    text('Договор:', 'titleH3')
    4.times{nextColumn()}
    text(contract(), 'titleH3')
    nextRow()
    text('Период:', 'titleH3')
    4.times{nextColumn()}
    text(period(), 'titleH3')
    2.times{nextRow()}

    // Table header
    columnWidth(5)
    text('№№', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(5)
    text('Код АК', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(10)
    text('№ билета', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(10)
    text('Дата', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(24)
    text('Маршрут', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(12)
    text('Тариф', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(10)
    text('Такса за бланк', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(10)
    text('Другие таксы', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(10)
    text('Штраф', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(12)
    text('Итого', 'columnHeader', 1, 2)
    nextColumn()
    columnWidth(15)
    text('Комиссия', 'columnHeader', 2, 1)
    2.times{nextColumn()}
    columnWidth(10)
    text('Сбор агента', 'columnHeader', 1, 2)
    nextRow()
    10.times{nextColumn()}
    columnWidth(5)
    text('%', 'columnHeader')
    nextColumn()
    columnWidth(10)
    text('Сумма', 'columnHeader')
    nextRow()

    def count = 0

    // Data
    tickets{
        def penalty = value(it.subagencyContractPenalty)
        def contractPenalty = value(it.vendorContractPenaltyValue)
        if (contractPenalty == null) {
            contractPenalty = value(it.subagencyContractPenaltyValue)
        }
        if (contractPenalty == null) {
            contractPenalty = value(it.clientContractPenaltyValue)
        }

        text(String.valueOf(count + 1), 'dataText')
        nextColumn()
        text(it.systemNumberPrefix, 'dataTextCenter')
        nextColumn()
        text(it.systemNumbers.size() > 0 ? it.systemNumbers.iterator().next() : null, 'dataTextCenter')
        nextColumn()
        date(it.issueDate, 'dataDate')
        nextColumn()
        text(it.routeLineCodes, 'dataTextCenter')
        nextColumn()
        number(value(it.subagencyContractFare), 'dataNumber')
        nextColumn()
        number(value(it.subagencyContractTaxesForBlankSum), 'dataNumber')
        nextColumn()
        number(value(MiscUtil.sum(value(it.subagencyContractOtherTaxesSum), value(it.subagencyHiddenFeeValue))), 'dataNumber')
        nextColumn()
        number(value(MiscUtil.sum(penalty, contractPenalty)), 'dataNumber')
        nextColumn()
        number(value(MiscUtil.sum(it.subagencyContractTotalSum, it.subagencyHiddenFeeValue)), 'dataNumber')
        nextColumn()
        number(value(it.subagencyCommissionRate), 'dataNumber')
        nextColumn()
        number(value(it.subagencyCommissionValue), 'dataNumber')
        nextColumn()
        number(value(MiscUtil.sub(value(it.subagencyFeeValue), value(it.subagencyHiddenFeeValue))), 'dataNumber')
        nextRow()

        count++
    }

    // Table footer
    text('Итого', 'dataTextRightBold', 5, 1)
    if (count != 0) {
        5.times{nextColumn()}
        formula("SUM(${cellIndex(-count, 0)}:${cellIndex(-1, 0)})", 'dataNumberBold')
        nextColumn()
        formula("SUM(${cellIndex(-count, 0)}:${cellIndex(-1, 0)})", 'dataNumberBold')
        nextColumn()
        formula("SUM(${cellIndex(-count, 0)}:${cellIndex(-1, 0)})", 'dataNumberBold')
        nextColumn()
        formula("SUM(${cellIndex(-count, 0)}:${cellIndex(-1, 0)})", 'dataNumberBold')
        nextColumn()
        formula("SUM(${cellIndex(-count, 0)}:${cellIndex(-1, 0)})", 'dataNumberBold')
        nextColumn()
        text(null, 'dataTextBold')
        nextColumn()
        formula("SUM(${cellIndex(-count, 0)}:${cellIndex(-1, 0)})", 'dataNumberBold')
        nextColumn()
        formula("SUM(${cellIndex(-count, 0)}:${cellIndex(-1, 0)})", 'dataNumberBold')
    }

    4.times{nextRow()}
    9.times{nextColumn()}
    text('Составил', 'titleH3Right')
    nextColumn()
    text('_________________________', 'titleH3Center', 3, 1)
    nextRow()
    10.times{nextColumn()}
    text('(                                          )', 'titleH3Center', 3, 1)
}
