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 printHead() {
    rowHeight(9)
    columnWidth(2)

    nextRow()
    nextColumn()
    rowHeight(15)
    text("Реестр продажи авиабилетов на бланках ТКП", "center-bold", 13, 1)
}

def printTitle() {
    nextRow()
    nextRow()
    nextColumn()
    text("Авиакомпания: ЗАО \"ИрАэро\"", "left", 13, 1)

    nextRow()
    nextColumn()
    text("Агентство: " + parameters['AGENCY_NAME'], "left", 13, 1)

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy г.")
    String agencyAgreementNumber = parameters['agency_agreement_number']
    Date agencyAgreementDate = (Date) parameters['agency_agreement_date']

    nextRow()
    nextColumn()
    text("Агентское соглашение: " +
            (TextUtil.nonBlank(agencyAgreementNumber) ? agencyAgreementNumber : "_______________") +
            " от " +
            (agencyAgreementDate ? sdf.format(agencyAgreementDate) : "________")
            , "left", 13, 1)

    def periodBeginParameter = parameters['key-report-params']?.periodBegin
    def periodEndParameter = parameters['key-report-params']?.periodEnd

    nextRow()
    nextColumn()
    text("Отчетный период с " +
            (periodBeginParameter ? sdf.format(periodBeginParameter) : "") +
            " по " +
            (periodEndParameter ? sdf.format(periodEndParameter) : ""),
            "left", 13, 1)
}

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

    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("Сумма тарифа", "center-center-border")
    nextColumn();text("% ком", "center-center-border")
    nextColumn();text("Сумма" + "\n" + "комиссии", "center-center-border")
    nextColumn();text("Такса РУ", "center-center-border")
    nextColumn();text("Такса YQ", "center-center-border")
    nextColumn();text("Такса ТКП", "center-center-border")
    nextColumn();text("Сумма к" + "\n" + "перечислению", "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-border")

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

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

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

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

        nextColumn()
        text(ticket.crtRouteLine)

        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 ruTaxes = BigDecimal.ZERO
        BigDecimal yqTaxes = BigDecimal.ZERO
        BigDecimal zzTaxes = BigDecimal.ZERO

        for (Tax tax : ticket.taxes) {
            if (tax.equivalentAmount != null) {
                if ("RU".equalsIgnoreCase(tax.code)) {
                    ruTaxes = ruTaxes.add(tax.equivalentAmount)
                }
                if ("YQ".equalsIgnoreCase(tax.code)) {
                    yqTaxes = yqTaxes.add(tax.equivalentAmount)
                }
                if ("ZZ".equalsIgnoreCase(tax.code)) {
                    zzTaxes = zzTaxes.add(tax.equivalentAmount)
                }
            }
        }

        nextColumn()
        number(ruTaxes)

        nextColumn()
        number(yqTaxes)

        nextColumn()
        number(zzTaxes)

        nextColumn()
        number(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)
    }

    nextColumn()
    text("")

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

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

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

    nextColumn()
    if (count() > 0) {
        formula("SUM(${cellIndex(-count(), 0)}:${cellIndex(-1, 0)})")
    } else {
        number(BigDecimal.ZERO)
    }
    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()

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

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