import com.gridnine.xtrip.common.model.booking.BookingFile
import com.gridnine.xtrip.common.model.booking.ProductIndex
import com.gridnine.xtrip.common.model.booking.air.Commission
import com.gridnine.xtrip.common.model.booking.air.Product
import com.gridnine.xtrip.common.model.dict.ContractType
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.entity.parameters.EntityStorageSearchParameters
import com.gridnine.xtrip.common.model.helpers.AirProductHelper
import com.gridnine.xtrip.common.model.helpers.BookingHelper
import com.gridnine.xtrip.common.model.helpers.GeneralProductHelper
import com.gridnine.xtrip.common.model.profile.OrganizationIndex
import com.gridnine.xtrip.common.reports.model.AirTicketsTemplateReportTicket
import com.gridnine.xtrip.common.search.SearchCriterion
import com.gridnine.xtrip.common.search.SearchQuery

import java.text.SimpleDateFormat

//CREATING STYLES
createStyle(name: 'title',fontBold: true, h_span: 17, h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight:15)
createStyle(name: 'header',fontBold: true,  h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight:8, leftBorder:'MEDIUM', rightBorder:'MEDIUM', topBorder:'MEDIUM', bottomBorder:'MEDIUM', wrapText: true)
createStyle(name: 'data',fontBold: false,  h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight:8, leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN')
createStyle(name: 'textData',parent: 'data')
createStyle(name: 'numberData',parent: 'data',h_alignment: 'RIGHT', format: '#,##0.00')
createStyle(name: 'dateData',parent: 'data',h_alignment: 'RIGHT',format: 'm/d/yy')
createStyle(name: 'subtotalTitle', parent: 'header', h_span: 6, h_alignment: 'RIGHT', fontBold: true, format: '#,##0.00')
createStyle(name: 'subtotalNumber',parent: 'subtotalTitle',  h_span: 1)
createStyle(name: 'totalTitle', parent: 'subtotalTitle', h_span: 3, format: '#,##0.00')
createStyle(name: 'totalNumber',parent: 'totalTitle')
createStyle(name: 'datePeriod',fontBold: true, h_span: 11, h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight:10 )
createStyle(name: 'subTitleStyle', fontBold: true, h_span: 3, h_alignment: 'LEFT', v_aligment: 'CENTER', fontHeight:10 )
createStyle(name: 'subTitleValueStyle', fontBold: true, h_span: 3, h_alignment: 'LEFT', v_aligment: 'CENTER', fontHeight: 10)
createStyle(name: 'numberStyle', fontBold: false, h_alignment: 'RIGHT', v_alignment: 'CENTER', fontHeight: 10 )
createStyle(name: 'sumTitle', leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', h_span: 9, h_alignment: 'LEFT', fontBold: true)
createStyle(name: 'sumNumber',fontBold: true,  h_alignment: 'RIGHT', v_alignment: 'CENTER', fontHeight:8, leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', format: '#,##0.00')
createStyle(name: 'mainSignTitle', h_span: 6, h_alignment: 'LEFT', fontBold: true, fontHeight:8)
createStyle(name: 'subSignTitle', h_span: 6, h_alignment: 'LEFT', fontBold: false, fontHeight:8)
createStyle(name: 'fioStyle', h_span: 4, h_alignment: 'CENTER', fontBold: false, v_alignment: 'CENTER', fontHeight:8)
createStyle(name: 'signStyle', h_span: 7, h_alignment: 'CENTER', fontBold: false)
createStyle(name: 'endTextStyle', h_span: 17, h_alignment: 'LEFT', fontBold: false, fontHeight:8)


def periodBeginParameter = parameters['key-report-params']?.periodBegin;
def periodEndParameter = parameters['key-report-params']?.periodEnd;
def agencyName = parameters['key-report-params']?.agency;
def bcoOwner = parameters['BLANK_OWNER'];

def paymentType = ' ';
if( parameters['paymentType'] != null)
  paymentType = parameters['paymentType'];
def reportDate = parameters['REPORT_DATE']
def corpClient = parameters['CLIENT']
String corpClientStr = corpClient;
if(corpClientStr == null || corpClientStr.isEmpty())
 {
     error("Не задан клиент")
     //throw new Exception("Не задан клиент")
     return
 }
SearchQuery query = new SearchQuery();
query
        .getCriteria()
        .getCriterions()
        .add(
        SearchCriterion.ilike(
        OrganizationIndex.Property.shortName.name(),
        "%$corpClient%"));
    List<OrganizationIndex> data = EntityStorage.get().search(

            OrganizationIndex.class, query,
            new EntityStorageSearchParameters().noCache(true)).getData();
def longName = "Не найдено имя";
if(data != null && data.size() > 0)
{
    longName = data.get(0).getName();
}
def format = new SimpleDateFormat('dd.MM.yy')
//ADDITIONAL FUNCTIONS
def sum = {BigDecimal... values ->
    BigDecimal result = BigDecimal.ZERO
    values.each {
        if(it != null){
            result = result.add(it)
        }
    }
    return result
}
def multi = {BigDecimal... values ->
    BigDecimal result = BigDecimal.ONE
    values.each {
        if(it == null){
            result == BigDecimal.ZERO
            return
        }
        result = result.multiply(it)
    }
    return result
}


def priceFactor = {def it->
    return ('REFUND'.equals(it.status?.name()) ||'EXCHANGE'.equals(it.status?.name()))? BigDecimal.ONE.negate(): BigDecimal.ONE
}
def fare =  {def it->
    return multi(BigDecimal.ONE, it.equivalentFare)
}
def taxes =  {def it->
    return multi(BigDecimal.ONE, it.taxesSum)
}
def penalty =  {def it->
    return it.penalty == null? BigDecimal.ZERO: it.penalty
}

def total =  {def AirTicketsTemplateReportTicket ticket, BigDecimal clientCommission ->
    BigDecimal total = BigDecimal.ZERO
    if(fare(ticket) != null)
    {
      total = total.add(fare(ticket))
    }
    if(clientCommission != null)
    {
      total = total.subtract(clientCommission)
    }
    if(ticket.getTaxes() != null)
    {
        BigDecimal agsTaxes = BigDecimal.ZERO;
        if(ticket.getTaxesSum() != null)
        {
            agsTaxes = ticket.getTaxesSum();
            if(ticket.getFuelChargeAmount() != null)
            {
                agsTaxes = agsTaxes.subtract(ticket.getFuelChargeAmount());
            }
            if(ticket.getRuTaxAmount() != null)
            {
                agsTaxes = agsTaxes.subtract(ticket.getRuTaxAmount());
            }
        }
        total = total.add(agsTaxes)
        total = total.add(ticket.getFuelChargeAmount())
        total = total.add(ticket.getRuTaxAmount())
        total = total.subtract(penalty(ticket))     
    }
    return total
}

def bspCommissionAmount =  {def it->
    return multi(priceFactor(it), it.bspCommissionEquivalentAmount)
}


//REPORT
page{"ВОЗВРАТ"}{
    //TITLE
    rowHeight(30)
    setStyle('title')
    text("Возврат А/Б");
    //HEADER
    nextRow()
    text("$longName")
    nextRow()
    rowHeight(20)
    text('Владелец БСО', 'subTitleStyle')
    nextColumn()
    text("$bcoOwner", 'subTitleValueStyle')
    nextColumn()
    text("Период отчетности с " + format.format(periodBeginParameter) + " по " + format.format(periodEndParameter), 'datePeriod')
    nextRow()
    text('Код взаиморасчетов', 'subTitleStyle')
    nextColumn()
    text("$paymentType", 'subTitleValueStyle')
    nextRow()
    text("Регион перевозок", 'subTitleStyle')
    nextColumn()
    text("ВСЕ", 'subTitleValueStyle')
    nextRow()
    rowHeight(40)
    columnWidth(7)
    setStyle('header')
    text('№ п/п')
    nextColumn()
    columnWidth(9)
    text('Вид БСО')
    nextColumn()
    columnWidth(14)
    text('№ билета системный')
    nextColumn()
    columnWidth(10)
    text('Дата продажи')
    nextColumn()
    columnWidth(10)
    text('Дата возврата')
    nextColumn()
    columnWidth(4)
    text('АК')
    nextColumn()
    columnWidth(10)
    text('Дата вылета')
    nextColumn()
    columnWidth(10)
    text('Базовый тариф')
    nextColumn()
    columnWidth(18)
    text('Маршрут')
    nextColumn()
    columnWidth(9)
    text('Тариф')
    nextColumn()
    columnWidth(5)
    text('% ком')
    nextColumn()
    columnWidth(11)
    text('Комиссия')
    nextColumn()
    columnWidth(11)
    text('АГС')
    nextColumn()
    columnWidth(11)
    text('ТН')
    nextColumn()
    columnWidth(11)
    text('Такса РУ/ТТКП')
    nextColumn()
    columnWidth(11)
    text('Штраф')
    nextColumn()
    columnWidth(11)
    text('Итого')

    def rowNumber = 1
    //DATA
    nextRow()
    rowHeight(10)
    String fareRow = cellIndex(0, 9)
    String comissionRow = cellIndex(0, 11)
    String agsRow = cellIndex(0,12)
    String thRow = cellIndex(0,13)
    String ttkpRow = cellIndex(0,14)
    String penaltyRow = cellIndex(0, 15)
    String totalRow = cellIndex(0, 16)
    tickets{ AirTicketsTemplateReportTicket ticket ->
        
        text("$rowNumber",'textData')
        nextColumn()
        text(ticket.getBlankType().toString(),'textData')
        nextColumn()
        text(ticket.ticketNumber?.toString(),'textData')
        nextColumn()
        date(ticket.issueDate,'dateData')
        nextColumn()
        date(ticket.issueDate,'dateData')
        nextColumn()
        text(ticket.validatingCarrier?.code?.toString(),'textData')
        nextColumn()
        date(ticket.departureDate,'dateData')
        nextColumn()
        text(ticket.fareBasisLine,'textData')
        nextColumn()
        text(ticket.routeLine,'textData')
        nextColumn()
        number(fare(ticket),'numberData')
        nextColumn()
        //Достаем комиссию клиента
        query = new SearchQuery();
        query
                .getCriteria()
                .getCriterions()
                .add(
                SearchCriterion.eq("navigationKey",
                ticket.getUid()));
        List<ProductIndex> pi =
                EntityStorage.get().search(ProductIndex.class, query).getData();
        BigDecimal clientCommission = BigDecimal.ZERO;
        BigDecimal clientCommissionRate = BigDecimal.ZERO;
        if(pi != null && !pi.empty)
        {
            ProductIndex productIndex = pi.get(0);
            BookingFile bookingFile = (BookingFile)EntityStorage.get().resolve(productIndex.getSource()).getEntity();
            if(bookingFile != null)
            {
                Product product = (Product)BookingHelper.findProductByUid(productIndex.getNavigationKey(), bookingFile);
                 Collection<Commission> clientComissions = GeneralProductHelper
                .filterCommissions(GeneralProductHelper.getUnmodifiableCommissions(
                 product, ContractType.CLIENT),
                 GeneralProductHelper.commissionPropertyTypes)
                clientCommission = AirProductHelper
                      .calculateCommissionsEquivalentValue(clientComissions);
                if(clientCommission == null)
                   clientCommission = BigDecimal.ZERO;
                clientCommissionRate = AirProductHelper.calculateCommissionsRate(clientComissions, false)
                if(clientCommissionRate == null)
                  clientCommissionRate = BigDecimal.ZERO;
            }
        }
        number(clientCommissionRate,'numberData')
        nextColumn()
        number(clientCommission,'numberData')
        nextColumn()
        BigDecimal agsTaxes = BigDecimal.ZERO;
        if(ticket.getTaxesSum() != null)
        {
            agsTaxes = ticket.getTaxesSum();
            if(ticket.getFuelChargeAmount() != null)
            {
                agsTaxes = agsTaxes.subtract(ticket.getFuelChargeAmount());
            }
            if(ticket.getRuTaxAmount() != null)
            {
                agsTaxes = agsTaxes.subtract(ticket.getRuTaxAmount());
            }
        }
        number(agsTaxes,'numberData')
        nextColumn()
        number(ticket?.getFuelChargeAmount(),'numberData')
        nextColumn()
        number(ticket?.getRuTaxAmount(),'numberData')
        nextColumn()
        number(penalty(ticket),'numberData')
        nextColumn()
        number(total(ticket, clientCommission),'numberData')
        nextRow()
        rowNumber++;
    }
    if(rowNumber > 1)
    {
        text('Итого по странице','sumTitle')
        nextColumn()
        formula("SUM(${fareRow}:${cellIndex(-1,0)})",'sumNumber')
        nextColumn()
        text(' ', 'sumNumber')
        nextColumn()
        formula("SUM(${comissionRow}:${cellIndex(-1,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${agsRow}:${cellIndex(-1,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${thRow}:${cellIndex(-1,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${ttkpRow}:${cellIndex(-1,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${penaltyRow}:${cellIndex(-1,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${totalRow}:${cellIndex(-1,0)})",'sumNumber')
        nextRow()

        text('Итого по реестру','sumTitle')
        nextColumn()
        formula("SUM(${fareRow}:${cellIndex(-2,0)})",'sumNumber')
        nextColumn()
        text(' ', 'sumNumber')
        nextColumn()
        formula("SUM(${comissionRow}:${cellIndex(-2,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${agsRow}:${cellIndex(-2,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${thRow}:${cellIndex(-2,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${ttkpRow}:${cellIndex(-2,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${penaltyRow}:${cellIndex(-2,0)})",'sumNumber')
        nextColumn()
        formula("SUM(${totalRow}:${cellIndex(-2,0)})",'sumNumber')
    }
    nextRow()
    nextRow()
    nextRow()
    text("Исполнительный директор", 'mainSignTitle')
    nextColumn()
    text("ФИО", 'fioStyle')
    nextColumn()
    text("___________________________________________________________________", 'signStyle')
    nextRow()
    nextRow()
    nextRow()
    text("Главный бухгалтер", 'mainSignTitle')
    nextColumn()
    text("ФИО", 'fioStyle')
    nextColumn()
    text("___________________________________________________________________", 'signStyle')
    nextRow()
    nextRow()
    nextRow()
    text("Исполнитель", 'subSignTitle')
    nextColumn()
    text("ФИО", 'fioStyle')
    nextColumn()
    text("___________________________________________________________________", 'signStyle')
    nextRow()
    nextRow()
    nextRow()   


}



