/*
 * 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.payroll;

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.EmployeeController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.admin.SanctionController;
import com.arrebol.taxiservicios.controller.payroll.PayrollController;
import com.arrebol.taxiservicios.controller.system.UserController;
import com.arrebol.taxiservicios.model.admin.EmployeeSanction;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.EmployeeSanctionType;
import com.arrebol.taxiservicios.model.payroll.Payroll;
import java.io.Serializable;
import java.util.Calendar;
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
@ViewScoped
public class PayrollBean extends TaxiGenericBean implements Serializable, Datatable {

    public void calculateTotalPercepciones() {
        try {
            totalPercepcion = getAddPayroll().getSalary() + getAddPayroll().getBono1()
                    + getAddPayroll().getBono2() + getAddPayroll().getBono3() + getAddPayroll().getIncrease();
        } catch (Exception e) {
            logger.error("calculateDifference", e);
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("stable.general.box"),
                    getBundlePropertyFile().getString("stable.general.box.calculate.difference.error"));
        }
    }

    public void onChangeSelectedUser() {
        try {
            User tmp = getUserController().getById(idUser);
            Person personTemp = tmp.getPerson();
            getAddPayroll().setSalary(tmp.getPerson().getSalary());
            getAddPayroll().setImss(tmp.getPerson().getImss());
            getAddPayroll().setSaving(tmp.getPerson().getSavingWeek());
            getAddPayroll().setAdelanto(getController().getAdvanceByUser(personTemp));
        } catch (Exception e) {
            logger.error("calculateDifference", e);
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("stable.general.box"),
                    getBundlePropertyFile().getString("stable.general.box.calculate.difference.error"));
        }
    }

    public void calculateTotal() {
        try {
            getAddPayroll().setTotal(totalPercepcion - totalDeduccion);
        } catch (Exception e) {
            logger.error("calculateDifference", e);
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("stable.general.box"),
                    getBundlePropertyFile().getString("stable.general.box.calculate.difference.error"));
        }
    }

    public void calculateTotalDeducciones() {
        try {
            totalDeduccion = getAddPayroll().getImss() + getAddPayroll().getCajeado() + getAddPayroll().getSaving()
                    + getAddPayroll().getAdelanto() + getAddPayroll().getDiscount() + getAddPayroll().getAbono();
        } catch (Exception e) {
            logger.error("calculateDifference", e);
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("stable.general.box"),
                    getBundlePropertyFile().getString("stable.general.box.calculate.difference.error"));
        }
    }

    public void updateHistoryPayrollList() {
        logger.info("updateHistoryPayrollList");
        try {
            if (getStartDate().after(getEndDate())) {
                showMessage(FacesMessage.SEVERITY_ERROR, "Nómina","Fecha inicial debe ser menor a fecha final");
            } else {
                setUpDates(false);
                setPayroll(
                        getController().findPayrollBetweenDates(
                                getStartDate(),
                                getEndDate(),
                                getLoggedUser().getLocation().getId()
                        )
                );
            }
        } catch (Exception e) {
            logger.error("updateHistoryPayrollList", 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) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void addRow() {
        logger.info("addRow");
        if (getGenericController().existStableGeneralBoxByCurdate(getLoggedUser())) {
            showMessage(FacesMessage.SEVERITY_WARN,
                    "Dia cerrado",
                    "No se pueden generar más nóminas porque ya existe un cuadre de caja general del día");
            return;
        }
        /*if (getController().existPayrrollBetweenDates(getLoggedUser(), startDate, endDate)) {
            showMessage(FacesMessage.SEVERITY_WARN,
                    "Nómina duplicada",
                    "Ya existe una nómina para el mismo empleado con ese rango de fechas");
            return;
        }*/
        getAddPayroll().setId(UUID.randomUUID().toString());
        getAddPayroll().setActive(true);
        getAddPayroll().setUser(new User(idUser, true));
        getAddPayroll().setCreatedBy(getLoggedUser());
        getAddPayroll().setCreatedOn(new Date());
        getAddPayroll().setLocation(getLoggedUser().getLocation());
        getAddPayroll().setInitDate(startDate);
        getAddPayroll().setEndDate(endDate);

        if (getController().save(getAddPayroll())) {

            setUpDates(false);
            setPayroll(
                    getController().findPayrollBetweenDates(
                            getStartDate(),
                            getEndDate(),
                            getLoggedUser().getLocation().getId()
                    )
            );

            if (getAddPayroll().getAbono() > 0) {
                User tmp = getUserController().getById(idUser);
                Person personTemp = tmp.getPerson();

                EmployeeSanction expense = new EmployeeSanction();
                expense.setId(UUID.randomUUID().toString());
                expense.setPayment(getAddPayroll().getAbono());
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.HOUR, -6);
                expense.setCreatedOn(calendar.getTime());
                expense.setDescription("");
                expense.setType(EmployeeSanctionType.ABONO_DEUDA_NOMINA);
                expense.setAmountToPay(0D);
                expense.setPaymentWeek(0D);
                expense.setLocation(getLoggedUser().getLocation());

                boolean success = getSanctionController().addEmployeeSanction(
                        expense,
                        getLoggedUser().getId(),
                        (null != personTemp.getId() && !"".equals(personTemp.getId().trim())) ? personTemp.getId() : null);

                if (success) {
                    showMessage(FacesMessage.SEVERITY_INFO,
                            "Abono al adeudo",
                            "Se agregó correctamente");

                    personTemp.setAdeudo((float) ((personTemp.getAdeudo() == null ? 0F : personTemp.getAdeudo()) - getAddPayroll().getAbono()));
                    getEmployeeController().editAdeudo(personTemp.getId(), personTemp.getAdeudo(), getLoggedUser());
                }

            }

            if (getAddPayroll().getSaving() > 0) {
                User tmp = getUserController().getById(idUser);
                Person personTemp = tmp.getPerson();

                EmployeeSanction expense = new EmployeeSanction();
                expense.setId(UUID.randomUUID().toString());
                expense.setPayment(getAddPayroll().getSaving());
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.HOUR, -6);
                expense.setCreatedOn(calendar.getTime());
                expense.setDescription("");
                expense.setType(EmployeeSanctionType.SAVING_NOMINA);
                expense.setAmountToPay(0D);
                expense.setPaymentWeek(0D);
                expense.setLocation(getLoggedUser().getLocation());

                boolean success = getSanctionController().addEmployeeSanction(
                        expense,
                        getLoggedUser().getId(),
                        (null != personTemp.getId() && !"".equals(personTemp.getId().trim())) ? personTemp.getId() : null);

                if (success) {
                    showMessage(FacesMessage.SEVERITY_INFO,
                            "Caja de ahorro",
                            "Se agregó correctamente");

                    personTemp.setSaving((double) (personTemp.getSaving()) + getAddPayroll().getSaving());
                    getEmployeeController().editSaving(personTemp.getId(), personTemp.getSaving(), getLoggedUser());
                }
            }

            initPayrollObject();

            showMessage(FacesMessage.SEVERITY_INFO,
                    "Nómina",
                    "Se agregó correctamente");
        } else {
            logger.error("payroll couldnot saved");
            showMessage(FacesMessage.SEVERITY_ERROR,
                    "Nómina",
                    "No se puedo crear la nómina");
        }
    }

    private void initPayrollObject() {
        logger.info("initPayrollObject");
        try {
            setAddPayroll(new Payroll());

            getAddPayroll().setAdelanto(0D);
            getAddPayroll().setBono1(0D);
            getAddPayroll().setBono2(0D);
            getAddPayroll().setBono3(0D);
            getAddPayroll().setCajeado(0D);
            getAddPayroll().setDiscount(0D);
            getAddPayroll().setImss(0D);
            getAddPayroll().setIncrease(0D);
            getAddPayroll().setSalary(0D);
            getAddPayroll().setTotal(0D);
            getAddPayroll().setDescriptionDiscount("");
            getAddPayroll().setDescriptionIncrease("");
        } catch (Exception e) {
            logger.error("initPayrollObject", e);
        }

    }

    @Override
    public void deleteRow() {

        if (getGenericController().existStableGeneralBoxByCurdate(getLoggedUser())) {
            showMessage(FacesMessage.SEVERITY_WARN,
                    "Dia cerrado",
                    "No se pueden eliminar más nóminas porque ya existe un cuadre de caja general del día");
            return;
        }
        getController().delete(selectedPayroll);

        setPayroll(
                getController().findPayrollBetweenDates(
                        getStartDate(),
                        getEndDate(),
                        getLoggedUser().getLocation().getId()
                ));

        setSelectedPayroll(null);
        showMessage(FacesMessage.SEVERITY_INFO, "Nómina eliminada", "Se eliminó correctamente.");

    }

    @PostConstruct
    public void init() {
        try {
            loadBundlePropertyFile();
            setController(new PayrollController());
            setUserController(new UserController());
            setBitacoraController(new BitacoraController());
            setEmployeeController(new EmployeeController());
            setSanctionController(new SanctionController());
            setCreatedOn(new Date());
            setUpDates(true);
            setGenericController(new GenericValidationController());
            setLastStableGeneralBox(getGenericController().lastStableGeneralBoxByDate(getLoggedUser()));
            setHayCuadre(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()));

            setPayroll(
                    getController().findPayrollBetweenDates(
                            getStartDate(),
                            getEndDate(),
                            getLoggedUser().getLocation().getId()
                    )
            );

            setUsers(getUserController().findUserActives(getLoggedUser().getLocation().getId()));

            totalPercepcion = 0F;
            totalDeduccion = 0F;
            ahorro = 0D;

            initPayrollObject();

        } catch (Exception e) {
            logger.error(e);
        }

    }

    private void setUpDates(boolean init) {
        Calendar startCalendar = Calendar.getInstance();
        Calendar endCalendar = Calendar.getInstance();

        if (!init) {
            startCalendar.setTime(getStartDate());
            endCalendar.setTime(getEndDate());
        } else {
            startCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            endCalendar.setTime(new Date());
        }

        startCalendar.add(Calendar.HOUR_OF_DAY, 2);
        startCalendar.add(Calendar.MINUTE, 0);
        startCalendar.add(Calendar.SECOND, 0);
        startCalendar.add(Calendar.MILLISECOND, 0);

        endCalendar.add(Calendar.HOUR_OF_DAY, 22);
        endCalendar.add(Calendar.MINUTE, 59);
        endCalendar.add(Calendar.SECOND, 59);
        endCalendar.add(Calendar.MILLISECOND, 0);

        setStartDate(startCalendar.getTime());
        setEndDate(endCalendar.getTime());
    }

    private PayrollController controller;
    private UserController userController;
    private EmployeeController employeeController;
    private SanctionController sanctionController;
    private List<Payroll> payroll;
    private List<User> users;
    private Payroll addPayroll;
    private Payroll selectedPayroll;
    private Date startDate;
    private Date endDate;
    private Date createdOn;
    private BitacoraController bitacoraController;
    private String commentsBitacora;
    private double totalPercepcion;
    private double totalDeduccion;
    private double ahorro;

    private String idUser;

    private GenericValidationController genericController;
    private Date lastStableGeneralBox;
    private boolean hayCuadre;

    public GenericValidationController getGenericController() {
        return genericController;
    }

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

    public Date getLastStableGeneralBox() {
        return lastStableGeneralBox;
    }

    public void setLastStableGeneralBox(Date lastStableGeneralBox) {
        this.lastStableGeneralBox = lastStableGeneralBox;
    }

    public boolean isHayCuadre() {
        return hayCuadre;
    }

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

    public SanctionController getSanctionController() {
        return sanctionController;
    }

    public void setSanctionController(SanctionController sanctionController) {
        this.sanctionController = sanctionController;
    }

    public EmployeeController getEmployeeController() {
        return employeeController;
    }

    public void setEmployeeController(EmployeeController employeeController) {
        this.employeeController = employeeController;
    }

    public double getTotalPercepcion() {
        return totalPercepcion;
    }

    public void setTotalPercepcion(double totalPercepcion) {
        this.totalPercepcion = totalPercepcion;
    }

    public PayrollController getController() {
        return controller;
    }

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

    public List<Payroll> getPayroll() {
        return payroll;
    }

    public void setPayroll(List<Payroll> payroll) {
        this.payroll = payroll;
    }

    public Payroll getAddPayroll() {
        return addPayroll;
    }

    public void setAddPayroll(Payroll addPayroll) {
        this.addPayroll = addPayroll;
    }

    public Payroll getSelectedPayroll() {
        return selectedPayroll;
    }

    public void setSelectedPayroll(Payroll selectedPayroll) {
        this.selectedPayroll = selectedPayroll;
    }

    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 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 String getIdUser() {
        return idUser;
    }

    public void setIdUser(String idUser) {
        this.idUser = idUser;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    public double getTotalDeduccion() {
        return totalDeduccion;
    }

    public void setTotalDeduccion(double totalDeduccion) {
        this.totalDeduccion = totalDeduccion;
    }

    public UserController getUserController() {
        return userController;
    }

    public void setUserController(UserController userController) {
        this.userController = userController;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public double getAhorro() {
        return ahorro;
    }

    public void setAhorro(double ahorro) {
        this.ahorro = ahorro;
    }

    private static final long serialVersionUID = 4735474224887176743L;
    final Logger logger = LogManager.getLogger(PayrollBean.class);

}
