package com.arrebol.taxiservicios.beans.stocktaking.invoice;

import com.arrebol.taxiservicios.beans.Datatable;
import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.catalog.BankCardController;
import com.arrebol.taxiservicios.controller.catalog.ClaveProductoServicioController;
import com.arrebol.taxiservicios.controller.catalog.ClaveUnidadController;
import com.arrebol.taxiservicios.controller.catalog.LocationController;
import com.arrebol.taxiservicios.controller.catalog.ProductBrandController;
import com.arrebol.taxiservicios.controller.catalog.ProductController;
import com.arrebol.taxiservicios.controller.stocktaking.InvoiceController;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.catalog.BankCard;
import com.arrebol.taxiservicios.model.catalog.Brand;
import com.arrebol.taxiservicios.model.catalog.ClaveProductoServicio;
import com.arrebol.taxiservicios.model.catalog.ClaveUnidad;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.catalog.Product;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.ExpenseStatusType;
import com.arrebol.taxiservicios.model.enums.StatusType;
import com.arrebol.taxiservicios.model.stocktaking.Invoice;
import com.arrebol.taxiservicios.model.stocktaking.InvoiceHasProduct;
import com.arrebol.taxiservicios.model.stocktaking.InvoiceHasProductId;
import com.arrebol.taxiservicios.services.catalog.ProductService;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
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;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author @author Carlos Janitzio Zavala López.
 */
@Named
@ViewScoped
public class InvoiceAddBean extends TaxiGenericBean implements Serializable, Datatable {

    /**
     *
     */
    public void createNewProduct() {
        try {
            if(getGenericController().existCheckStocktakingPending(getLoggedUser().getLocation().getId()))
                {
                    showMessage(FacesMessage.SEVERITY_WARN,
                                "Inventario cerrado",
                                "No puedes hacer ningun movimiento al inventario hasta que se termine de cotejar");
                    return;
                }
            getNewProduct().setAmount(0d);
            getNewProduct().setAmount2(0d);
            getNewProduct().setQuantity(0);
            getNewProduct().setQuantity2(0);
            getNewProduct().setUtility(0d);
            getNewProduct().setUtility2(0d);
            getNewProduct().setService(BasicType.DISABLED);
            getNewProduct().setHerramienta(BasicType.DISABLED);
            getNewProduct().setActiveStatus(BasicType.ENEBLED);
            getNewProduct().setClaveUnidad(getClaveUnidad());
            getNewProduct().setClaveProductoServicio(getClaveProductoServicio());

            if (productCtrl.saveProduct(getNewProduct(), getLoggedUser().getId(), getBrandId())) {
                logger.info("createNewProduct");
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("invoice.add.title"),
                        getBundlePropertyFile().getString("invoice.add.new.product.success.desc"));

                setExistingProducts(null);
            } else {
                logger.info("Error createNewProduct");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("invoice.add.title"),
                        getBundlePropertyFile().getString("invoice.add.new.product.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("createNewProduct: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("invoice.add.title"),
                    getBundlePropertyFile().getString("invoice.add.new.product.exception.desc"));
        }

        setNewProduct(null);
        setClaveUnidad(null);
        setClaveProductoServicio(null);
        setIdClaveUnidad(null);
        setIdClaveProductoServicio(null);
    }

    public void calculateIVA() {
        prepareAmount();
    }

    /**
     * Save or update a Invoince and It's product list.
     */
    public void saveUpdateInvoice() {
        logger.info("saveUpdateInvoice");
        boolean success = false;
        User by = new User(getLoggedUser().getId(), "");
        
        if(getGenericController().existCheckStocktakingPending(getLoggedUser().getLocation().getId()))
        {
            showMessage(FacesMessage.SEVERITY_WARN,
                        "Inventario cerrado",
                        "No puedes hacer ningun movimiento al inventario hasta que se termine de cotejar");
            return;
        }
        
        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,
                            "Dia cerrado",
                            "No se pueden eliminar más registros porque ya existe un cuadre de caja chica del día");
                return;
            }

        try {

            if (isAddInvoiceBtnOnclick()) {
                setInvoiceId(UUID.randomUUID().toString());

                getInvoice().setId(getInvoiceId());
                getInvoice().setSubtotal(getSubTotal());
                getInvoice().setIva(getTotalIva());
                getInvoice().setTotal(getTotal());
                getInvoice().setPerson(new Person(personId));
                getInvoice().setActive(true);
                getInvoice().setCreatedBy(by);
                getInvoice().setLocation(getLoggedUser().getLocation());
                getInvoice().setTaxi(taxiId == null || taxiId.equals("") ? null : new Taxi(taxiId));
                getInvoice().setDriver(driverId == null || driverId.equals("") ? null : new Person(driverId));
                getInvoice().setAuthorize(StatusType.PENDING);
                getInvoice().setCreatedOn(new Date());
                getInvoice().setLocationSend(new Location(locationId));
                
                if(locationId.equalsIgnoreCase(getLoggedUser().getLocation().getId())){
                    getInvoice().setPaid(BasicType.ENEBLED);
                    getInvoice().setStatusType(StatusType.APPROVED);
                }
                else
                {
                    getInvoice().setPaid(BasicType.DISABLED);
                    getInvoice().setStatusType(StatusType.PENDING);
                }
                
                if(isDeposit()){
                    getInvoice().setDepositStatus(ExpenseStatusType.PENDING);
                    getInvoice().setBankCard(new BankCard(getBankCardId()));
                
                }else{
                    getInvoice().setDepositStatus(ExpenseStatusType.AUTHORIZED);
                }

                success = getController()
                        .saveInvoice(getInvoice(), fillInvoiceProducts(by));
            } else {
                getInvoice().setPerson(new Person(personId));
                getInvoice().setLastUpdatedBy(by);
                getInvoice().setLastUpdatedOn(new Date());

                success = getController()
                        .updateInvoice(getInvoice());
            }

            if (success) {
                String title = isAddInvoiceBtnOnclick() ? "invoice.add.title" : "invoice.edit.title";
                String message = isAddInvoiceBtnOnclick() ? "invoice.add.success.desc" : "invoice.edit.success.desc";
                setAddInvoiceBtnOnclick(false);
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString(title),
                        getBundlePropertyFile().getString(message));
            } else {
                logger.error("Invoice " + getInvoice() + " was not " + (isAddInvoiceBtnOnclick() ? "updated" : "saved"));
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("invoice.add.title"),
                        getBundlePropertyFile().getString("invoice.add.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("addInvoice: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("invoice.add.title"),
                    getBundlePropertyFile().getString("invoice.add.exception.desc"));
        }
    }

    /**
     * Delete the selected product from a Invoice's product list.
     */
    public void deleteSelectedProduct() {
        logger.info("deleteSelectedProduct");
        try {
            if (!isAddInvoiceBtnOnclick()) {

            }
            getInvoiceProducts().remove(getSelectedProduct());

            prepareAmount();
        } catch (Exception e) {
            logger.error("deleteSelectedProduct", e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("garage.title"),
                    getBundlePropertyFile().getString("fatal.access.details"));
        }
    }

    /**
     * Fill list of Invoice's products.
     *
     * @param by Created/Updated user.
     * @return List of products to be saved for Invoice.
     */
    private List<InvoiceHasProduct> fillInvoiceProducts(User by) {
        List<InvoiceHasProduct> invoiceHasProducts = new ArrayList<>();

        getInvoiceProducts().forEach((Product prdct) -> {
            invoiceHasProducts.add(
                    new InvoiceHasProduct(
                            new InvoiceHasProductId(getInvoiceId(), prdct.getId()),
                            prdct.getAmount().floatValue(), prdct.getQuantity(),
                            by, new Date(), prdct.getUtility().floatValue(), BasicType.DISABLED
                    )
            );
        });

        return invoiceHasProducts;
    }

     public void onItemSelectClaveUnidad(SelectEvent event) {
        
        try {
            setClaveUnidad(claveUnidadController.getById(getIdClaveUnidad()));
        } catch (Exception e) {
            
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("garage.title"),
                    getBundlePropertyFile().getString("garage.generic.exception"));
        }
    }
    
    public void onItemSelectClaveProductoServicio(SelectEvent event) {
        
        try {
            setClaveProductoServicio(claveProductoServicioController.getById(getIdClaveProductoServicio()));
        } catch (Exception e) {
            
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("garage.title"),
                    getBundlePropertyFile().getString("garage.generic.exception"));
        }
    }
    
    public List<ClaveProductoServicio> searchClaveProductoServicios(String query) {
        
        List<ClaveProductoServicio> list = null;
        try {
            list = getClaveProductoServicioController().getClaveProductoServicioLike(query);
        } catch (Exception e) {
            
            showMessage(FacesMessage.SEVERITY_FATAL,
                    "No se pudo buscar la clave producto servicio",
                    "Error");
        }
        return list;
    }
    
    public List<ClaveUnidad> searchClaveUnidad(String query) {
        
        List<ClaveUnidad> list = null;
        try {
            list = getClaveUnidadController().getClaveUnidadLike(query);
        } catch (Exception e) {
            
            showMessage(FacesMessage.SEVERITY_FATAL,
                    "No se pudo buscar la clave producto servicio",
                    "Error");
        }
        return list;
    }
    
    public void handleClose() {
        setClaveUnidad(null);
        setClaveProductoServicio(null);
        setIdClaveUnidad(null);
        setIdClaveProductoServicio(null);
        
    }
    private static final long serialVersionUID = -2908972533530111320L;

    final Logger logger = LogManager.getLogger(InvoiceAddBean.class);

    private InvoiceController controller;
    private GenericValidationController genericController;
    private Invoice invoice;
    private List<InvoiceHasProduct> details;
    private List<Product> invoiceProducts;
    private List<Product> oldInvoiceProducts;
    private Product selectedProduct;
    private Product product;
    private String personId;
    private boolean addInvoiceBtnOnclick;
    private String invoiceId;
    private InvoiceHasProduct selectedDetail;
    private String productId;
    private Integer quantity;
    private Float price;
    private Float priceMayoreo;
    private Float subTotal;
    private Float totalIva;
    private Float total;
    private List<Product> existingProducts;
    private boolean activeIVA;
    private Product newProduct;
    private String brandId;
    private String driverId;
    
    private String taxiId;
    private String locationId;
    
    private ProductBrandController brandCtrl;
    private ProductController productCtrl;
    private LocationController locationController;
    
    private String idClaveUnidad;
    private ClaveUnidad claveUnidad;
    private String idClaveProductoServicio;
    private ClaveProductoServicio claveProductoServicio;
    private ClaveUnidadController claveUnidadController;
    private ClaveProductoServicioController claveProductoServicioController;
    
    private boolean deposit;
    private String bankCardId;
    private BankCardController bankCardController;
    private List<BankCard> bankCards;
    
    private List<Location> locations;

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            productCtrl = new ProductController();
            brandCtrl = new ProductBrandController();
            setInvoice(new Invoice());
            setController(new InvoiceController());
            setGenericController(new GenericValidationController());
            setLocationController(new LocationController());
            setAddInvoiceBtnOnclick(true);
            setLocations(getLocationController().fillLocationDatatable());
            setClaveUnidadController(new ClaveUnidadController());
        setClaveProductoServicioController(new ClaveProductoServicioController());
        setBankCardController(new BankCardController());
        setBankCards(getBankCardController().findAllBankCardsByLocation(getLoggedUser().getLocation().getId()));
            setDeposit(false);
            
        } catch (Exception e) {
            logger.error("Can not load the add view for Invoice", e);
        }
    }

    public List<Location> getLocations() {
        return locations;
    }

    public void setLocations(List<Location> locations) {
        this.locations = locations;
    }

    public LocationController getLocationController() {
        return locationController;
    }

    public void setLocationController(LocationController locationController) {
        this.locationController = locationController;
    }

    public String getLocationId() {
        return locationId;
    }

    public void setLocationId(String locationId) {
        this.locationId = locationId;
    }

    public ProductBrandController getBrandCtrl() {
        return brandCtrl;
    }

    public void setBrandCtrl(ProductBrandController brandCtrl) {
        this.brandCtrl = brandCtrl;
    }

    public ProductController getProductCtrl() {
        return productCtrl;
    }

    public void setProductCtrl(ProductController productCtrl) {
        this.productCtrl = productCtrl;
    }

    public String getDriverId() {
        return driverId;
    }

    public void setDriverId(String driverId) {
        this.driverId = driverId;
    }

    public String getTaxiId() {
        return taxiId;
    }

    public void setTaxiId(String taxiId) {
        this.taxiId = taxiId;
    }
    
    public List<Taxi> getTaxis() {
        return getController().fillTaxisComboBox();
    }
    
    public List<Taxi> getTaxis2() {
        return getController().fillTaxisComboBox2();
    }

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public InvoiceHasProduct getSelectedDetail() {
        return selectedDetail;
    }

    public void setSelectedDetail(InvoiceHasProduct selectedDetail) {
        this.selectedDetail = selectedDetail;
    }

    public String getInvoiceId() {
        return invoiceId;
    }

    public void setInvoiceId(String invoiceId) {
        this.invoiceId = invoiceId;
    }

    public List<InvoiceHasProduct> getDetails() {
        return details;
    }

    public void setDetails(List<InvoiceHasProduct> details) {
        this.details = details;
    }

    public String getPersonId() {
        return personId;
    }

    public void setPersonId(String personId) {
        this.personId = personId;
    }

    public InvoiceController getController() {
        return controller;
    }

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

    public Invoice getInvoice() {
        return invoice;
    }

    public void setInvoice(Invoice invoice) {
        this.invoice = invoice;
    }

    public void setAddInvoiceBtnOnclick(boolean addInvoiceBtnOnclick) {
        this.addInvoiceBtnOnclick = addInvoiceBtnOnclick;
    }

    public boolean isAddInvoiceBtnOnclick() {
        return addInvoiceBtnOnclick;
    }

    public List<Person> getProviders() {
        return getController().fillProviderComboBox();
    }
    
    public List<Person> getDrivers() {
        return getController().fillDriversComboBox();
    }

    public List<Product> getExistingProducts() {
        if (null == existingProducts) {
            existingProducts = getController().fillProductsComboBox();
        }
        return existingProducts;

    }

    public void setExistingProducts(List<Product> existingProducts) {
        this.existingProducts = existingProducts;
    }

    public List<Product> getInvoiceProducts() {
        if (null == invoiceProducts) {
            invoiceProducts = new ArrayList<>();
        }
        return invoiceProducts;
    }

    public List<Product> getOldInvoiceProducts() {
        if (null == oldInvoiceProducts) {
            oldInvoiceProducts = new ArrayList<>();
        }
        return oldInvoiceProducts;
    }

    public Product getSelectedProduct() {
        return selectedProduct;
    }

    public void setSelectedProduct(Product selectedProduct) {
        this.selectedProduct = selectedProduct;
    }

    public Float getSubTotal() {
        return subTotal;
    }

    public void setSubTotal(Float subTotal) {
        this.subTotal = subTotal;
    }

    public Float getTotalIva() {
        return totalIva;
    }

    public void setTotalIva(Float totalIva) {
        this.totalIva = totalIva;
    }

    public Float getTotal() {
        return total;
    }

    public void setTotal(Float total) {
        this.total = total;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public boolean isActiveIVA() {
        return activeIVA;
    }

    public void setActiveIVA(boolean activeIVA) {
        this.activeIVA = activeIVA;
    }

    public Product getNewProduct() {
        if (null == newProduct) {
            newProduct = new Product();
        }

        return newProduct;
    }

    public void setNewProduct(Product newProduct) {
        this.newProduct = newProduct;
    }

    public List<Brand> getBrandes() {
        return brandCtrl.fillProductBrandComboBox();
    }

    public String getBrandId() {
        return brandId;
    }

    public void setBrandId(String brandId) {
        this.brandId = brandId;
    }

    public Float getPriceMayoreo() {
        return priceMayoreo;
    }

    public void setPriceMayoreo(Float priceMayoreo) {
        this.priceMayoreo = priceMayoreo;
    }
    
     public String getIdClaveUnidad() {
        return idClaveUnidad;
    }

    public void setIdClaveUnidad(String idClaveUnidad) {
        this.idClaveUnidad = idClaveUnidad;
    }

    public ClaveUnidad getClaveUnidad() {
        return claveUnidad;
    }

    public void setClaveUnidad(ClaveUnidad claveUnidad) {
        this.claveUnidad = claveUnidad;
    }

    public String getIdClaveProductoServicio() {
        return idClaveProductoServicio;
    }

    public void setIdClaveProductoServicio(String idClaveProductoServicio) {
        this.idClaveProductoServicio = idClaveProductoServicio;
    }

    public ClaveProductoServicio getClaveProductoServicio() {
        return claveProductoServicio;
    }

    public void setClaveProductoServicio(ClaveProductoServicio claveProductoServicio) {
        this.claveProductoServicio = claveProductoServicio;
    }

    public ClaveUnidadController getClaveUnidadController() {
        return claveUnidadController;
    }

    public void setClaveUnidadController(ClaveUnidadController claveUnidadController) {
        this.claveUnidadController = claveUnidadController;
    }

    public ClaveProductoServicioController getClaveProductoServicioController() {
        return claveProductoServicioController;
    }

    public void setClaveProductoServicioController(ClaveProductoServicioController claveProductoServicioController) {
        this.claveProductoServicioController = claveProductoServicioController;
    }

    public boolean isDeposit() {
        return deposit;
    }

    public void setDeposit(boolean deposit) {
        this.deposit = deposit;
    }

    public String getBankCardId() {
        return bankCardId;
    }

    public void setBankCardId(String bankCardId) {
        this.bankCardId = bankCardId;
    }

    public BankCardController getBankCardController() {
        return bankCardController;
    }

    public void setBankCardController(BankCardController bankCardController) {
        this.bankCardController = bankCardController;
    }

    public List<BankCard> getBankCards() {
        return bankCards;
    }

    public void setBankCards(List<BankCard> bankCards) {
        this.bankCards = bankCards;
    }

    @Override
    public void editRow(RowEditEvent event) {
        try {
            Product p = (Product) event.getObject();

            getInvoiceProducts().forEach((Product comboProduct) -> {
                if (p.getId().equals(comboProduct.getId())) {
                    comboProduct.setQuantity(p.getQuantity());
                    comboProduct.setAmount(p.getAmount());
                    comboProduct.setUtility(p.getUtility());
                }
            });

            prepareAmount();
        } catch (Exception e) {
            logger.error("editRow: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL, "Compras",
                    "Error al editar el producto");
        }

    }

    @Override
    public void onRowCancel(RowEditEvent event) {
    }

    @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() {
        logger.info("addRow for INVOICEHASPRODUCT");
        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;
            }
        try {
            Product prod = new Product(productId, price.doubleValue(), quantity);
            Product tmpProduct = findProduct(productId);
            prod.setCode(tmpProduct.getCode());
            prod.setName(tmpProduct.getName());
            prod.setUtility(priceMayoreo.doubleValue());

            getInvoiceProducts().add(prod);

            prepareAmount();

            productId = null;
            price = null;
            priceMayoreo = null;
            quantity = null;
        } catch (Exception e) {
            logger.error("addRow for INVOICEHASPRODUCT: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("invoice.detail.add.title"),
                    getBundlePropertyFile().getString("invoice.detail.add.exception.desc"));
        }
    }

    private void prepareAmount() {
        setSubTotal(0f);
        setTotalIva(0f);
        setTotal(0f);

        getInvoiceProducts().forEach((p) -> {
            subTotal += p.getQuantity() * p.getAmount().floatValue();
        });

        if (isActiveIVA()) {
            setTotalIva(getSubTotal() * iva.floatValue());
        }

        setTotal(getSubTotal() + getTotalIva());
    }

    public Product findProduct(String id) {
        for (Product prod : getExistingProducts()) {
            if (id.equals(prod.getId())) {
                return prod;
            }
        }
        return null;
    }

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