package com.ekom.ekomerp.web.weektask;

import com.ekom.ekomerp.entity.*;
import com.ekom.ekomerp.global.DateTimeUtils;
import com.ekom.ekomerp.global.WeekTaskConverter;
import com.ekom.ekomerp.service.LaboriousnessService;
import com.ekom.ekomerp.service.ManufacturingShiftTaskLineService;
import com.ekom.ekomerp.service.ManufacturingShiftTaskService;
import com.ekom.ekomerp.service.TaskEntryService;
import com.ekom.ekomerp.web.manufacturingshifttask.ManufacturingShiftTaskEdit;
import com.ekom.ekomerp.web.manufacturingshifttask.ManufacturingShiftTaskLookup;
import com.ekom.ekomerp.web.util.ComponentsHelper;
import com.haulmont.bali.util.ParamsMap;
import com.haulmont.chile.core.datatypes.DatatypeRegistry;
import com.haulmont.chile.core.model.MetaPropertyPath;
import com.haulmont.cuba.core.app.DataService;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.gui.ScreenBuilders;
import com.haulmont.cuba.gui.UiComponents;
import com.haulmont.cuba.gui.WindowManager;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.actions.BaseAction;
import com.haulmont.cuba.gui.components.data.value.ContainerValueSource;
import com.haulmont.cuba.gui.model.CollectionContainer;
import com.haulmont.cuba.gui.screen.LoadDataBeforeShow;
import com.haulmont.cuba.gui.screen.UiController;
import com.haulmont.cuba.gui.screen.UiDescriptor;
import com.haulmont.cuba.gui.xml.layout.ComponentsFactory;
import com.haulmont.cuba.security.global.UserSession;
import com.haulmont.reports.entity.Report;
import com.haulmont.reports.gui.ReportGuiManager;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;

import javax.inject.Inject;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Calendar;
import java.util.*;
import java.util.stream.Collectors;

@UiController("ekomerp_WeekTask")
@UiDescriptor("week-task.xml")
@LoadDataBeforeShow
public class WeekTask extends AbstractWindow {
    protected static final String COLUMN_SUFFIX = "Column";
    private static final String TOTAL_COLUMN_ID = "totalColumn";

    @Inject
    protected DatatypeRegistry datatypeRegistry;
    @Inject
    private TimeSource timeSource;
    @Inject
    private Label<String> weekCaption;
    @Inject
    private UserSession userSession;
    @Inject
    protected Actions actions;
    @Inject
    private GroupTable<WeekTaskEntry> weekTaskEntriesDcTable;
    @Inject
    private LinkButton setToday;
    @Inject
    private LinkButton showNextWeek;
    @Inject
    private LinkButton showPreviousWeek;
    @Inject
    private CollectionContainer<WeekTaskEntry> weekTaskEntriesDc;
    @Inject
    private DateField<java.sql.Date> dateField;
    @Inject
    private ComponentsFactory componentsFactory;
    @Inject
    protected WeekTaskConverter weekTaskConverter;
    @Inject
    private LookupPickerField<Brigade> brigadeLookupPickerField;
    protected Date initDate;

    public void setFirstDayOfWeek(Date firstDayOfWeek) {
        this.firstDayOfWeek = firstDayOfWeek;
    }

    public void setLastDayOfWeek(Date lastDayOfWeek) {
        this.lastDayOfWeek = lastDayOfWeek;
    }

    protected Date firstDayOfWeek;
    protected Date lastDayOfWeek;
    protected Date monday;
    protected Date tuesday;
    protected Date wednesday;
    protected Date thursday;
    protected Date friday;
    protected Date saturday;
    protected Integer weekNumber;
    protected String operation = "";
    protected List<WeekTaskEntry> initWeekTaskEntries = new ArrayList<>();
    @Inject
    private Button removeButton;
    @Inject
    private Metadata metadata;
    @Inject
    private TaskEntryService taskEntryService;
    @Inject
    private ManufacturingShiftTaskService manufacturingShiftTaskService;
    @Inject
    private ManufacturingShiftTaskLineService manufacturingShiftTaskLineService;
    @Inject
    private LaboriousnessService laboriousnessService;
    @Inject
    private Button reportButton;
    @Inject
    protected DataService dataService;
    @Inject
    private  ButtonsPanel buttonsPanel;
    @Inject
    protected ReportGuiManager reportGuiManager = AppBeans.get(ReportGuiManager.class);
    @Inject
    protected UiComponents uiComponents;
    @Inject
    protected ScreenBuilders screenBuilders;
    @Inject
    protected MetaPropertyPath metaPropertyPath;

    protected Map<String, Label> totalLabelsMap = new HashMap<>();

    @Override
    protected void init(InitEvent initEvent) {
        initDate = (initDate!=null ? initDate: timeSource.currentTimestamp());
        weekTaskEntriesDcTable.getColumns().forEach(weekTaskEntryColumn -> {
            if (!weekTaskEntryColumn.isEditable()) {
                weekTaskEntryColumn.setColumnGenerator(entity->{
                    Label<String> label =  componentsFactory.createComponent(Label.class);
                    Object val = entity.getValueEx(weekTaskEntryColumn.getStringId());
                    label.setValue(String.valueOf(val));
                    return label;
                });
            }
        });
        setWeekRange(DateTimeUtils.getFirstDayOfWeek(initDate));
        weekTaskEntriesDcTable.setSettingsEnabled(false);
        updateWeekCaption();
        fillExistingTaskEntries();
        initWeekEntriesTable();
        initDateChangeComponents();
        initBrigadeComponent();
        updateDayColumnsCaptions();
        removeButton.setEnabled(false);
        removeButton.setAction(weekTaskEntriesDcTable.getAction("remove"));
        weekTaskEntriesDc.addItemChangeListener(e->{
           if (weekTaskEntriesDcTable.getSelected()!=null){
               removeButton.setEnabled(true);
           }else{
               removeButton.setEnabled(false);
           }
        });
    }

    @Override
    public void ready() {
        setWeekRange(DateTimeUtils.getFirstDayOfWeek(initDate));
        updateWeek();
        addDistinctInitTaskEntries(initWeekTaskEntries);
        weekTaskEntriesDcTable.repaint();
        super.ready();
    }

    protected void initBrigadeComponent(){
//        brigadesDl.load();
        brigadeLookupPickerField.addValueChangeListener(e->{
            updateWeekCaption();
            if(hasUnsavedData()){
                showOptionDialog(
                        messages.getMainMessage("closeUnsaved.caption"),
                        getMessage("notification.unsavedData"),
                        MessageType.CONFIRMATION,
                        new Action[]{
                                new DialogAction(DialogAction.Type.OK) {
                                    @Override
                                    public void actionPerform(Component component) {
                                        fillExistingTaskEntries();
                                        weekTaskEntriesDcTable.repaint();
                                    }
                                },
                                new DialogAction(DialogAction.Type.CANCEL)
                        }
                );
            } else {
                fillExistingTaskEntries();
                weekTaskEntriesDcTable.repaint();
            }
        });

    }
    protected void initDateChangeComponents() {
        setToday.setAction(new CheckUnsavedAction("") {
            @Override
            public void doAction() {
                super.doAction();
                setToday();
            }
        });

        showNextWeek.setAction(new CheckUnsavedAction("") {
            @Override
            public void doAction() {
                showNextWeek();
            }
        });

        showPreviousWeek.setAction(new CheckUnsavedAction("") {
            @Override
            public void doAction() {
                showPreviousWeek();
            }
        });
        brigadeLookupPickerField.addValueChangeListener(e->{
            if(brigadeLookupPickerField.getValue()!=null){
                buttonsPanel.setEnabled(true);
            }else{
                buttonsPanel.setEnabled(false);
            }
        });


        dateField.addValueChangeListener(e -> {
            if (hasUnsavedData()) {
                showOptionDialog(
                        messages.getMainMessage("closeUnsaved.caption"),
                        getMessage("notification.unsavedData"),
                        MessageType.CONFIRMATION,
                        new Action[]{
                                new DialogAction(DialogAction.Type.OK) {
                                    @Override
                                    public void actionPerform(Component component) {
                                        setWeekRange(DateTimeUtils.getFirstDayOfWeek(e.getValue()));
                                        updateWeek();
                                    }
                                },
                                new DialogAction(DialogAction.Type.CANCEL)
                        }
                );
            } else {
                setWeekRange(DateTimeUtils.getFirstDayOfWeek(e.getValue()));
                updateWeek();
            }
        });
    }

    public void addWeekTask(){
        List<ManufacturingMemoLine> selectedLines = new ArrayList<>();
        openLookup("ekomerp$ManufacturingMemoLine.browse",new Lookup.Handler() {
            @Override
            public void handleLookup(Collection items) {
                if (!items.isEmpty()) {
                    selectedLines.addAll(items);
                    for(ManufacturingMemoLine line:selectedLines){
                        WeekTaskEntry weekTaskEntry = metadata.create(WeekTaskEntry.class);
                        weekTaskEntry.setManufacturingMemoLine(line);
                        weekTaskEntry.setBrigade(brigadeLookupPickerField.getValue());
                        weekTaskEntry.setLaboriosness(BigDecimal.valueOf(laboriousnessService.getLaboriousnessByProductAndOperation(line.getProduct(),brigadeLookupPickerField.getValue().getOperation()).get(0).getValue()));
                        weekTaskEntriesDc.getMutableItems().add(weekTaskEntry);
                    }
                }
            }

        }, WindowManager.OpenType.DIALOG.setCloseOnClickOutside(true).setResizable(true).setHeight("75%").setWidth("75%"), ParamsMap.of(
                "brigade", brigadeLookupPickerField.getValue(),
                "added", weekTaskEntriesDc.getItems().stream()
                        .map(line -> line.getManufacturingMemoLine())
                        .collect(Collectors.toList())
        ));
    }


    public void submitAll() {
        Collection<WeekTaskEntry> weekTaskEntries = weekTaskEntriesDc.getItems();
        if (!weekTaskEntries.isEmpty()) {
            CommitContext commitContext = new CommitContext();
            for (WeekTaskEntry weekTaskEntry : weekTaskEntries) {
                int dayWithTaskCounter = 0;
                for (final DayOfWeekEnum day : DayOfWeekEnum.values()) {
                    Integer dayOfWeekPlan = weekTaskEntry.getDayOfWeekTaskPlan(day);
                    Integer dayOfWeekFact = weekTaskEntry.getDayOfWeekTaskFact(day);
                    if (dayOfWeekPlan!=null||dayOfWeekFact!=null) {
                        Integer quantityPlan = dayOfWeekPlan!=null?dayOfWeekPlan:0;
                        Integer quantityFact = dayOfWeekFact!=null?dayOfWeekFact:0;
                        ManufacturingShiftTask
                                shiftTask = manufacturingShiftTaskService.getShiftTask(weekTaskEntry.getBrigade(),DateTimeUtils.getSpecificDayOfWeek(firstDayOfWeek, day.getJavaCalendarDay()));
                        if(shiftTask==null){
                            shiftTask = manufacturingShiftTaskService.createManufacturingShiftTask(weekTaskEntry.getBrigade(),DateTimeUtils.getSpecificDayOfWeek(firstDayOfWeek, day.getJavaCalendarDay()));
                        }
                        List<TaskEntry> existingEntries = weekTaskEntry.getDayOfWeekTaskEntries(day);
                        TaskEntry taskEntry = existingEntries != null ? existingEntries.get(0) : metadata.create(TaskEntry.class);
                        taskEntry.setManufacturingShiftTask(shiftTask);
                        taskEntry.setManufacturingMemoLine(weekTaskEntry.getManufacturingMemoLine());
                        taskEntry.setBrigade(weekTaskEntry.getBrigade());
                        taskEntry.setQuantityPlan(quantityPlan);
                        taskEntry.setQuantityFact(quantityFact);
                        List<Laboriousness> laboriousnesses = laboriousnessService.getLaboriousnessByProductAndOperation(weekTaskEntry.getManufacturingMemoLine().getProduct(),weekTaskEntry.getBrigade().getOperation());
                        if(laboriousnesses!=null&&!laboriousnesses.isEmpty()) {
                            taskEntry.setLaboriousness(BigDecimal.valueOf(laboriousnessService.getLaboriousnessByProductAndOperation(weekTaskEntry.getManufacturingMemoLine().getProduct(), weekTaskEntry.getBrigade().getOperation()).get(0).getValue()));
                        }
                        dayWithTaskCounter++;
                        commitContext.getCommitInstances().add(taskEntry);
                    }
                    if (dayOfWeekPlan!=null||dayOfWeekFact!=null||
                            weekTaskEntry.getDayOfWeekTaskEntries(day)!=null) {
                        dayWithTaskCounter++;
                    }

                }
                if(dayWithTaskCounter==0){
                    ManufacturingShiftTask
                            shiftTask = manufacturingShiftTaskService.getShiftTask(weekTaskEntry.getBrigade(),DateTimeUtils.getSpecificDayOfWeek(firstDayOfWeek, DayOfWeekEnum.MONDAY.getJavaCalendarDay()));
                    if(shiftTask==null){
                        shiftTask = manufacturingShiftTaskService.createManufacturingShiftTask(weekTaskEntry.getBrigade(),DateTimeUtils.getSpecificDayOfWeek(firstDayOfWeek, DayOfWeekEnum.MONDAY.getJavaCalendarDay()));
                    }
                    List<TaskEntry> existingEntries = weekTaskEntry.getDayOfWeekTaskEntries(DayOfWeekEnum.MONDAY);
                    TaskEntry taskEntry = existingEntries != null ? existingEntries.get(0) : metadata.create(TaskEntry.class);
                    taskEntry.setManufacturingShiftTask(shiftTask);
                    taskEntry.setManufacturingMemoLine(weekTaskEntry.getManufacturingMemoLine());
                    taskEntry.setBrigade(weekTaskEntry.getBrigade());
                    taskEntry.setQuantityPlan(0);
                    taskEntry.setQuantityFact(0);
                    List<Laboriousness> laboriousnesses = laboriousnessService.getLaboriousnessByProductAndOperation(weekTaskEntry.getManufacturingMemoLine().getProduct(),weekTaskEntry.getBrigade().getOperation());
                    if(laboriousnesses!=null&&!laboriousnesses.isEmpty()) {
                        taskEntry.setLaboriousness(BigDecimal.valueOf(laboriousnessService.getLaboriousnessByProductAndOperation(weekTaskEntry.getManufacturingMemoLine().getProduct(), weekTaskEntry.getBrigade().getOperation()).get(0).getValue()));
                    }
                    commitContext.getCommitInstances().add(taskEntry);
                }
            }
            getDsContext().getDataSupplier().commit(commitContext);
            updateWeek();
        }
    }

    protected void removeTaskEntries(List<TaskEntry> taskEntries) {
        CommitContext commitContext = new CommitContext();
        for (TaskEntry taskEntry : taskEntries) {
            if (!PersistenceHelper.isNew(taskEntry)) {
                commitContext.getRemoveInstances().add(taskEntry);
//                Collection<TaskEntry> taskEntryCollection = taskEntryService.getTaskEntriesByManufacturingShiftTask(taskEntry.getManufacturingShiftTask());
//                Collection<ManufacturingShiftTaskLine> manufacturingShiftTaskLines = manufacturingShiftTaskLineService.getManufacturingShiftTaskLinesByManufacturingShiftTask(taskEntry.getManufacturingShiftTask());
//                if(taskEntryCollection.size()<2&&manufacturingShiftTaskLines.isEmpty()){
//                    commitContext.getRemoveInstances().add(taskEntry.getManufacturingShiftTask());
//                }
            }
        }
        getDsContext().getDataSupplier().commit(commitContext);
    }

    public void onRefreshButtonClick() {
        fillExistingTaskEntries();
        weekTaskEntriesDcTable.repaint();
    }

    public void onReportButtonClick() throws ParseException {
          Map<String,Object> reportParams = new HashMap<>();
          monday = firstDayOfWeek;
          tuesday = Date.from(monday.toInstant().plusSeconds(86400));
          wednesday = Date.from(tuesday.toInstant().plusSeconds(86400));
          thursday = Date.from(wednesday.toInstant().plusSeconds(86400));
          friday = Date.from(thursday.toInstant().plusSeconds(86400));
          saturday = Date.from(friday.toInstant().plusSeconds(86400));
          reportParams.put("monday", firstDayOfWeek);
          reportParams.put("tuesday", tuesday);
          reportParams.put("wednesday", wednesday);
          reportParams.put("friday", friday);
          reportParams.put("saturday",saturday);
          reportParams.put("sunday", lastDayOfWeek);
          reportParams.put("brigade", brigadeLookupPickerField.getValue());
          LoadContext<Report> lContext = new LoadContext<>(Report.class);
          lContext.setQueryString("select r from report$Report r where r.name like '%week Manufacturing plan%'");
          List<Report> reports = dataService.loadList(lContext);
          for (Report report : reports) {
            reportGuiManager.printReport(report, reportParams);
          }
    }

    protected class WeekTaskEntryRemoveAction extends ComponentsHelper.CaptionlessRemoveAction {

        public WeekTaskEntryRemoveAction(ListComponent target) {
            super(target);
        }

        @SuppressWarnings("unchecked")
        @Override
        public void actionPerform(Component component) {
            Set<WeekTaskEntry> entries = target.getSelected();
            if (!entries.isEmpty()) {
                for (WeekTaskEntry entry : entries) {
                    removeTaskEntries(entry.getExistTaskEntries());
                }
            }
            fillExistingTaskEntries();
            weekTaskEntriesDcTable.repaint();
            super.actionPerform(component);
        }
    }

    protected void updateWeekCaption(){
        Calendar cal = Calendar.getInstance();
        cal.setTime(firstDayOfWeek);
        weekNumber=cal.get(Calendar.WEEK_OF_YEAR);
        if(brigadeLookupPickerField.getValue() == null){
            operation = "";

        }else {
           operation = brigadeLookupPickerField.getValue().getOperation().getName();
        }
        weekCaption.setValue(String.format("Неделя %s (%s - %s) %s",weekNumber, DateTimeUtils.getDateFormat().format(firstDayOfWeek),DateTimeUtils.getDateFormat().format(
                lastDayOfWeek), operation));
    }

    protected void setWeekRange(Date start){
        firstDayOfWeek = start;
        lastDayOfWeek = DateTimeUtils.getLastDayOfWeek(firstDayOfWeek);
    }

    protected void updateDayColumnsCaptions(){
        for(Date current = firstDayOfWeek; current.getTime() <= lastDayOfWeek.getTime(); current = DateUtils.addDays(current,1)){
            DayOfWeekEnum day = DayOfWeekEnum.fromCalendarDay(DateTimeUtils.getCalendarDayOfWeek(current));
            String columnId = day.getId();
                    //+ COLUMN_SUFFIX;
            Table.Column<WeekTaskEntry> column = weekTaskEntriesDcTable.getColumn(columnId);
            column.setCaption(ComponentsHelper.getColumnCaption(day.getId(),current));

        }
    }

    public void setToday() {
        setWeekRange(DateTimeUtils.getFirstDayOfWeek(timeSource.currentTimestamp()));
        updateWeek();
    }

    public void showPreviousWeek() {
        setWeekRange(DateUtils.addWeeks(firstDayOfWeek, -1));
        updateWeek();
    }

    public void showNextWeek() {
        setWeekRange(DateUtils.addWeeks(firstDayOfWeek, 1));
        updateWeek();
    }


    protected class CheckUnsavedAction extends AbstractAction {
        public CheckUnsavedAction(String id) {
            super(id);
        }


        @Override
        public void actionPerform(Component component) {
            if (hasUnsavedData()) {
                showOptionDialog(
                        messages.getMainMessage("closeUnsaved.caption"),
                        getMessage("notification.unsavedData"),
                        MessageType.CONFIRMATION,
                        new Action[]{
                                new DialogAction(DialogAction.Type.OK) {
                                    @Override
                                    public void actionPerform(Component component) {
                                        doAction();
                                    }
                                },
                                new DialogAction(DialogAction.Type.CANCEL)
                        }
                );
            } else {
                doAction();
            }
        }

        public void doAction() {

        }
    }

    protected boolean hasUnsavedData() {
        for (WeekTaskEntry weekTaskEntry : weekTaskEntriesDc.getItems()) {
            if (weekTaskEntry.hasFilledTaskPlan() || weekTaskEntry.hasFilledTaskFact() || hasNewEntries(weekTaskEntry)) {
                return true;
            }
        }
        return false;
    }


    protected boolean hasNewEntries(WeekTaskEntry weekTaskEntry) {
        for (TaskEntry taskEntry : weekTaskEntry.getExistTaskEntries()) {
            if (PersistenceHelper.isNew(taskEntry)) {
                return true;
            }
        }
        return false;
    }


    protected void updateWeek() {
        updateWeekCaption();
        fillExistingTaskEntries();
        weekTaskEntriesDcTable.repaint();
        updateDayColumnsCaptions();
    }

    protected void fillExistingTaskEntries() {
        List<TaskEntry> taskEntries = taskEntryService.getTaskEntriesForPeriod(firstDayOfWeek,lastDayOfWeek,brigadeLookupPickerField.getValue());
        List<WeekTaskEntry> weekTaskEntries = weekTaskConverter.convertFromTaskEntries(taskEntries);
        weekTaskEntriesDc.setItems(weekTaskEntries);
    }

    protected void initWeekEntriesTable() {
        weekTaskEntriesDcTable.addAction(new WeekTaskEntryRemoveAction(weekTaskEntriesDcTable));
        initDaysColumns();
        initTotalColumns();
    }


    protected void openTaskEntryEditor(TaskEntry taskEntry) {
//        final TaskEntryEdit editor = (TaskEntryEdit)
                openEditor("ekomerp_TaskEntry.edit", taskEntry, WindowManager.OpenType.DIALOG).addListener(actionId -> {
            if (COMMIT_ACTION_ID.equals(actionId)) {
                updateWeek();
            }
        });
    }

    protected void openShiftTaskEditor(TaskEntry taskEntry) {
//        final TaskEntryEdit editor = (TaskEntryEdit)
        ManufacturingShiftTaskEdit manufacturingShiftTaskEdit = (ManufacturingShiftTaskEdit) openEditor("ekomerp$ManufacturingShiftTask.edit", taskEntry.getManufacturingShiftTask(), WindowManager.OpenType.DIALOG);
        manufacturingShiftTaskEdit.setFocusComponent("taskEntriesTable");
        manufacturingShiftTaskEdit.selectTaskEntriesTableLine(taskEntry);
        manufacturingShiftTaskEdit.addListener(actionId -> {
//            if (COMMIT_ACTION_ID.equals(actionId)) {
//                updateWeek();
//            }
        });
    }

    protected void initDaysColumns() {
        for (Date current = firstDayOfWeek; current.getTime() <= lastDayOfWeek.getTime(); current = DateUtils.addDays(current, 1)) {
            final DayOfWeekEnum day = DayOfWeekEnum.fromCalendarDay(DateUtils.toCalendar(current).get(Calendar.DAY_OF_WEEK));
            final String columnId = day.getId() ;
 //                   + COLUMN_SUFFIX;
            weekTaskEntriesDcTable.addGeneratedColumn(columnId, new Table.ColumnGenerator<WeekTaskEntry>() {
                        @Override
                        public Component generateCell(final WeekTaskEntry entity) {
                            List<TaskEntry> taskEntries = entity.getDayOfWeekTaskEntries(day);
                            if (CollectionUtils.isEmpty(taskEntries) || taskEntries.size() == 1 && PersistenceHelper.isNew(taskEntries.get(0))) {
                                return createTextFieldForTaskInput(entity);
                            }
                            else {
                                return createLinkAndActionsForExistingEntry(entity, taskEntries);
                            }
                        }

                        private Component createLinkAndActionsForExistingEntry(WeekTaskEntry weekTaskEntry, List<TaskEntry> taskEntries) {
                            HBoxLayout hBox = componentsFactory.createComponent(HBoxLayout.class);
                            hBox.setSpacing(true);

                            if (taskEntries.size() == 1) {
                                createLinkToSingleTimeEntry(weekTaskEntry, taskEntries, hBox);
                            } else {
                                createLinkToMultipleTimeEntries(weekTaskEntry, hBox, taskEntries.get(0).getManufacturingShiftTask().getDate());
                            }
                            createRemoveButton(weekTaskEntry, hBox);

                            return hBox;
                        }

                        private void createRemoveButton(final WeekTaskEntry weekTaskEntry, HBoxLayout hBox) {
                            LinkButton removeButton = componentsFactory.createComponent(LinkButton.class);
                            removeButton.setIcon("icons/remove.png");
                            removeButton.setAlignment(Alignment.MIDDLE_RIGHT);
                            removeButton.setAction(new ComponentsHelper.CustomRemoveAction("taskEntryRemove", getFrame()) {
                                @Override
                                protected void doRemove() {
                                    removeTaskEntries(weekTaskEntry.getDayOfWeekTaskEntries(day));
                                    weekTaskEntry.changeDayOfWeekTaskEntries(day, null);
                                    weekTaskEntriesDcTable.repaint();
                                }
                            });
                            hBox.add(removeButton);
                        }

                        private void createLinkToMultipleTimeEntries(final WeekTaskEntry weekTaskEntry, HBoxLayout hBox, final Date date) {
                            LinkButton linkButton = uiComponents.create(LinkButton.class);
                            String planQuantity = String.valueOf(weekTaskEntry.getTotalPlanForDay(day));
                            String factQuantity = String.valueOf(weekTaskEntry.getTotalFactForDay(day));
                            String caption = planQuantity+"("+factQuantity+")";
                            linkButton.setCaption(caption);
                            linkButton.setAction(new BaseAction("edit").withHandler(actionPerformedEvent -> {
                                ManufacturingShiftTaskLookup manufacturingShiftTaskLookup = (ManufacturingShiftTaskLookup) screenBuilders.lookup(ManufacturingShiftTask.class,WeekTask.this)
                                        .build();
                                manufacturingShiftTaskLookup.setTaskEntries(weekTaskEntry.getDayOfWeekTaskEntries(day));
                                manufacturingShiftTaskLookup.show();
                            }));
                            hBox.add(linkButton);
                        }

                        private void createLinkToSingleTimeEntry(final WeekTaskEntry weekTaskEntry, List<TaskEntry> taskEntries, HBoxLayout hBox) {
                            final TaskEntry taskEntry = taskEntries.get(0);
                            final LinkButton linkButton = componentsFactory.createComponent(LinkButton.class);
                            String planQuantity = String.valueOf(weekTaskEntry.getTotalPlanForDay(day));
                            String factQuantity = String.valueOf(weekTaskEntry.getTotalFactForDay(day));
                            String caption = planQuantity+"("+factQuantity+")";
                            linkButton.setCaption(caption);
                            linkButton.setAction(new AbstractAction("edit") {
                                @Override
                                public void actionPerform(Component component) {
//                                    openTaskEntryEditor(taskEntry);
                                    openShiftTaskEditor(taskEntry);
                                }
                            });
                            hBox.add(linkButton);
                        }

                        private Component createTextFieldForTaskInput(WeekTaskEntry weekTaskEntry) {
                            HBoxLayout hBox = componentsFactory.createComponent(HBoxLayout.class);
                            hBox.setSpacing(true);
                            hBox.setWidth("100%");
                            TextField<Integer> taskPlanField = uiComponents.create(TextField.TYPE_INTEGER);
                            taskPlanField.setWidth("100%");
                            taskPlanField.setHeight("22px");
                            hBox.add(taskPlanField);
                            TextField<Integer> taskFactField =  uiComponents.create(TextField.TYPE_INTEGER);
                            taskFactField.setWidth("100%");
                            taskFactField.setHeight("22px");
                            hBox.add(taskFactField);
                            taskPlanField.setValueSource(new ContainerValueSource(weekTaskEntriesDcTable.getInstanceContainer(weekTaskEntry),day.getId() + "Plan"));
                            taskFactField.setValueSource(new ContainerValueSource(weekTaskEntriesDcTable.getInstanceContainer(weekTaskEntry),day.getId() + "Fact"));
                            List<TaskEntry> taskEntries = weekTaskEntry.getDayOfWeekTaskEntries(day);
                            if(taskEntries!=null&&!taskEntries.isEmpty()) {
                                taskPlanField.setValue(weekTaskEntry.getTotalPlanForDay(day));
                                taskFactField.setValue(weekTaskEntry.getTotalFactForDay(day));
                            }else{
//                                taskPlanField.setValue(" ");
//                                taskFactField.setValue(" ");
                            }
                            return hBox;
                        }
                    }
            );
            Table.Column<WeekTaskEntry> column = weekTaskEntriesDcTable.getColumn(columnId);
            column.setWidth(120);

//            Table.Column column = weekTaskEntriesDcTable.getColumn(columnId);
//            column.setAggregation(ComponentsHelper.createAggregationInfo(
//                    projectsService.getEntityMetaPropertyPath(WeeklyReportEntry.class, day.getId()),
//                    new WeeklyReportEntryAggregation()
//            ));
        }
    }
    protected void initTotalColumns() {
        weekTaskEntriesDcTable.addGeneratedColumn(TOTAL_COLUMN_ID, weekTaskEntry -> {
            Label label = uiComponents.create(Label.class);
            label.setValue(weekTaskEntry.getTotalPlan()+"("+weekTaskEntry.getTotalFact()+")");
//            totalLabelsMap.put(ScreensHelper.getCacheKeyForEntity(weekTaskEntry, TOTAL_COLUMN_ID), label);
            return label;
        });
        weekTaskEntriesDcTable.getColumn(TOTAL_COLUMN_ID).setWidth(80);
        weekTaskEntriesDcTable.getColumn(TOTAL_COLUMN_ID).setCaption(messages.getMessage(getClass(), "total"));
        AggregationInfo info = new AggregationInfo();
        info.setPropertyPath(metaPropertyPath);
        info.setStrategy(new WeekTaskTotalAggregation());
        Table.Column column = weekTaskEntriesDcTable.getColumn(TOTAL_COLUMN_ID);
        column.setAggregation(info);
    }
    public void setBrigade(Brigade brigade){
        brigadeLookupPickerField.setValue(brigade);
    }

    public void setDate(Date date){initDate = date;}

    public void addWeekTaskEntries(Collection<ManufacturingMemoLine> manufacturingMemoLines){
            for(ManufacturingMemoLine line:manufacturingMemoLines){
                 List<Laboriousness> laboriousnessList = laboriousnessService.getLaboriousnessByProductAndOperation(line.getProduct(),brigadeLookupPickerField.getValue().getOperation());
                if(!laboriousnessList.isEmpty()) {
//                    Collection<WeekTaskEntry> weekTaskEntries = weekTaskEntriesDc.getItems();
                    WeekTaskEntry weekTaskEntry = metadata.create(WeekTaskEntry.class);
//                    Boolean weekTaskEntriesIsEmpty = true;
//                    for(WeekTaskEntry weekTaskEntry1:weekTaskEntries){
//                        if(weekTaskEntry1.getManufacturingMemoLine().equals(line)){
//                            weekTaskEntriesIsEmpty = false;
//                            break;
//                        }
//                    }
//                    if(weekTaskEntriesIsEmpty == true){
                        weekTaskEntry.setManufacturingMemoLine(line);
                        weekTaskEntry.setBrigade(brigadeLookupPickerField.getValue());
                        weekTaskEntry.setLaboriosness(BigDecimal.valueOf(laboriousnessList.get(0).getValue()));
                        initWeekTaskEntries.add(weekTaskEntry);
//                    }
                }
            }
    }

    public void addDistinctInitTaskEntries(List<WeekTaskEntry> initWeekTaskEntries){
        for(WeekTaskEntry weekTaskEntry:initWeekTaskEntries){
            Boolean weekTaskEntryExists = false;
            for(WeekTaskEntry weekTaskEntry1:weekTaskEntriesDc.getItems()){
                if(weekTaskEntry1.getManufacturingMemoLine().equals(weekTaskEntry.getManufacturingMemoLine())){
                    weekTaskEntryExists = true;
                    break;
                }
            }
            if(weekTaskEntryExists == false){
                weekTaskEntriesDc.getMutableItems().add(weekTaskEntry);
            }
         }
    }

}