/*
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
package com.arrebol.apc.web.drive;

import com.arrebol.apc.controller.GenericController;
import com.arrebol.apc.controller.admin.LoanController;
import com.arrebol.apc.controller.drive.DriverController;
import com.arrebol.apc.model.enums.LoanDetailsType;
import com.arrebol.apc.model.loan.LoanDetails;
import com.arrebol.apc.model.views.CobranzaWeekByUserView;
import com.arrebol.apc.model.views.ColocationWeekByUserView;
import com.arrebol.apc.model.views.InformationLoanWeekView;
import com.arrebol.apc.model.views.ResumenInOutWeekByUserView;
import com.arrebol.apc.model.views.ResumenTotalWeekView;
import com.arrebol.apc.model.views.SubtotalWeekByUserView;
import com.arrebol.apc.web.beans.Datatable;
import com.arrebol.apc.web.beans.GenericBean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Oscar Armando Vargas Cardenas <oscar.vargas@arrebol.com.mx>
 */
@Named("driverDateManager")
@ViewScoped
public class DriverDateBean extends GenericBean implements Serializable, Datatable {

    public void searchLoanWeekByDate() {
        try {
            setData(fillDataTable());
            searchResumenDataWeekByDate();
        } catch (Exception e) {
        }
    }

    public List<LoanDetails> getDetails(String id) {
        try {
            loanDetails = loanCtrl.getLoanDetailsbyId(id);
            getSaldoInsolutoAbono();
        } catch (Exception e) {
        }
        return null == loanDetails ? new ArrayList<>() : loanDetails;
    }
    
     public void getSaldoInsolutoAbono( ) {
        Double sumaAbonosAnteriores;
        Double totalAPagar;
        Double saldoInsoluto;
        Double saldoMultas;
        // 
        for (LoanDetails detail : loanDetails) {
            sumaAbonosAnteriores = loanDetails.stream().filter(p -> p.getReferenceNumber() <= detail.getReferenceNumber() && !p.getLoanDetailsType().equals(LoanDetailsType.FEE) )
                    .mapToDouble(LoanDetails::getAbonoD)
                    .sum();
            saldoMultas = loanDetails.stream().filter(p -> p.getReferenceNumber() <= detail.getReferenceNumber() && p.getLoanDetailsType().equals(LoanDetailsType.FEE))
                    .mapToDouble(LoanDetails::getAbonoD)
                    .sum();
            
            totalAPagar = detail.getLoan().getLoanType().getPaymentTotal().doubleValue();
            saldoInsoluto = totalAPagar - sumaAbonosAnteriores + saldoMultas;

            detail.setSaldoInsoluto(new BigDecimal(saldoInsoluto));
        }
    }
    
    public void searchResumenDataWeekByDate() {
        try {
            SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
            String date = DATE_FORMAT.format(getStarDate());

            dataColocation = driverCtrl.getAllColocationWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
            dataSubtotal = driverCtrl.getAllSubtotalThisWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
            dataResumen = driverCtrl.getAllResumenInOutThisWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
            dataCobranza = driverCtrl.getAllCobranzaThisWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
            dataTotal = driverCtrl.getAllResumenTotalWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
        } catch (Exception e) {
        }
    }

    public List<InformationLoanWeekView> fillDataTable() {
        SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
        String starDate = "";
        if (getStarDate() != null) {
            starDate = DATE_FORMAT.format(getStarDate());
        }
        return getDriverCtrl().getAllLoanWeekByOfficeMySQLQuery(starDate, getLoggedUser().getOffice().getId());
    }

    @Override
    public void editRow(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void onRowCancel(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void onRowReorder(ReorderEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void addRow() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void deleteRow() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public DriverController getDriverCtrl() {
        return driverCtrl;
    }

    public void setDriverCtrl(DriverController driverCtrl) {
        this.driverCtrl = driverCtrl;
    }

    public List<InformationLoanWeekView> getData() {
        return data;
    }

    public void setData(List<InformationLoanWeekView> data) {
        this.data = data;
    }

    public InformationLoanWeekView getSelectedData() {
        return selectedData;
    }

    public void setSelectedData(InformationLoanWeekView selectedData) {
        this.selectedData = selectedData;
    }

    public List<ColocationWeekByUserView> getDataColocation() {
        return dataColocation;
    }

    public void setDataColocation(List<ColocationWeekByUserView> dataColocation) {
        this.dataColocation = dataColocation;
    }

    public ColocationWeekByUserView getSelectedColocation() {
        return selectedColocation;
    }

    public void setSelectedColocation(ColocationWeekByUserView selectedColocation) {
        this.selectedColocation = selectedColocation;
    }

    public List<SubtotalWeekByUserView> getDataSubtotal() {
        return dataSubtotal;
    }

    public void setDataSubtotal(List<SubtotalWeekByUserView> dataSubtotal) {
        this.dataSubtotal = dataSubtotal;
    }

    public SubtotalWeekByUserView getSelectedSubtotal() {
        return selectedSubtotal;
    }

    public void setSelectedSubtotal(SubtotalWeekByUserView selectedSubtotal) {
        this.selectedSubtotal = selectedSubtotal;
    }

    public List<ResumenInOutWeekByUserView> getDataResumen() {
        return dataResumen;
    }

    public void setDataResumen(List<ResumenInOutWeekByUserView> dataResumen) {
        this.dataResumen = dataResumen;
    }

    public ResumenInOutWeekByUserView getSelectedResumen() {
        return selectedResumen;
    }

    public void setSelectedResumen(ResumenInOutWeekByUserView selectedResumen) {
        this.selectedResumen = selectedResumen;
    }

    public List<CobranzaWeekByUserView> getDataCobranza() {
        return dataCobranza;
    }

    public void setDataCobranza(List<CobranzaWeekByUserView> dataCobranza) {
        this.dataCobranza = dataCobranza;
    }

    public CobranzaWeekByUserView getSelectedCobranza() {
        return selectedCobranza;
    }

    public void setSelectedCobranza(CobranzaWeekByUserView selectedCobranza) {
        this.selectedCobranza = selectedCobranza;
    }

    public List<ResumenTotalWeekView> getDataTotal() {
        return dataTotal;
    }

    public void setDataTotal(List<ResumenTotalWeekView> dataTotal) {
        this.dataTotal = dataTotal;
    }

    public ResumenTotalWeekView getSelectedTotal() {
        return selectedTotal;
    }

    public void setSelectedTotal(ResumenTotalWeekView selectedTotal) {
        this.selectedTotal = selectedTotal;
    }

    public GenericController getGenericCtrl() {
        return genericCtrl;
    }

    public void setGenericCtrl(GenericController genericCtrl) {
        this.genericCtrl = genericCtrl;
    }

    public void paintDataXLS(Object document) {    
        HSSFWorkbook wb = (HSSFWorkbook) document;
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow header = sheet.getRow(0);
        HSSFCellStyle cellStyle = wb.createCellStyle();
        HSSFFont font = wb.createFont();
        font.setBold(true);
        cellStyle.setFont(font);
        cellStyle.setBorderTop(BorderStyle.DOUBLE);
        cellStyle.setBorderBottom(BorderStyle.DOUBLE);
        cellStyle.setBorderLeft(BorderStyle.DOUBLE);
        cellStyle.setBorderRight(BorderStyle.DOUBLE);
        cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LEMON_CHIFFON.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        short dataFormat = wb.createDataFormat().getFormat("$#,##0.00");

        initCellStyle(wb);
        HSSFCell cellNew;
       

        for (int i = 0; i < header.getPhysicalNumberOfCells(); i++) {
            HSSFCell cell = header.getCell(i);
            cell.setCellStyle(cellStyle);
        }

        String aux = "";
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            HSSFRow row = sheet.getRow(i);
            InformationLoanWeekView loanWeekData = data.get(i - 1);
            HSSFCell cell;
            String rowRenov = loanWeekData.getConditionRenovation();            
            //cellStyleRow = getCellStyle(rowRenov);
            // Row General
            for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
                cell = row.getCell(j);
                cell.setCellStyle(getCellStyle(rowRenov));

                if ((j >= 5 && j <= 23) || (j == 2) || (j==3)) {
                    cell.getCellStyle().setDataFormat(dataFormat);
                    aux = cell.getStringCellValue().replace("$", "");
                    aux = aux.replace(",", "");
                    cell.setCellValue(Double.parseDouble(aux));
                    cell.setCellType(CellType.NUMERIC);
                }
            }

            // Lunes
            cell = row.getCell(9);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionLunes()));
            cell.getCellStyle().setDataFormat(dataFormat);
            cell = row.getCell(10);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionLunes()));
            cell.getCellStyle().setDataFormat(dataFormat);

            // Martes
            cell = row.getCell(11);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionMartes()));
            cell.getCellStyle().setDataFormat(dataFormat);
            cell = row.getCell(12);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionMartes()));
            cell.getCellStyle().setDataFormat(dataFormat);

            // Miércoles
            cell = row.getCell(13);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionMiercoles()));
            cell.getCellStyle().setDataFormat(dataFormat);
            cell = row.getCell(14);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionMiercoles()));
            cell.getCellStyle().setDataFormat(dataFormat);

            // Jueves
            cell = row.getCell(15);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionJueves()));
            cell.getCellStyle().setDataFormat(dataFormat);
            cell = row.getCell(16);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionJueves()));
            cell.getCellStyle().setDataFormat(dataFormat);

            // Viernes
            cell = row.getCell(17);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionViernes()));
            cell.getCellStyle().setDataFormat(dataFormat);
            cell = row.getCell(18);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionViernes()));
            cell.getCellStyle().setDataFormat(dataFormat);

            // Sábado
            cell = row.getCell(19);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionSabado()));
            cell.getCellStyle().setDataFormat(dataFormat);
            cell = row.getCell(20);
            cell.setCellStyle(getCellStyle(loanWeekData.getConditionSabado()));
            cell.getCellStyle().setDataFormat(dataFormat);
            
           /* cell = row.createCell(24);
            BigDecimal suma = loanWeekData.getPaymentMonday().add(loanWeekData.getPaymentTuesday().add(loanWeekData.getPaymentWednesday()
                    .add(loanWeekData.getPaymentThursday().add(loanWeekData.getPaymentFriday().add(loanWeekData.getPaymentSaturday())))));
            if (suma.compareTo(suma.subtract(loanWeekData.getFaltante())) != 0) {
                cell.setCellStyle(getCellStyle("difRow"));
            }
            cell.setCellType(CellType.NUMERIC);
            cell.setCellValue(suma.doubleValue());
            cell.getCellStyle().setDataFormat(dataFormat);

            cell = row.createCell(25);
            if (suma.compareTo(suma.subtract(loanWeekData.getFaltante())) != 0) {
                cell.setCellStyle(getCellStyle("difRow"));
            }
            cell.setCellType(CellType.NUMERIC);
            BigDecimal dif = suma.subtract(loanWeekData.getFaltante());
            cell.setCellValue(dif.doubleValue());
            cell.getCellStyle().setDataFormat(dataFormat);*/
        }

        String ruta = data.get(0).getRouteName();
        int regInsertados = 0;
        int regSize = sheet.getPhysicalNumberOfRows();

        for (int i = 1; i < regSize; i++) {
            if (!ruta.equalsIgnoreCase(data.get(i - 1 - regInsertados).getRouteName())) {
                //creaRegistroTotalesGeneral(ruta, sheet, dataFormat, false, i);
                creaRegistroTotales(ruta, sheet, dataFormat, false, i);
                ruta = data.get(i - 1 - regInsertados).getRouteName();
                regInsertados++;
            }
        }
        
        ruta = data.get(0).getRouteName();
        regInsertados = 0;
        int recorrido= 1;
        for (int i = 1; i < regSize; i++) {
            if (!ruta.equalsIgnoreCase(data.get(i - 1 - regInsertados).getRouteName())) {
                creaRegistroTotalesGeneral(ruta, sheet, dataFormat, false, i+recorrido);
                //creaRegistroTotales(ruta, sheet, dataFormat, false, i);
                ruta = data.get(i - 1 - regInsertados).getRouteName();
                regInsertados++;
                recorrido++;
            }
        }
        
        creaRegistroTotales(ruta, sheet, dataFormat, true, sheet.getPhysicalNumberOfRows() + 1);
        creaRegistroTotalesGeneral(ruta, sheet, dataFormat, true, sheet.getPhysicalNumberOfRows() + 1);
        
      
    }

    private void creaRegistroTotales(String ruta, HSSFSheet sheet, short dataFormat, boolean lastRow, int i) {
        HSSFRow r;
        HSSFCell cellNew;
        String rutaAux = ruta;
        if (lastRow) {
            r = sheet.createRow(sheet.getPhysicalNumberOfRows() + 1);
        } else {
            sheet.shiftRows(i, sheet.getLastRowNum(), 1, true, false);
            r = sheet.createRow(i);
        }
        
        Calendar c2 = Calendar.getInstance();
        c2.setTime(getStarDate());
        int weekDate = c2.get(Calendar.WEEK_OF_YEAR);
        
        // Apoyos
        cellNew = r.createCell(2);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        BigDecimal suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux) && p.getWeekLoanDate() == weekDate)).map((py) -> py.getApoyos()).reduce(BigDecimal::add).isPresent()
                ? data.stream().filter((p) -> (p.getRouteName().equals(rutaAux) && p.getWeekLoanDate() == weekDate)).map((py) -> py.getApoyos()).reduce(BigDecimal::add).get()
                : BigDecimal.ZERO;
        cellNew.setCellValue(suma.doubleValue());
        // Comsion por apertura
        /*cellNew = r.createCell(3);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux) && p.getWeekLoanDate() == weekDate)).map((py) -> py.getComisionApertura()).reduce(BigDecimal::add).isPresent()
                ? data.stream().filter((p) -> (p.getRouteName().equals(rutaAux) && p.getWeekLoanDate() == weekDate)).map((py) -> py.getComisionApertura()).reduce(BigDecimal::add).get()
                : BigDecimal.ZERO;
        cellNew.setCellValue(suma.doubleValue());*/
        
        //Totales
        cellNew = r.createCell(7);
        cellNew.setCellType(CellType.STRING);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.setCellValue("TOTALES: ");
        // Lunes
        cellNew = r.createCell(9);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getPaymentMonday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        cellNew = r.createCell(10);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getFeeMonday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        // Martes
        cellNew = r.createCell(11);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getPaymentTuesday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        cellNew = r.createCell(12);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getFeeTuesday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        // Miércoles
        cellNew = r.createCell(13);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getPaymentWednesday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        cellNew = r.createCell(14);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getFeeWednesday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        // Jueves
        cellNew = r.createCell(15);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getPaymentThursday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        cellNew = r.createCell(16);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getFeeThursday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        // Viernes
        cellNew = r.createCell(17);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getPaymentFriday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        cellNew = r.createCell(18);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getFeeFriday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        // Sábado
        cellNew = r.createCell(19);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getPaymentSaturday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        cellNew = r.createCell(20);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getFeeSaturday()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        // Faltante
        cellNew = r.createCell(22);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        suma = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getFaltante()).reduce(BigDecimal::add).get();
        cellNew.setCellValue(suma.doubleValue());
        
        
    }

    private void creaRegistroTotalesGeneral(String ruta, HSSFSheet sheet, short dataFormat, boolean lastRow, int i) {
        HSSFRow r;
        HSSFCell cellNew;
        String rutaAux = ruta;
        if (lastRow) {
            r = sheet.createRow(sheet.getPhysicalNumberOfRows() + 1);
        } else {
            sheet.shiftRows(i, sheet.getLastRowNum(), 1, true, false);
            r = sheet.createRow(i);
        }

        Calendar calendar = Calendar.getInstance();
        Calendar calendarFor = Calendar.getInstance();
        calendar.setTime(getStarDate());
        int numberWeekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);

        // Falta sacar el calculo
        
        Entrego = BigDecimal.ZERO;
        ComisionAp = BigDecimal.ZERO;
        AbonosSemana = BigDecimal.ZERO;
        Presto = BigDecimal.ZERO;
        data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).forEach(py -> {
            calendarFor.setTime(py.getFecha());

            if (numberWeekOfYear == calendarFor.get(Calendar.WEEK_OF_YEAR)) {
                setComisionAp(py.getComisionApertura());
                setAbonosSemana(py.getPaymentMonday());
                setAbonosSemana(py.getPaymentTuesday());
                setAbonosSemana(py.getPaymentWednesday());
                setAbonosSemana(py.getPaymentThursday());
                setAbonosSemana(py.getPaymentFriday());
                setAbonosSemana(py.getPaymentSaturday());
                setPresto(py.getApoyos());
            }
        });
        Entrego = Entrego.add(ComisionAp.add(AbonosSemana));

        Long BonosNuevos = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).filter((py) -> (py.getNewCustomer().equalsIgnoreCase("Si"))).count();
        BigDecimal sumaAbonosSemana = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getPaymentMonday().add(py.getPaymentTuesday()
                .add(py.getPaymentWednesday().add(py.getPaymentThursday().add(py.getPaymentFriday().add(py.getPaymentSaturday())))))).reduce(BigDecimal::add).get();
        BigDecimal sumaFaltante = data.stream().filter((p) -> (p.getRouteName().equals(rutaAux))).map((py) -> py.getFaltante()).reduce(BigDecimal::add).get();
        BigDecimal faltanteReal = sumaAbonosSemana.subtract(sumaFaltante);

        //(FALTANTE REAL* 100) / ENTREGO
        BigDecimal porcentajeReal = faltanteReal.multiply(BigDecimal.valueOf(100.0));
        double entr = Entrego.doubleValue();
        double porcReal = porcentajeReal.doubleValue();
        
        if (Entrego.compareTo(BigDecimal.ZERO) > 0 && porcentajeReal.compareTo(BigDecimal.ZERO) != 0) {
            porcentajeReal = new BigDecimal(porcReal/entr);
        }
        else{
            porcentajeReal = BigDecimal.ZERO;
        }

        //Totales
        cellNew = r.createCell(1);
        cellNew.setCellType(CellType.STRING);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.setCellValue("TOTALES GENERAL: ");
        
        //Entregó
        cellNew = r.createCell(2);
        cellNew.setCellType(CellType.STRING);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.setCellValue("Entregó: ");
        cellNew = r.createCell(3);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        cellNew.setCellValue(Entrego.doubleValue());

        //Prestó
        cellNew = r.createCell(4);
        cellNew.setCellType(CellType.STRING);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.setCellValue("Prestó: ");
        cellNew = r.createCell(5);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        cellNew.setCellValue(Presto.doubleValue());
        
        //Faltante Real
        cellNew = r.createCell(6);
        cellNew.setCellType(CellType.STRING);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.setCellValue("Faltante Real: ");
        cellNew = r.createCell(7);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        cellNew.setCellValue(faltanteReal.doubleValue());
        
        //Porcentaje Real
        cellNew = r.createCell(8);
        cellNew.setCellType(CellType.STRING);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.setCellValue("Porcentaje Real: ");
        cellNew = r.createCell(9);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.getCellStyle().setDataFormat(dataFormat);
        cellNew.setCellValue(porcentajeReal.doubleValue());
        
        //Bonos Nuevos
        cellNew = r.createCell(10);
        cellNew.setCellType(CellType.STRING);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.setCellValue("Bonos Nuevos: ");
        cellNew = r.createCell(11);
        cellNew.setCellType(CellType.NUMERIC);
        cellNew.setCellStyle(getCellStyle("greyRow"));
        cellNew.setCellValue(BonosNuevos);
        
    }
    // Se calcula el campo Entrego y Presto
    BigDecimal Entrego = BigDecimal.ZERO;
    BigDecimal ComisionAp = BigDecimal.ZERO;
    BigDecimal AbonosSemana = BigDecimal.ZERO;
    BigDecimal Presto = BigDecimal.ZERO;

    public BigDecimal getComisionAp() {
        return ComisionAp;
    }

    public void setComisionAp(BigDecimal ComisionAp) {
        this.ComisionAp = this.ComisionAp.add(ComisionAp);
    }

    public BigDecimal getAbonosSemana() {
        return AbonosSemana;
    }

    public void setAbonosSemana(BigDecimal AbonosSemana) {
        this.AbonosSemana = this.AbonosSemana.add(AbonosSemana);
    }

    public BigDecimal getPresto() {
        return Presto;
    }

    public void setPresto(BigDecimal Presto) {
        this.Presto = this.Presto.add(Presto);
    }

    private HSSFCellStyle getCellStyle(String cellStyleColor) {
        if (cellStyleColor == null) {
            cellStyleColor = "White";
        }

        switch (cellStyleColor) {
            case "redRow":
                return cellStyleRed;
            case "greenRow":
                return cellStyleGreen;
            case "yellowRow":
                return cellStyleYellow;
            case "blueRow":
                return cellStyleBlue;
            case "blueLightRow":
                return cellStyleBlueLight;
            case "greenLigthRow":
                return cellStyleGreenLight;
            case "greenStrongRow":
                return cellStyleGreenStrong;
            case "greyRow":
                return cellStyleGrey;
            case "orangeRow":
                return cellStyleOrange;
            case "difRow":
                return cellStyleDif;
            case "whiteRow":
                return cellStyleWhite;
            case "limeGreenRow":
                return cellStyleLimeGreen;
            default:
                return cellStyleWhite;
        }
    }

    private void initCellStyle(HSSFWorkbook wb) {
        // MULTA
        fontRed = wb.createFont();
        cellStyleRed = wb.createCellStyle();
        fontRed.setColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        cellStyleRed.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleRed.setFillForegroundColor(IndexedColors.RED.getIndex());
        //cellStyleRed.setFont(fontRed);

        // ABONO 0
        fontGreen = wb.createFont();
        cellStyleGreen = wb.createCellStyle();
        fontGreen.setColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        cellStyleGreen.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleGreen.setFillForegroundColor(IndexedColors.SEA_GREEN.getIndex());
        //cellStyleGreen.setFont(fontGreen);

        // ABONÓ MENOS
        fontYellow = wb.createFont();
        cellStyleYellow = wb.createCellStyle();
        fontYellow.setColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        cellStyleYellow.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleYellow.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
        //cellStyleYellow.setFont(fontYellow);

        // ABONÓ DE MÁS
        fontBlue = wb.createFont();
        cellStyleBlue = wb.createCellStyle();
        fontBlue.setColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        cellStyleBlue.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //cellStyleBlue.setFillForegroundColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());
        cellStyleBlue.setFillForegroundColor(IndexedColors.TURQUOISE.getIndex());
        //cellStyleBlue.setFont(fontBlue);

        // PAGO CONGELADO
        fontBlueLight = wb.createFont();
        cellStyleBlueLight = wb.createCellStyle();
        fontBlueLight.setColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        cellStyleBlueLight.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleBlueLight.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
        
        // RENOVÓ
        fontGreenLight = wb.createFont();
        cellStyleGreenLight = wb.createCellStyle();
        fontGreenLight.setColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        cellStyleGreenLight.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleGreenLight.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
        //cellStyleGreenLight.setFont(fontGreenLight);

        // getSaldoInsoluto == 0
        fontGreenStrong = wb.createFont();
        cellStyleGreenStrong = wb.createCellStyle();
        fontGreenStrong.setColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        cellStyleGreenStrong.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleGreenStrong.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        //cellStyleGreenStrong.setFont(fontGreenStrong);
        
        //Reactivacion 
        fontLimeGreen= wb.createFont();
        cellStyleLimeGreen = wb.createCellStyle();
        fontLimeGreen.setColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        cellStyleLimeGreen.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleLimeGreen.setFillForegroundColor(IndexedColors.LIME.getIndex());
        
        // CLIENTE NUEVO
        fontOrange = wb.createFont(); 
        cellStyleOrange = wb.createCellStyle();
        fontOrange.setColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
        cellStyleOrange.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleOrange.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
        //cellStyleGreenLight.setFont(fontGreenLight);
        
        // Totales
        fontGrey = wb.createFont();
        cellStyleGrey = wb.createCellStyle();
        fontGrey.setColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
        cellStyleGrey.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleGrey.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        cellStyleGrey.setFont(fontGrey);
        
        // Totales
        fontDif = wb.createFont();
        cellStyleDif = wb.createCellStyle();
        fontDif.setColor(HSSFColor.HSSFColorPredefined.RED.getIndex());
        //cellStyleDif.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //cellStyleDif.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        cellStyleDif.setFont(fontDif);

        cellStyleWhite = wb.createCellStyle();
        cellStyleWhite.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleWhite.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
    }

    private DriverController driverCtrl;
    private GenericController genericCtrl;
    private List<InformationLoanWeekView> data;
    private InformationLoanWeekView selectedData;
    private LoanController loanCtrl;

    private List<ColocationWeekByUserView> dataColocation;
    private ColocationWeekByUserView selectedColocation;

    private List<SubtotalWeekByUserView> dataSubtotal;
    private SubtotalWeekByUserView selectedSubtotal;

    private List<ResumenInOutWeekByUserView> dataResumen;
    private ResumenInOutWeekByUserView selectedResumen;

    private List<CobranzaWeekByUserView> dataCobranza;
    private CobranzaWeekByUserView selectedCobranza;

    private List<ResumenTotalWeekView> dataTotal;
    private ResumenTotalWeekView selectedTotal;
    
    private List<LoanDetails> loanDetails;

    // Datos para pintar las celdas
    HSSFCellStyle cellStyleRed;
    HSSFFont fontRed;
    HSSFCellStyle cellStyleGreen;
    HSSFFont fontGreen;
    HSSFCellStyle cellStyleYellow;
    HSSFFont fontYellow;
    HSSFCellStyle cellStyleBlue;
    HSSFFont fontBlue;
    HSSFCellStyle cellStyleBlueLight;
    HSSFFont fontBlueLight;
    HSSFCellStyle cellStyleGreenLight;
    HSSFFont fontGreenLight;
    HSSFCellStyle cellStyleGreenStrong;
    HSSFFont fontGreenStrong;
    HSSFCellStyle cellStyleOrange;
    HSSFFont fontOrange;
    HSSFCellStyle cellStyleWhite;
    HSSFCellStyle cellStyleGrey;
    HSSFFont fontGrey;
    HSSFCellStyle cellStyleDif;
    HSSFFont fontDif;
    HSSFCellStyle cellStyleLimeGreen;
    HSSFFont fontLimeGreen;
    

    @PostConstruct
    public void init() {
        SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
        loadBundlePropertyFile();
        initStartAndEndDates(Calendar.DAY_OF_WEEK, 2);
        String date = DATE_FORMAT.format(getStarDate());

        driverCtrl = new DriverController();
        genericCtrl = new GenericController();
        loanCtrl = new LoanController();
        data = fillDataTable();
        dataColocation = driverCtrl.getAllColocationWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
        dataSubtotal = driverCtrl.getAllSubtotalThisWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
        dataResumen = driverCtrl.getAllResumenInOutThisWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
        dataCobranza = driverCtrl.getAllCobranzaThisWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
        dataTotal = driverCtrl.getAllResumenTotalWeekByOfficeMySQLQuery(date, getLoggedUser().getOffice().getId());
    }

}
