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.entity.EntityStorage
import com.gridnine.xtrip.common.model.profile.Person
import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicket
import com.gridnine.xtrip.common.util.MiscUtil
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)

    12.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", 15, 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", 15, 1)
}

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

    nextColumn(); text("№ п/п", "center-center-border")
    nextColumn(); text("№ принятого" + "\n" + "к обмену авиабилета", "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" + "по авиабилету," + "\n" + "выданному" + "\n" + "в обмен", "center-center-border")
    nextColumn(); text("Сумма," + "\n" + "по авиабилету," + "\n" + "принятому" + "\n" + "для обмена", "center-center-border")
    nextColumn(); text("Доплата" + "\n" + "по тарифу", "center-center-border")
    nextColumn(); text("Доп. сбор", "center-center-border")
    nextColumn(); text("% ком", "center-center-border")
    nextColumn(); text("Ком. сбор", "center-center-border")
    nextColumn(); text("К перечислению", "center-center-border")
}

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

    int i = 0

    tickets { AirTicketsTemplateReportTicket ticket ->
        i++

        nextRow(); rowHeight(15)

        nextColumn()
        number(i, "center-center-border")

        nextColumn()
        text((ticket.isEticket() ? "Э " : "") + ticket.relatedTicketNumber ? ticket.relatedTicketNumber : "")

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

        nextColumn()
        text(ticket.crtRouteLine)

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

        nextColumn()
        text(ticket.relatedTicketFareBasisLine ? ticket.relatedTicketFareBasisLine : "")

        nextColumn()
        text((ticket.isEticket() ? "Э " : "") + ticket.ticketNumber ? ticket.ticketNumber : "")

        nextColumn()
        text(ticket.fareBasisLine)

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

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

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

        nextColumn()
        number(MiscUtil.sum(BigDecimal.ZERO, ticket.penalty, ticket.taxesSum))

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

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

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

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

    7.times {
        nextColumn()
    }

    4.times {
        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("")

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

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

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

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