import com.gridnine.xtrip.common.l10n.model.LocaleHelper
import com.gridnine.xtrip.common.model.booking.ProductStatus
import com.gridnine.xtrip.common.model.dict.DictionaryCache
import com.gridnine.xtrip.common.model.dict.DictionaryReference
import com.gridnine.xtrip.common.model.dict.GeoLocation
import com.gridnine.xtrip.common.model.dict.LocationType
import com.gridnine.xtrip.common.model.helpers.DictHelper
import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicket

import java.text.SimpleDateFormat

createStyle(name: "left", h_alignment: "LEFT")
createStyle(name: "right", h_alignment: "RIGHT")
createStyle(name: "center", h_alignment: "CENTER")
createStyle(name: "left-bold", h_alignment: "LEFT", fontBold : true)
createStyle(name: "right-bold", h_alignment: "RIGHT", fontBold : true)
createStyle(name: "center-bold", h_alignment: "CENTER", fontBold : true)
createStyle(name: "left-bold-border", h_alignment: "LEFT", fontBold : true, leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)
createStyle(name: "right-bold-border", h_alignment: "RIGHT", fontBold : true, leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)
createStyle(name: "center-bold-border", h_alignment: "CENTER", fontBold : true, leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)
createStyle(name: "left-border", h_alignment: "LEFT", leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)
createStyle(name: "right-border", h_alignment: "RIGHT", leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)
createStyle(name: "center-border", h_alignment: "CENTER", leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)

def printHead() {
    rowHeight(15)
    columnWidth(5)
    nextColumn()
    columnWidth(30)
    nextColumn()
    columnWidth(25)
    nextColumn()
    columnWidth(25)

    nextRow()
    nextColumn()
    text("АО \"КАП\"")

    nextRow()
    nextColumn()
    text("Агентство")

    nextColumn()
    text(parameters['AGENCY_NAME'])
}

def printTitle() {
    nextRow()
    nextRow()
    nextRow()
    text("Реестр продажи и возврата по аэропортам вылета", "center-bold", 4, 1)

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    def periodBeginParameter = parameters['key-report-params']?.periodBegin
    def periodEndParameter = parameters['key-report-params']?.periodEnd

    nextRow()
    text("за период с " +
            (periodBeginParameter ? sdf.format(periodBeginParameter) : "") +
            " по " +
            (periodEndParameter ? sdf.format(periodEndParameter) : ""),
            "center-bold", 4, 1)
}

def printTickets() {
    Map<DictionaryReference<GeoLocation>, Map<ProductStatus, BigDecimal>> result = new HashMap<>()

    tickets { AirTicketsTemplateReportTicket ticket ->
        if (ticket.status != null &&
                ticket.departureGeoLocation != null &&
                ticket.equivalentFare != null) {
            GeoLocation departureGeoLocation =
                    DictionaryCache.get().resolveReference(ticket.departureGeoLocation)
            if (departureGeoLocation.type == LocationType.AIRPORT) {
                GeoLocation departureCity =
                        DictHelper.findCityByAirport(departureGeoLocation.code)
                if (departureCity != null) {
                    departureGeoLocation = departureCity
                }
            }

            Map<ProductStatus, BigDecimal> statusToFare = result.get(departureGeoLocation.toReference())
            if (statusToFare == null) {
                statusToFare = new HashMap<>()
                result.put(departureGeoLocation.toReference(), statusToFare)
            }

            if (!statusToFare.containsKey(ticket.status)) {
                statusToFare.put(ticket.status, BigDecimal.ZERO)
            }

            BigDecimal newFare =
                    statusToFare.get(ticket.status)
                            .add(ticket.price)

            statusToFare.put(ticket.status, newFare);
        }
    }

    nextRow()
    nextRow()
    nextColumn()
    text("Пункт вылета", "center-bold-border")

    nextColumn()
    text("Продажа")

    nextColumn()
    text("Возврат")

    for (Map.Entry<DictionaryReference<GeoLocation>, Map<ProductStatus, BigDecimal>> entry : result.entrySet()) {
        nextRow()
        nextColumn()
        text(entry.getKey()?.toString(LocaleHelper.RU_LOCALE), "left-border")

        nextColumn()

        BigDecimal sellFare
        if (entry.getValue().containsKey(ProductStatus.SELL)) {
            sellFare = entry.getValue().get(ProductStatus.SELL)
        } else {
            sellFare = BigDecimal.ZERO
        }
        number(sellFare, "right-border")

        nextColumn()

        BigDecimal refundFare
        if (entry.getValue().containsKey(ProductStatus.REFUND)) {
            refundFare = entry.getValue().get(ProductStatus.REFUND)
        } else {
            refundFare = BigDecimal.ZERO
        }
        number(refundFare)
    }

    nextRow()
    nextColumn()
    text("ИТОГО:", "center-bold-border")

    nextColumn()
    if (!result.isEmpty()) {
        formula("SUM(${cellIndex(-result.size(), 0)}:${cellIndex(-1, 0)})", "right-bold-border")
    } else {
        number(BigDecimal.ZERO)
    }

    nextColumn()
    if (!result.isEmpty()) {
        formula("SUM(${cellIndex(-result.size(), 0)}:${cellIndex(-1, 0)})", "right-bold-border")
    } else {
        number(BigDecimal.ZERO)
    }
}

page{"Реестр по аэропортам вылета"} {
    // Set fix width for amount of sheets
    fitWidth(1)

    // Set fix height for amount of sheets
    fitHeight(1)

    // Set portrait mode
    landscape(false)

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

    // Set scale
    scale(70)

    // Set preserve mode
    preserve(false)

    printHead()
    printTitle()
    printTickets()
}