//IMPORTS
import com.gridnine.xtrip.common.model.booking.ProductStatus
import com.gridnine.xtrip.common.model.booking.TicketType
import com.gridnine.xtrip.common.model.booking.TransportationType
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicket
import com.gridnine.xtrip.common.util.MiscUtil
import com.gridnine.xtrip.common.util.TextUtil
import com.gridnine.xtrip.common.util.LocaleUtil
import com.gridnine.xtrip.common.l10n.model.L10nStringHelper
import java.text.SimpleDateFormat

//CREATING STYLES
createStyle(name: 'title', h_alignment: 'CENTER', v_alignment: 'CENTER')
createStyle(name: 'titleH1', fontHeight: 17)
createStyle(name: 'titleH2', fontHeight: 14)
createStyle(name: 'header', h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight: 7)
createStyle(name: 'columnHeader', wrapText: true, parent: 'header')
createStyle(name: 'rowHeader', wrapText: true, parent: 'header')
createStyle(name: 'data', h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight: 7)
createStyle(name: 'dataText', parent: 'data')
createStyle(name: 'dataDate', format: 'm/d/yy', parent: 'data')
createStyle(name: 'dataNumber', h_alignment: 'RIGHT', format: '#,##0.00', parent: 'data')
createStyle(name: 'ahl', h_alignment: 'LEFT')
createStyle(name: 'ahc', h_alignment: 'CENTER')
createStyle(name: 'ahr', h_alignment: 'RIGHT')
createStyle(name: 'avt', v_alignment: 'TOP')
createStyle(name: 'avc', v_alignment: 'CENTER')
createStyle(name: 'avb', v_alignment: 'BOTTOM')
createStyle(name: 'aac', h_alignment: 'CENTER', v_alignment: 'CENTER')
createStyle(name: 'bold', fontBold: true)
createStyle(name: 'italic', fontItalic: true)
createStyle(name: 'bt', topBorder: 'THIN')
createStyle(name: 'bl', leftBorder: 'THIN')
createStyle(name: 'bb', bottomBorder: 'THIN')
createStyle(name: 'br', rightBorder: 'THIN')
createStyle(name: 'ba', topBorder: 'THIN', leftBorder: 'THIN', bottomBorder: 'THIN', rightBorder: 'THIN')
createStyle(name: 'grey25', foreground: 'GREY_25_PERCENT')
createStyle(name: 'red', fontColor: 'RED')
createStyle(name: 'locked', locked: true)
createStyle(name: 'wrap', wrapText: true)
createStyle(name: 'normal')

def issueDate = {
    SimpleDateFormat dateFormat = new SimpleDateFormat('dd/MM/yy')
    text(it?.issueDate ? dateFormat.format(it.issueDate) : "")
}

def blankOwner = {
    String result = EntityStorage.get()?.resolve(it?.blankOwner)?.getEntity()?.airline?.code
    text(result)
}

def status = {
    String result = it?.status
    text(result)
}

def validatingCarrier = {
    String result = it?.validatingCarrier?.caption
    text(result)
}

def carrierNumber = {
    String result = it?.validatingCarrierNumber
    text(result)
}

def ticketNumber = {
    String result = it?.ticketNumber
    text(result)
}

def equivalentFare = {
    BigDecimal result = MiscUtil.nonNull(it?.equivalentFare)
    if (it?.status == ProductStatus.REFUND || it?.status == ProductStatus.EXCHANGE) {
        result = MiscUtil.negate(result)
    }
    number(result)
}

def taxesSum = {
    BigDecimal result = MiscUtil.nonNull(it?.taxesSum)
    if (it?.status == ProductStatus.REFUND || it?.status == ProductStatus.EXCHANGE) {
        result = MiscUtil.negate(result)
    }
    number(result)
}

def penalty = {
    BigDecimal result = MiscUtil.nonNull(it?.penalty)
    number(result)
}

def clientFeeValue = {
    BigDecimal result = MiscUtil.nonNull(it?.clientFeeValue)
    if (it?.status == ProductStatus.REFUND || it?.status == ProductStatus.EXCHANGE) {
        result = MiscUtil.negate(result)
    }
    number(result)
}

def clientFopAmount = {
    formula("SUM(${cellIndex(0, -4)}:${cellIndex(0, -1)})")
}

def travelerName = {
    String result = it
    text(result)
}

def routeLine = {
    String result = it?.localizedRouteLine
    text(result)
}

def departureDate = {
    SimpleDateFormat dateFormat = new SimpleDateFormat('dd/MM/yy')
    text(it?.departureDate ? dateFormat.format(it.departureDate) : "")
}

def lastFlightDate = {
    SimpleDateFormat dateFormat = new SimpleDateFormat('dd/MM/yy')
    text(it?.lastFlightDate ? dateFormat.format(it.lastFlightDate) : "")
}

def comments = {
    String result = it?.comments ?: ''
    text(result)
}

def createHead = {
    def name = parameters?.params?.description?.caption
    def datePeriod = parameters.REPORT_PERIOD
    def client = parameters.CLIENT
    text(name ?: "", 'ahc|ba|titleH1', 16, 1)
    rowHeight(20)
    nextRow()
    text('Дата: ', 'ahl|ba|titleH2', 2, 1)
    2.times {nextColumn()}
    text(datePeriod, 'ahl|ba|titleH2', 14, 1)
    rowHeight(16)
    nextRow()
    text('Клиент: ', 'ahl|ba|titleH2', 2, 1)
    2.times {nextColumn()}
    text(client, 'ahl|ba|titleH2', 14, 1)
    nextRow()
    text("", 'ahl|ba|titleH2', 16, 1)
    nextRow()
}

def createBodyHead = {
    text('Дата выписки', 'bold|ahc|avc|wrap|ba')
    rowHeight(40)
    nextColumn()
    text('Владелец бланка')
    columnWidth(10)
    nextColumn()
    text('Статус')
    nextColumn()
    text('Валид. перевозчик')
    columnWidth(15)
    nextColumn()
    text('Р/К')
    columnWidth(6)
    nextColumn()
    text('Номера билетов')
    columnWidth(13)
    nextColumn()
    text('Сумма тарифа экв.')
    columnWidth(11)
    nextColumn()
    text('Сумма таксы')
    columnWidth(11)
    nextColumn()
    text('Сумма штрафа')
    columnWidth(11)
    nextColumn()
    text('Сумма сбора с клиента')
    columnWidth(11)
    nextColumn()
    text('Сумма оплаты клиента')
    columnWidth(11)
    nextColumn()
    text('Путешественник')
    columnWidth(25)
    nextColumn()
    text('Маршрут')
    columnWidth(40)
    nextColumn()
    text('Дата вылета')
    columnWidth(10)
    nextColumn()
    text('Дата последнего вылета')
    columnWidth(10)
    nextColumn()
    text('Комментарии')
    columnWidth(23)
}

def createBody = {
    int ticketsCount = 0

    Map<AirTicketsTemplateReportTicket, String> ticketMap = new HashMap<AirTicketsTemplateReportTicket, String>()

// Initialization
    tickets {
        if (parameters.ticketType && (TicketType.OWN == it.ticketType || TicketType.EXTERNAL == it.ticketType)) {

            String fName = EntityStorage.get()?.resolve(it?.travellerProfile)?.getEntity()?.firstName ?
                    L10nStringHelper.getValue(EntityStorage.get()?.resolve(it?.travellerProfile)?.getEntity()?.firstName, LocaleUtil.LOCALE_RU, false) : ""
            String lName = EntityStorage.get()?.resolve(it?.travellerProfile)?.getEntity()?.lastName ?
                    L10nStringHelper.getValue(EntityStorage.get()?.resolve(it?.travellerProfile)?.getEntity()?.lastName, LocaleUtil.LOCALE_RU, false) : ""
            String personName = ((fName ?: '') + " " + (lName ?: '')).trim()
            if (TextUtil.isBlank(personName)) {
                personName = it?.cyrillicName ?: it?.travellerName
            }

            ticketMap.put(it, personName)

        } else if (TicketType.OWN == it.ticketType) {

            String fName = EntityStorage.get()?.resolve(it?.travellerProfile)?.getEntity()?.firstName ?
                    L10nStringHelper.getValue(EntityStorage.get()?.resolve(it?.travellerProfile)?.getEntity()?.firstName, LocaleUtil.LOCALE_RU, false) : ""
            String lName = EntityStorage.get()?.resolve(it?.travellerProfile)?.getEntity()?.lastName ?
                    L10nStringHelper.getValue(EntityStorage.get()?.resolve(it?.travellerProfile)?.getEntity()?.lastName, LocaleUtil.LOCALE_RU, false) : ""
            String personName = ((fName ?: '') + " " + (lName ?: '')).trim()
            if (TextUtil.isBlank(personName)) {
                personName = it?.cyrillicName ?: it?.travellerName
            }

            ticketMap.put(it, personName)

        }
    }

// Sorting
    ticketMap = ticketMap.sort { a, b ->
        a.value <=> b.value ?: a.key.ticketNumber <=> b.key.ticketNumber
    }

    nextRow()
    setStyle('ba')

// Filling cells
    ticketMap.forEach { k, v ->
        rowAutoHeight()

        ticketsCount++

        issueDate(k)
        nextColumn()
        blankOwner(k)
        nextColumn()
        status(k)
        nextColumn()
        validatingCarrier(k)
        nextColumn()
        carrierNumber(k)
        nextColumn()
        ticketNumber(k)
        nextColumn()
        equivalentFare(k)
        nextColumn()
        taxesSum(k)
        nextColumn()
        penalty(k)
        nextColumn()
        clientFeeValue(k)
        nextColumn()
        clientFopAmount(k)
        nextColumn()
        travelerName(v)
        nextColumn()
        routeLine(k)
        nextColumn()
        departureDate(k)
        nextColumn()
        lastFlightDate(k)
        nextColumn()
        comments(k)
        nextRow()
    }

// Sums
    rowAutoHeight()
    text('Итого:', 'bold|avt|wrap|ba')
    nextColumn()
    5.times {
        text("")
        nextColumn()
    }
    5.times {
        formula("SUM(${cellIndex(-ticketsCount, 0)}:${cellIndex(-1, 0)})")
        nextColumn()
    }
    5.times {
        text("")
        nextColumn()
    }
}

page{'Реестр продаж'} {
    // Set fix width for amount of sheets
    fitWidth(1)

    // Set portrait mode
    landscape(true)

    // Set narrow margins
    margin(0.25, 0.25, 0.25, 0.25)

    // Set scale
    scale(70)

    // Set preserve mode
    preserve(false)

    createHead()
    createBodyHead()
    createBody()
}