/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arrebol.taxiservicios.beans.admin;

import com.arrebol.taxiservicios.beans.Datatable;
import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.BitacoraController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.admin.PaymentCustomerController;
import com.arrebol.taxiservicios.controller.catalog.BankCardController;
import com.arrebol.taxiservicios.controller.catalog.BankCardKardexController;
import com.arrebol.taxiservicios.controller.stocktaking.HistoryUpdateKmController;
import com.arrebol.taxiservicios.model.admin.FinancingCustomer;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.catalog.BankCard;
import com.arrebol.taxiservicios.model.catalog.BankCardKardex;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BankCardKardexType;
import com.arrebol.taxiservicios.model.stocktaking.Invoice;
import com.arrebol.taxiservicios.model.stocktaking.view.HistoryUpdateKm;
import com.arrebol.taxiservicios.model.view.report.PaymentClient;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Oscar
 */
@Named("paymentClientBean")
@ViewScoped
public class PaymentClientBean extends TaxiGenericBean implements Serializable, Datatable {
    
    public String seeDetails(String outcome) {
        return outcome;
    }

    public void fillDataTableBetweenDates() {
        try {
            if (getGenericStartDate().after(getGenericEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, getBundlePropertyFile().getString("generic.start.date"), getBundlePropertyFile().getString("generic.end.date.error"));
            } else {
                setHistory(getController().fillDataTableBetweenDates(getGenericStartDate(), getGenericEndDate()));
                
                calcularTotales();
            }
        } catch (Exception e) {
            logger.error("", e);
        }
    }
    
    public void authorizeDeposit() {
        logger.info("autorizadeDeposit");
        User by = new User(getLoggedUser().getId(), "");
        try {
            if (getGenericController().existClosingDayByCreatedOn(new Date(), getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN, "Error","No se puede hacer ninguna acción si existe un corte del día");
                return;
            }
            if (getController().autorizarDeposito(selectedPayment.getId(), by)) {
                
                BankCardKardex bankCardKardexObj = new BankCardKardex();
                

                bankCardKardexObj.setBankCard(getSelectedPayment().getBankCard());
                bankCardKardexObj.setAmount(getSelectedPayment().getTotalPayment());
                bankCardKardexObj.setAmountBefore(getSelectedPayment().getBankCard().getBalance());
                bankCardKardexObj.setAmountAfter(bankCardKardexObj.getAmountBefore()-bankCardKardexObj.getAmount());
                bankCardKardexObj.setKardexType(BankCardKardexType.EXPENSE);
                bankCardKardexObj.setDescription("Compra de inventario");
                bankCardKardexObj.setLocation(getSelectedPayment().getLocation());
                
                BankCardKardexController bankCardKardexCtrl = new BankCardKardexController(); 
                bankCardKardexCtrl.save(bankCardKardexObj, getLoggedUser().getId());

                BankCard bankCard = getSelectedPayment().getBankCard();
                
                bankCard.setBalance(bankCardKardexObj.getAmountAfter());
                
                BankCardController bankCardCtrl = new BankCardController();
                
                bankCardCtrl.save(bankCard, getLoggedUser().getId());
                
                setSelectedPayment(null);
                showMessage(FacesMessage.SEVERITY_INFO, "Mensaje","Pago al cliente autorizada");
                setHistoryPending(getController().fillDataTableDepositPending(getLoggedUser().getLocation().getId()));
            } else {
                logger.error("Invoice " + getSelectedPayment()+ "can not be updated");
                showMessage(FacesMessage.SEVERITY_WARN, "Error","No se pudo autorizar la compra");
            }

        } catch (Exception e) {
            logger.error("editRow: " + e);
            
        }
    }
    
    @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) {
        showMessage(FacesMessage.SEVERITY_INFO, "Registro Movido", "De columna: " + (event.getFromIndex() + 1) + " a columna: " + (event.getToIndex() + 1));
    }

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

    @Override
    public void deleteRow() {
        logger.info("deleteRow in Sanction");
        try {
            if (getGenericController().existClosingDayByCreatedOn(new Date(), getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Error",
                        "No se puede hacer ninguna acción si existe un corte del día");
                return;
            }
            if (getGenericController().existStableSmallBoxByCurdate(getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Error",
                        "No se puede hacer ninguna acción si existe un cuadre de caja chica");
                return;
            }
            if (getGenericController().existStableGeneralBoxByCurdate(getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Error",
                        "No se puede hacer ninguna acción si existe un cuadre de caja general");
                return;
            }
            
            boolean success = getController().deleteById(getSelectedPayment().getId());
            
            if (success) {
                
                Taxi taxi = getSelectedPayment().getTaxi();
                FinancingCustomer financingCustomer = getController().getFinancingCustomerByPaymentClient(getSelectedPayment());
                
                taxi.setAdeudo(taxi.getAdeudo() + (float) getSelectedPayment().getAbonoAdeudo() - (float) financingCustomer.getMonthDebit() - (float) financingCustomer.getIncrease() + (float) financingCustomer.getDiscount());
                getController().updateAdeudoTaxi(taxi);
                getController().updateExpenseFinance(getSelectedPayment());
                getController().updateExpensePaid(getSelectedPayment());
                getController().updateServiceOrderHasProductPaid(getSelectedPayment());
                getController().updateServiceOrderHasProductFinance(getSelectedPayment());
                
                String actionBitacora = "Eliminar pago del cliente";
                String descBitacora = "Se eliminó el pago del cliente " + getSelectedPayment().getTaxi().getCustomer().getFirstName() + " " + getSelectedPayment().getTaxi().getCustomer().getLastName() +
                         ", monto " + currencyFormatNumber(getSelectedPayment().getTotalPayment())
                        + " y fecha " + getSelectedPayment().getCreatedOn();

                getBitacoraController().saveNewRecordInBitacora(createNewRecordInBitacora(UUID.randomUUID().toString(), actionBitacora, getCommentsBitacora(), descBitacora),
                        getLoggedUser().getLocation().getId());
                setHistory(getController().fillDataTableBetweenDates(getGenericStartDate(), getGenericEndDate()));
                showMessage(FacesMessage.SEVERITY_INFO,
                            "Eliminar pago a cliente",
                            "Se eliminó correctamente");
            } else {
                logger.error("PaymentClient " + getSelectedPayment() + "was not deleted");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        "Eliminar pago a cliente",
                        "No se pudo eliminar el pago a cliente");
            }
            
        } catch (Exception e) {
            logger.error("deleteRow: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                    "Eliminar pago a cliente",
                    getBundlePropertyFile().getString("sanction.delete.exception.desc"));
        
        }
    }
    
    final Logger logger = LogManager.getLogger(PaymentClientBean.class);
    PaymentCustomerController controller;
    private GenericValidationController genericController;
    private Date startDate;
    private Date endDate;
    List<PaymentClient> history;
    PaymentClient selectedPayment;
    double totalPagado;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private Date lastStableSmallBox;
    private boolean hayCuadre;
    private List<PaymentClient> historyPending;
    
    public void calcularTotales(){
        totalPagado = 0D;
        if(getHistory() != null && !getHistory().isEmpty())
        {
            for(PaymentClient pay: getHistory())
            {
               totalPagado += pay.getTotalPayment();
            }
        }
    }
    
    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            setGenericUpDates(true);
            setController(new PaymentCustomerController());
            setGenericController(new GenericValidationController());
            setBitacoraController(new BitacoraController());
            setHistory(getController().fillDataTableBetweenDates(getGenericStartDate(),
                    getGenericEndDate()));
            
            setHistoryPending(getController().fillDataTableDepositPending(getLoggedUser().getLocation().getId()));
            
            setLastStableSmallBox(getGenericController().lastStableSmallBoxByDate(getLoggedUser()));
            setHayCuadre(getGenericController().existStableSmallBoxByCurdate(getLoggedUser()));
            
            calcularTotales();

            logger.info("HistoryUpdateKm loaded");
        } catch (Exception e) {
            logger.error("init", e);
        }
    }

    public Date getLastStableSmallBox() {
        return lastStableSmallBox;
    }

    public void setLastStableSmallBox(Date lastStableSmallBox) {
        this.lastStableSmallBox = lastStableSmallBox;
    }

    public boolean isHayCuadre() {
        return hayCuadre;
    }

    public void setHayCuadre(boolean hayCuadre) {
        this.hayCuadre = hayCuadre;
    }

    public BitacoraController getBitacoraController() {
        return bitacoraController;
    }

    public void setBitacoraController(BitacoraController bitacoraController) {
        this.bitacoraController = bitacoraController;
    }

    public String getCommentsBitacora() {
        return commentsBitacora;
    }

    public void setCommentsBitacora(String commentsBitacora) {
        this.commentsBitacora = commentsBitacora;
    }

    public double getTotalPagado() {
        return totalPagado;
    }

    public void setTotalPagado(double totalPagado) {
        this.totalPagado = totalPagado;
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

    public void setGenericController(GenericValidationController genericController) {
        this.genericController = genericController;
    }

    public PaymentClient getSelectedPayment() {
        return selectedPayment;
    }

    public void setSelectedPayment(PaymentClient selectedPayment) {
        this.selectedPayment = selectedPayment;
    }

    public PaymentCustomerController getController() {
        return controller;
    }

    public void setController(PaymentCustomerController controller) {
        this.controller = controller;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public List<PaymentClient> getHistory() {
        return history;
    }

    public void setHistory(List<PaymentClient> history) {
        this.history = history;
    }

    public List<PaymentClient> getHistoryPending() {
        return historyPending;
    }

    public void setHistoryPending(List<PaymentClient> historyPending) {
        this.historyPending = historyPending;
    }
    
    
}
