import com.gridnine.xtrip.common.l10n.model.LocaleHelper
import com.gridnine.xtrip.common.model.dict.GdsName
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.profile.GdsReference
import com.gridnine.xtrip.common.model.profile.Person
import com.gridnine.xtrip.common.model.system.PaymentType
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", h_alignment: "CENTER", v_alignment: "CENTER")
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", format: '0.00', h_alignment: "CENTER", leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)
createStyle(name: "center-center-border-number", format: '0.00', h_alignment: "CENTER", v_alignment: "CENTER", leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', wrapText: true)

def printHead() {
    rowHeight(30)
    columnWidth(2)

    nextRow()
    rowHeight(30)
    9.times {
        nextColumn()
    }
    text("Форма №2", "center-center-bold", 4, 1)
}

def printTitle() {
    nextRow(); rowHeight(15)
    nextRow(); nextColumn()

    text("Реестр продажи авиаперевозок", "center-center-bold", 13, 1)

    nextRow(); nextColumn()

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

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

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

    nextColumn();text("№" + "\n" + "п/п", "center-center-border")
    nextColumn();text("№ авиабилета")
    nextColumn();text("Дата продажи")
    nextColumn();text("Рейс")
    nextColumn();text("Дата вылета")
    nextColumn();text("Маршрут")
    nextColumn();text("Валидатор" + "\n" + "кассира")
    nextColumn();text("Сумма тарифа")
    nextColumn();text("Код тарифа")
    nextColumn();text("% льготы")
    nextColumn();text("Сборы")
    nextColumn();text("Комиссия")
    nextColumn();text("Форма оплаты")
}

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.validatingCarrierNumber ? ticket.validatingCarrierNumber + " " : "") +
                (ticket.ticketNumber ? ticket.ticketNumber : ""))

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

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

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

        nextColumn()
        text(ticket.crtRouteLine)

        nextColumn()
        String agentCode = ""
        Person agent = EntityStorage.get().resolve(ticket.agent)?.getEntity()
        if (agent != null) {
            for (GdsReference ref : agent.getGdsReferences()) {
                if (ref.getGdsName() == GdsName.SIRENA) {
                    agentCode = ref.getReference()
                    break;
                }
            }
        }
        text(agentCode)

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

        nextColumn()
        text(ticket.fareBasisLine, "center-center-border")

        nextColumn()
        text("")

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

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

        nextColumn()
        Set<String> paymentTypes = new LinkedHashSet<>()
        for (PaymentType type : ticket.paymentTypes) {
            if (type != null) {
                paymentTypes.add(type.toString(LocaleHelper.RU_LOCALE))
            }
        }
        text(TextUtil.join(", ", paymentTypes), "center-center-border")
    }

    nextRow()
    nextColumn()
    text("Общий итог:", "left-center-bold-border", 7, 1)

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

    2.times {
        nextColumn()
        text("")
    }

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

    nextColumn()
    text("")
}

def printAccountant() {
    nextRow(); rowHeight(60);
    nextRow(); nextColumn(); nextColumn(); rowHeight(60)
    text("Главный бухгалтер ___________________________", "left", 4, 1)

}

def setAutoWidth() {
    nextRow()
    rowAutoHeight()

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

page{"Реестр продажи авиаперевозок"} {
    printHead()
    printTitle()
    printHeader()
    printTickets()
    printAccountant()
    setAutoWidth()
}