import com.gridnine.xtrip.common.l10n.model.LocaleHelper
import com.gridnine.xtrip.common.l10n.model.PersonalLocalizableNameUtil
import com.gridnine.xtrip.common.model.EntityContainer
import com.gridnine.xtrip.common.model.EntityReference
import com.gridnine.xtrip.common.model.booking.air.Tax
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.profile.Person
import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicket
import com.gridnine.xtrip.common.util.TextUtil

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: "center-center-bold", h_alignment: "CENTER", v_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: "left-center-bold-border", h_alignment: "LEFT", v_alignment: "CENTER", 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)
createStyle(name: "center-center-border", h_alignment: "CENTER", v_alignment: "CENTER", leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)
createStyle(name: "center-border-number", h_alignment: "CENTER", leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)
createStyle(name: "center-center-border-number", h_alignment: "CENTER", v_alignment: "CENTER", leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)

def printTitle() {
    rowHeight(9); columnWidth(2)
    nextRow(); rowHeight(45)

    11.times {
        nextColumn()
    }
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy г.")
    String agencyAgreementNumber = parameters['agency_agreement_number']
    Date agencyAgreementDate = (Date) parameters['agency_agreement_date']
    text("Приложение № 3" + "\n" + "к Агентскому соглашению № " +
            (TextUtil.nonBlank(agencyAgreementNumber) ? agencyAgreementNumber : "_______________")
            + "\n" + " от " +
            (agencyAgreementDate ? sdf.format(agencyAgreementDate) : "________"), "center", 4, 1)

    nextRow(); rowHeight(15)
    nextColumn()
    text("Реестр возврата авиабилетов " + parameters['AGENCY_NAME'], "center-bold", 14, 1)

    nextRow()
    nextColumn()
    def periodBeginParameter = parameters['key-report-params']?.periodBegin
    def periodEndParameter = parameters['key-report-params']?.periodEnd
    text("за период с " +
            (periodBeginParameter ? sdf.format(periodBeginParameter) : "") +
            " по " +
            (periodEndParameter ? sdf.format(periodEndParameter) : ""),
            "center", 14, 1)
}

def printHeader() {
    nextRow(); nextRow(); rowHeight(45)

    nextColumn(); text("№ авиабилета", "center-center-border")
    nextColumn(); text("Дата продажи", "center-center-border")
    nextColumn(); text("Дата возврата", "center-center-border")
    nextColumn(); text("Маршрут", "center-center-border")
    nextColumn(); text("№ рейса", "center-center-border")
    nextColumn(); text("Дата вылета", "center-center-border")
    nextColumn(); text("Код тарифа", "center-center-border")
    nextColumn(); text("Сумма возврата" + "\n" + "по тарифу", "center-center-border")
    nextColumn(); text("% ком", "center-center-border")
    nextColumn(); text("Сумма комиссии," + "\n" + "подлежащая" + "\n" + "возврату", "center-center-border")
    nextColumn(); text("Сумма" + "\n" + "возврата" + "\n" + "по прочим сборам", "center-center-border")
    nextColumn(); text("Сумма" + "\n" + "возврата" + "\n" + "по сбору YQ", "center-center-border")
    nextColumn(); text("Штраф", "center-center-border")
    nextColumn(); text("Сумма возврата," + "\n" + "удерживаемая" + "\n" + "с перевозчика", "center-center-border")
}

def printTickets() {
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy")

    tickets { AirTicketsTemplateReportTicket ticket ->
        nextRow(); rowHeight(15)

        nextColumn()
        text((ticket.eticket ? "Э " : "") + ticket.ticketNumber ? ticket.ticketNumber : "", "center-center-border")

        nextColumn()
        text(ticket.relatedTicketIssueDate ? sdf.format(ticket.relatedTicketIssueDate) : "")

        nextColumn()
        text(ticket.issueDate ? sdf.format(ticket.issueDate) : "")

        nextColumn()
        text(ticket.crtRouteLine)

        nextColumn()
        text(TextUtil.join(", ", new LinkedHashSet(ticket.flightNumbers)))

        nextColumn()
        text(ticket.departureDate ? sdf.format(ticket.departureDate) : "")

        nextColumn()
        text(ticket.fareBasisLine)

        nextColumn()
        number(ticket.equivalentFare ? ticket.equivalentFare : BigDecimal.ZERO, "center-center-border-number")

        nextColumn()
        number(ticket.vendorCommissionRate ? ticket.vendorCommissionRate : BigDecimal.ZERO)

        nextColumn()
        number(ticket.vendorCommissionValue ? ticket.vendorCommissionValue : BigDecimal.ZERO)

        BigDecimal otherTaxes = BigDecimal.ZERO
        BigDecimal yqTaxes = BigDecimal.ZERO

        for (Tax tax : ticket.taxes) {
            if (tax.equivalentAmount != null) {
                if ("YQ".equalsIgnoreCase(tax.code)) {
                    yqTaxes = yqTaxes.add(tax.equivalentAmount);
                } else {
                    otherTaxes = otherTaxes.add(tax.equivalentAmount)
                }
            }
        }

        nextColumn()
        number(otherTaxes)

        nextColumn()
        number(yqTaxes)

        nextColumn()
        number(ticket.penalty)

        nextColumn()
        number(ticket.price ? ticket.price : BigDecimal.ZERO)
    }

    nextRow()
    nextColumn()
    text("Итого:", "left-center-bold-border", 7, 1)

    nextColumn()
    nextColumn()
    nextColumn()
    nextColumn()
    nextColumn()
    nextColumn()
    nextColumn()
    if (count() > 0) {
        formula("SUM(${cellIndex(-count(), 0)}:${cellIndex(-1, 0)})", "center-center-border-number")
    } else {
        number(BigDecimal.ZERO, "center-center-border-number")
    }

    nextColumn()
    text("")

    5.times {
        nextColumn()
        if (count() > 0) {
            formula("SUM(${cellIndex(-count(), 0)}:${cellIndex(-1, 0)})")
        } else {
            number(BigDecimal.ZERO)
        }
    }
}

def printAuthor() {
    EntityReference<Person> authorRef = (EntityReference<Person>) parameters['report_author']
    EntityContainer<Person> authorCont = EntityStorage.get().resolve(authorRef)

    String authorName =
            authorCont ? PersonalLocalizableNameUtil.buildFullName(
                    authorCont.entity, true, LocaleHelper.RU_LOCALE, false) : "___________"

    nextRow(); rowHeight(60); nextRow(); nextColumn(); rowHeight(60)
    text("М.П." + "\n" + "\nОтчет составил:  ____________________ (" + authorName + ")", "left", 6, 1)

}

def setAutoWidth() {
    nextRow()
    rowAutoHeight()

    14.times {
        nextColumn()
        columnAutoWidth()
    }
}

page{parameters['title']} {
    printTitle()
    printHeader()
    printTickets()
    printAuthor()
    setAutoWidth()
}