import com.gridnine.xtrip.common.l10n.model.LocaleHelper
import com.gridnine.xtrip.common.model.booking.OperationBatch
import com.gridnine.xtrip.common.model.dict.GdsName
import com.gridnine.xtrip.common.model.dict.ProductCategory
import com.gridnine.xtrip.common.model.profile.GdsReference
import com.gridnine.xtrip.common.model.profile.SalesPoint
import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicket
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.profile.Person

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: "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 printTitle() {
    rowHeight(9)
    columnWidth(2)

    nextRow()
    nextColumn()
    rowHeight(20)

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

    text("Реестр операций на бланках КАП, проведённых не в Камчатском филиале",
            "center-center-bold", 6, 1)

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

def printHeader() {
    nextRow()
    rowHeight(15)
    nextRow()
    nextColumn()

    nextColumn(); text("Дата отчёта", "center-bold-border")
    nextColumn(); text("Касса", "center-bold-border")
    nextColumn(); text("Номер документа", "center-bold-border")
    nextColumn(); text("Наименование операции", "center-bold-border")
}

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

    tickets { AirTicketsTemplateReportTicket ticket ->
        if (isKamchatkaRegion(ticket)) {
            return
        }

        nextRow()
        nextColumn()
        nextColumn()
        text(ticket.issueDate ? sdf.format(ticket.issueDate) : "", "center-border")

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

        nextColumn()
        String number =
                (ticket.validatingCarrierNumber ? ticket.validatingCarrierNumber + " " : "") +
                        (ticket.ticketNumber ? ticket.ticketNumber : "")
        text(number)

        nextColumn()
        if (ticket.operationBatch) {
            if (ticket.productCategory == ProductCategory.AIR) {
                switch (ticket.operationBatch) {
                    case OperationBatch.SELL:
                        text("Продажа авиаперевозки")
                        break
                    case OperationBatch.VOID:
                        text("Аннулирование авиаперевозки")
                        break
                    case OperationBatch.REFUND:
                        text("Возврат авиаперевозки")
                        break
                    case OperationBatch.EXCHANGE:
                        text("Обмен авиаперевозки")
                        break
                    default:
                        text(ticket.operationBatch.toString(LocaleHelper.RU_LOCALE))
                }
            } else {
                text(ticket.operationBatch.toString(LocaleHelper.RU_LOCALE))
            }
        }
    }
}

boolean isKamchatkaRegion(AirTicketsTemplateReportTicket ticket) {
    String kamchatkaSalesPointString = parameters['kamchatkaSalesPoints']
    if (!kamchatkaSalesPointString) {
        return false
    }

    def kamchatkaSalesPoints = Arrays.asList(kamchatkaSalesPointString.split(","))

    SalesPoint sp = EntityStorage.get().resolve(ticket.salesPoint)?.entity
    if (!sp) {
        return false
    }

    return kamchatkaSalesPoints.contains(sp.code)
}

def setAutoWidth() {
    nextRow()
    nextColumn()

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

page{"Реестр операций на бланках КАП"} {
    printTitle()
    printHeader()
    printTickets()
    setAutoWidth()
}