package com.gridnine.xtrip.server.reports.templates

import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;

import com.gridnine.xtrip.common.l10n.model.LocaleHelper;
import com.gridnine.xtrip.common.l10n.model.PersonalLocalizableNameUtil;
import com.gridnine.xtrip.common.model.helpers.BillingTransactionHelper;
import com.gridnine.xtrip.common.model.helpers.ProfileHelper;
import com.gridnine.xtrip.common.model.system.BillingTransactionCategory;
import com.gridnine.xtrip.common.model.system.BillingTransactionStatus;
import com.gridnine.xtrip.common.model.system.MetadataKey;
import com.gridnine.xtrip.common.model.entity.EntityStorage;
import com.gridnine.xtrip.common.vip.reports.AgencyFilter;
import com.gridnine.xtrip.common.vip.VIPHelper;

import com.gridnine.xtrip.common.util.MiscUtil
import com.gridnine.xtrip.common.util.CollectionUtil
import com.gridnine.xtrip.common.model.helpers.SystemHelper

import com.gridnine.xtrip.common.model.profile.BlockPeriods;
import com.gridnine.xtrip.common.model.profile.Organization;
import com.gridnine.xtrip.common.model.profile.vip.CuratorRole

def cell = { value ->
    if (value instanceof Number)
        number(value, 'numberData')
    else if (value instanceof Date)
        date(value, 'dateData')
    else
        text(value, 'textData')
}

def getName = { ref ->
    def ct = EntityStorage.get().resolve(ref)
    return ct != null ? PersonalLocalizableNameUtil.buildFullName(ct.entity, true, LocaleHelper.getCurrentLocale(), false) : null
}

//CREATING STYLES
createStyle(name: 'title',fontBold: true, h_span: 17, h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight:20)
createStyle(name: 'metadataTitle',fontBold: true, h_span: 2, h_alignment: 'RIGHT', v_alignment: 'CENTER', fontHeight:10)
createStyle(name: 'metadataValue', parent: 'metadataTitle', h_span: 10, fontBold: false, h_alignment: 'LEFT')
createStyle(name: 'metadataDateValue', parent: 'metadataValue', format: 'm/d/yy')
createStyle(name: 'header',fontBold: false,  h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight:10, leftBorder:'MEDIUM', rightBorder:'MEDIUM', topBorder:'MEDIUM', bottomBorder:'MEDIUM', wrapText: true)
createStyle(name: 'header2',parent: 'header',  h_span: 2)
createStyle(name: 'data',fontBold: false,  h_alignment: 'CENTER', v_alignment: 'CENTER', fontHeight:10, leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN')
createStyle(name: 'textData',parent: 'data', wrapText: true)
createStyle(name: 'numberData',parent: 'data',h_alignment: 'RIGHT')
createStyle(name: 'dateData',parent: 'data',h_alignment: 'CENTER',format: 'm/d/yy')
createStyle(name: 'totalTitle', parent: 'header', fontBold: true)
createStyle(name: 'totalNumber',parent: 'totalTitle',h_alignment: 'RIGHT')

def es = EntityStorage.get()

def endDate = MiscUtil.setDayEndTime(parameters.date?:new Date())
def agency;
if (parameters['subagency'] != null) {
    agency = parameters['subagency']
} else if (parameters['agency'] == AgencyFilter.EUROCONTACT) {
    agency = VIPHelper.getEurocontactProfile()
} else if (parameters['agency'] == AgencyFilter.VIP) {
    agency = VIPHelper.getVIPServiceProfile()
} else if (parameters['agency'] == AgencyFilter.VIPCONNECT) {
    agency = VIPHelper.getVipConnectProfile()
} else {
    agency = null
}
def employee = getName(parameters['employee'])

text('Сводный баланс (задолженности)', 'title')
nextRow()
rowHeight(20)
text("дата формирования отчета ${new java.text.SimpleDateFormat('dd.MM.yyyy').format(endDate)} (включительно)", 'metadataValue');nextColumn()
nextRow()
rowHeight(13)
text(employee?:'Все сотрудники', "metadataValue");
nextRow()

rowHeight(30)
text('№ п/п', 'header');nextColumn()
text('Субагент', 'header');columnWidth(30);nextColumn()
text('Код СОФИ', 'header');columnWidth(20);nextColumn()
text('Кредит', 'header');columnWidth(20);nextColumn()
text('Баланс (сумма задолженности)', 'header');columnWidth(20);nextColumn()
text('Дата установки блокировки', 'header');columnWidth(20);nextColumn()
text('Финансовый куратор', 'header');columnWidth(20);nextColumn()
text('Менеджер по привлечению', 'header');columnWidth(20);nextColumn()
text('Менеджер поддержки', 'header');columnWidth(20);nextColumn()

def totalBalance = 0

def data = []
tickets.each { index ->
    def subagencyReference = index.source
    def subagencyContainer = es.resolve(subagencyReference);
    def subagency = subagencyContainer.entity

    def subagencyName = subagency.fullName.toString()
    def sofiCode = SystemHelper.findMetadataAsString(subagency.metadata, MetadataKey.SOFI_CODE)?:subagency.code

    def balance = BillingTransactionHelper.calculateBillingTransactionsSum(null, subagencyReference, agency, null, null, BillingTransactionStatus.ACTIVE, null, endDate)
    if (balance) {
        balance = balance.setScale(2, RoundingMode.HALF_UP)
        totalBalance = totalBalance + balance
    }

    def creditInfo = ProfileHelper.getOrganizationCreditLimit(subagencyReference, agency);
    def credit = creditInfo ? ProfileHelper.getCreditAmount(creditInfo) : 0

    def blockDate = MiscUtil.clearTime(subagency.issueBlockPeriods.find{ null == it.endDate && it.startDate != null }?.startDate)
    if (null == blockDate) {
        return
    }
        
    def finance = CollectionUtil.collectionToString(subagency.curators.findAll{ CuratorRole.FINANCE == it.role && MiscUtil.isBetween(it.dateBegin, it.dateEnd, endDate) }.collect { getName(it.curator) }, ', ', false)
    def manager = CollectionUtil.collectionToString(subagency.curators.findAll{ CuratorRole.MANAGER == it.role && MiscUtil.isBetween(it.dateBegin, it.dateEnd, endDate) }.collect { getName(it.curator) }, ', ', false)
    def coordinator = CollectionUtil.collectionToString(subagency.curators.findAll{ CuratorRole.COORDINATOR == it.role && MiscUtil.isBetween(it.dateBegin, it.dateEnd, endDate) }.collect { getName(it.curator) }, ', ', false)

    def row = []
    row.add(subagencyName)
    row.add(sofiCode)
    row.add(credit)
    row.add(balance)
    row.add(blockDate)
    row.add(finance)
    row.add(manager)
    row.add(coordinator)
    
    data.add(row)
}

def num = 1;
data.each { row ->
    nextRow()
    rowHeight(13)
    cell(num++)
    nextColumn()
    row.each { column ->
        cell(column)
        nextColumn()
    }
}

nextRow()
3.times{nextColumn()}
text('Итого', 'totalTitle')
nextColumn()
number(totalBalance, 'totalNumber')
//nextColumn(); 4.times{text('', 'totalTitle');nextColumn()}
