service.actions.OrderSearch.java Source code

Java tutorial

Introduction

Here is the source code for service.actions.OrderSearch.java

Source

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

import datastructure.OrderListData;
import datastructure.CountOrders;
import datastructure.OrderSearchData;
import entity.Admin;
import entity.Author;
import entity.AuthorSalary;
import entity.Branch;
import entity.Direction;
import entity.Order;
import entity.OrderType;
import entity.OrderView;
import entity.PaymentType;
import entity.User;
import entity.orderStatus.OrderStatus;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mvc.view.OrderCssManager;
import mvc.view.ViewResolver;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.stereotype.Component;
import persistence.AuthorRejectDao;
import persistence.OrderViewDao;
import project.SystemVariables;
import rights.BranchRights;
import rights.BranchRightsHolder;
import rights.Rights;
import rights.UserRightsUtil;
import service.AuthorService;
import service.DirectionService;
import service.OrderService;
import service.OrderTypeService;
import service.PaymentTypeService;
import support.AuthManager;
import support.DateFormatter;
import support.DateUtils;
import support.StringAdapter;

/**
 *
 * ?? 
 *
 * @author Rice Pavel
 */
@Component
@Scope(value = "prototype")
public class OrderSearch {

    protected Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private persistence.OrderDao orderDao;

    @Autowired
    private AuthManager authManager;

    @Autowired
    private AuthorRejectDao rejectionDao;

    @Autowired
    private OrderService orderService;

    @Autowired
    private BranchRightsHolder branchRightsHolder;

    @Autowired
    private AuthorService authorService;

    @Autowired
    private OrderViewDao orderViewDao;

    @Autowired
    private DirectionService directionService;

    @Autowired
    private OrderTypeService orderTypeService;

    @Autowired
    private PaymentTypeService paymentTypeService;

    @Autowired
    WebInvocationPrivilegeEvaluator webPrivs;

    /**
     * ?  ? , ? 
     *
     * @param authorIdForSearch   ? ?.    null
     * @param branchId   ? ?.    null
     * @return
     */
    public datastructure.CountOrders getCountForMenu(Long authorIdForSearch, Long branchId,
            List<OrderStatus> rightStatusList) {
        Author authorForSearch = null;
        if (authorIdForSearch != null) {
            authorForSearch = authorService.find(authorIdForSearch);
        }
        User authUser = authManager.getCurrentUser();
        Set<Long> branchIds = branchRightsHolder.getBranchIds(BranchRights.SEARCH_ORDER);
        if (authUser instanceof Admin) {
            List<Object[]> list = orderDao.getCountsForAdmin(branchIds, authorForSearch, null, branchId,
                    rightStatusList);
            datastructure.CountOrders data = transformToData(list);
            data.countHaveCost = getCountHaveCostForAdmin(branchIds, authorForSearch, branchId, rightStatusList);
            long countAll = 0L;
            for (Long l : data.counts.values()) {
                countAll += l;
            }
            data.countAll = countAll;
            return data;
        } else {
            Author author = (Author) authUser;
            return getCountForAuthorBySql(author, branchIds, rightStatusList);
        }
    }

    private Long getCountHaveCostForAdmin(Set<Long> branchIds, Author authorForSearch, Long branchId,
            List<OrderStatus> rightStatusList) {
        List<Object[]> list = orderDao.getCountsForAdmin(branchIds, authorForSearch, OrderStatus.PRICED, branchId,
                rightStatusList);
        Long count = 0L;
        for (Object[] arr : list) {
            Long val = getLong(arr[1]);
            if (val != null) {
                count = val;
            }
        }
        return count;
    }

    public List<Date> getDeadlineDatesForAuthor(List<OrderStatus> rightStatusList) {
        List<Date> dateList = new ArrayList();
        User authUser = authManager.getCurrentUser();
        if (authUser instanceof Author) {
            List<OrderStatus> statusList = statusListForCalendar();
            Set<Long> rightBranchIds = branchRightsHolder.getBranchIds(BranchRights.SEARCH_ORDER);
            Date dateFrom = DateUtils.startOfDay(new Date());
            OrderSearchData searchData = new OrderSearchData();
            List<Map> dataMap;
            Author author = (Author) authUser;
            searchData.deadlineFrom = dateFrom;
            dataMap = orderDao.getForAuthorBySql(author, null, getAuthorDirectionIds(author), rightBranchIds,
                    searchData, null, null, statusList, rightStatusList, false);
            List<OrderListData> dataList = transformBySqlMap(dataMap);
            for (OrderListData data : dataList) {
                Order order = data.order;
                if (order != null) {
                    if (order.getDeadlineDate() != null) {
                        dateList.add(order.getDeadlineDate());
                    }
                }
            }
        }
        return dateList;
    }

    public List<OrderListData> getFromCalendar(Date date, List<OrderStatus> rightStatusList) {
        if (todayOrLater(date)) {
            List<OrderStatus> statusList = statusListForCalendar();
            Set<Long> rightBranchIds = branchRightsHolder.getBranchIds(BranchRights.SEARCH_ORDER);
            Date dateFrom = DateUtils.startOfDay(date);
            Date dateTo = DateUtils.endOfDay(date);
            OrderSearchData searchData = new OrderSearchData();
            List<Map> dataMap;
            User authUser = authManager.getCurrentUser();
            if (authUser instanceof Admin) {
                searchData.realDateFrom = dateFrom;
                searchData.realDateTo = dateTo;
                dataMap = orderDao.getForAdminBySql(rightBranchIds, null, statusList, searchData,
                        authUser.getUserId(), null, null, rightStatusList, false);
            } else {
                Author author = (Author) authUser;
                searchData.deadlineFrom = dateFrom;
                searchData.deadlineTo = dateTo;
                dataMap = orderDao.getForAuthorBySql(author, null, getAuthorDirectionIds(author), rightBranchIds,
                        searchData, null, null, statusList, rightStatusList, false);
            }
            List<OrderListData> dataList = transformBySqlMap(dataMap);
            return dataList;
        } else {
            return new ArrayList();
        }
    }

    private List<OrderStatus> statusListForCalendar() {
        List<OrderStatus> statusList = new ArrayList();
        statusList.add(OrderStatus.WORKING);
        statusList.add(OrderStatus.REWORK);
        statusList.add(OrderStatus.CHECK);
        statusList.add(OrderStatus.CONFIRMATION);
        return statusList;
    }

    private boolean todayOrLater(Date date) {
        Date current = new Date();
        current = DateUtils.startOfDay(current);
        return (date.equals(current) || date.after(current));
    }

    private CountOrders getCountForAuthorBySql(Author author, Set<Long> branchIds,
            List<OrderStatus> rightStatusList) {
        Map<OrderStatus, Long> counts = new HashMap();
        Set<Long> authorDirectionIds = getAuthorDirectionIds(author);
        for (OrderStatus status : OrderStatus.values()) {
            counts.put(status, orderDao.getCountForAuthor(author, authorDirectionIds, branchIds, status,
                    rightStatusList, false));
        }
        Long countAll = orderDao.getCountForAuthor(author, authorDirectionIds, branchIds, null, rightStatusList,
                false);
        CountOrders data = new CountOrders();
        data.counts = counts;
        data.countAll = countAll;
        return data;
    }

    private datastructure.CountOrders transformToData(List<Object[]> list) {
        datastructure.CountOrders data = new CountOrders();
        for (Object[] arr : list) {
            OrderStatus status = (OrderStatus) arr[0];
            Long count = (Long) arr[1];
            data.counts.put(status, count);
        }
        addNoll(data);
        return data;
    }

    private void addNoll(CountOrders data) {
        for (OrderStatus status : OrderStatus.values()) {
            if (!data.counts.containsKey(status)) {
                data.counts.put(status, 0L);
            }
        }
    }

    /**
     *  ?? 
     *
     * @param rightBrancheIds  ,    
     * @param status ??
     * @param searchData  ? ?
     * @return
     */
    public List<Order> getOrderList(Set<Long> rightBrancheIds, OrderStatus status, OrderSearchData searchData) {
        return _getOrderList(rightBrancheIds, status, searchData, null, null);
    }

    /**
     *  ?? 
     *
     * @param rightBrancheIds  ,  ? ?
     * @param status ??
     * @param searchData  ? ?
     * @param start
     * @param numberOfRecords
     * @return
     */
    public List<OrderListData> getOrderDataList(Set<Long> rightBrancheIds, OrderStatus status,
            datastructure.OrderSearchData searchData, Integer start, Integer numberOfRecords,
            List<OrderStatus> rightStatusList, Boolean overdue) {
        return getDataListBySqlMap(rightBrancheIds, status, searchData, start, numberOfRecords, rightStatusList,
                overdue);
    }

    public List<List<String>> getOrderTestDataList(Set<Long> rightBranchIds, OrderStatus status,
            List<OrderStatus> commonAvailableStatusList, datastructure.OrderSearchData searchData, Integer start,
            Integer numberOfRecords, List<OrderStatus> rightStatusList, Boolean overdue) {
        User authUser = authManager.getCurrentUser();
        if (authUser instanceof Admin) {
            List<List<String>> res = getTestAdminOrderListData(rightBranchIds, status, commonAvailableStatusList,
                    searchData, authUser, start, numberOfRecords, rightStatusList, overdue);
            //log.warn("serviceResCount= "+res.size());
            return res;
        } else {
            return getTestAuthorOrderListData(rightBranchIds, status, commonAvailableStatusList, searchData,
                    authUser, start, numberOfRecords, rightStatusList, overdue);
        }
    }

    /*public List<List<String>> getOrderOrderedDataList(Set<Long> rightBranchIds, OrderStatus status,
        List<OrderStatus> commonAvailableStatusList, datastructure.OrderSearchData searchData,
        Integer start, Integer numberOfRecords, List<OrderStatus> rightStatusList, Boolean overdue) {
    User authUser = authManager.getCurrentUser();
    if (authUser instanceof Admin) {
        List<List<String>> res = getOrderedAdminOrderListData(rightBranchIds, status, commonAvailableStatusList, searchData, authUser, start, numberOfRecords, rightStatusList, overdue);
        //log.warn("serviceResCount= "+res.size());
        return res;
    } else {
        return getTestAuthorOrderListData(rightBranchIds, status, commonAvailableStatusList, searchData, authUser, start, numberOfRecords, rightStatusList, overdue);
    }
    }*/

    private List<List<String>> getTestAuthorOrderListData(Set<Long> rightBranchIds, OrderStatus status,
            List<OrderStatus> commonAvailebleStatusList, OrderSearchData searchData, User authUser, Integer start,
            Integer numberOfRecords, List<OrderStatus> rightStatusList, Boolean overdue) {
        List<List<String>> res = new ArrayList();
        Author author = (Author) authManager.getCurrentUser();
        if (author.getActive()) {
            Set<Long> authorDirectionIds = getAuthorDirectionIds(author);
            ViewResolver vr = new ViewResolver(author, branchRightsHolder);
            OrderCssManager ocm = new OrderCssManager(author);
            HashMap<Long, HashMap<String, Boolean>> br = branchRightsHolder.getBranchRights();
            HashMap<Rights, Boolean> cr = new HashMap();
            for (Rights r : Rights.values()) {
                cr.put(r, UserRightsUtil.isRight(r));
            }
            Authentication a = SecurityContextHolder.getContext().getAuthentication();
            SimpleDateFormat df = new SimpleDateFormat("dd/MM");

            //List<Map>oldRes = orderDao.getForAuthorBySql(author, status, authorDirectionIds, rightBranchIds, searchData, start, numberOfRecords, null, rightStatusList, overdue);
            List<OrderListData> oldRes = transformBySqlMap(
                    orderDao.getForAuthorBySql(author, status, authorDirectionIds, rightBranchIds, searchData,
                            start, numberOfRecords, null, rightStatusList, overdue));

            for (OrderListData oldOrderData : oldRes) {
                List<String> orderData = new ArrayList();
                Order o = oldOrderData.getOrder();
                Long orderId = o.getId();
                String number = o.getNumber();
                List<Direction> directionsData = o.getDirections();
                OrderType orderType = o.getOrderType();
                String subject = o.getSubject();
                Date deadlineDate = o.getDeadlineDate();
                Double authorSalary = o.getAuthor_salary();
                Double paymentSum = o.getPaymentSum();
                OrderStatus orderStatus = o.getStatus();
                Double cost = o.getCost();
                Boolean statusOfUser = o.getStatusOfUser();
                Boolean existReject = oldOrderData.isExistReject();
                int countNotReadyAuthorMessages = oldOrderData.getCountNotReadyAuthorMessages();
                int countAllAuthorMessages = oldOrderData.getCountAllAuthorMesages();
                boolean allowReject = oldOrderData.isAllowReject();
                boolean allowRecoverFromReject = oldOrderData.getAllowRecoverFromReject();

                HashMap<String, Boolean> branchRights = br.get(o.getBranch().getId());

                orderData.add("<tr class=" + ocm.getRowClass(o) + ">");
                String col = "";

                if (cr.get(Rights.TABLE_NUMBER)) {
                    if (branchRights.get("GET_ORDER") && webPrivs.isAllowed("/Order/get", a)) {
                        col = "<td><a href='#' class='orderShow flat' data-id=" + orderId + " data-number=" + number
                                + ">";
                        col += "<p class='order-num'>" + number + "</p></a></td>";
                    } else {
                        col = "<td>" + number + "</td>";
                    }
                    orderData.add(col);
                }

                if (cr.get(Rights.TABLE_DIRECTIONS)) {
                    col = "<td class='directionsTd' data-orderId=" + orderId + ">";
                    for (Direction d : directionsData) {
                        col += d.getName();
                    }
                    col += "</td>";
                    orderData.add(col);
                }

                if (cr.get(Rights.TABLE_TYPE)) {
                    col = "<td><div class='changeDiv dbl-area-select' data-orderId=" + orderId
                            + " data-parameterName='orderType' data-isRight='false'>";
                    col += "<div class='text'>" + orderType.getName() + "</div>";
                    col += "<select>";
                    for (OrderType ot : orderTypeService.getAll()) {
                        col += "<option value=" + ot.getOrderTypeId() + " "
                                + (ot.getOrderTypeId().equals(orderType.getId()) ? "selected" : "") + ">"
                                + ot.getName() + "</option>";
                    }
                    col += "</select></div></td>";
                    orderData.add(col);
                }

                if (cr.get(Rights.TABLE_SUBJECT)) {
                    col = "<td><div class='changeDiv dbl-area-auto' data-orderId=" + orderId
                            + " data-parameterName='subject' data-isRight='false'>";
                    col += "<div class='text'>" + subject + "</div>";
                    col += "<textarea>" + subject + "</textarea></div></td>";
                    orderData.add(col);
                }

                if (cr.get(Rights.TABLE_DATE)) {
                    col = "<td><div data-fromTable='true' class='changeDiv dbl-area' data-orderId=" + orderId
                            + " data-parameterName='deadlineDate' style='width: inherit;' data-isRight='false'>";
                    col += "<div style='font-size: 0.8em;'>" + (deadlineDate != null ? df.format(deadlineDate) : "")
                            + "</div>";
                    //col += "<input type='text' class='date' value=" + (deadlineDate!=null?df.format(deadlineDate):"") + "></div>";
                    orderData.add(col);
                }

                if (cr.get(Rights.TABLE_AUTHOR_SALARY)) {
                    col = "<td>" + (authorSalary != null ? authorSalary : "") + "</td>";
                    orderData.add(col);
                }

                if (cr.get(Rights.TABLE_STATUS)) {
                    col = "<td class=" + ocm.getStatusClass(o, paymentSum)
                            + "><div class='dbl-area-select color' >";
                    col += "<div class='text'>" + vr.getStatusName(orderStatus, existReject, cost, statusOfUser)
                            + "</div>";
                    col += "</div></td>";
                    orderData.add(col);
                }

                if (cr.get(Rights.TABLE_AUTHOR_MESSAGE)) {
                    col = "<td>";
                    if (countNotReadyAuthorMessages != 0) {
                        col += "<p class='circle'>" + countNotReadyAuthorMessages + "</p>";
                    } else {
                        col += "(" + countAllAuthorMessages + ")";
                    }
                    //col += "<br/>";
                    col += "</td>";
                    orderData.add(col);
                }

                if (cr.get(Rights.TABLE_FLAGS)) {
                    col = "<td>";
                    if (allowReject && webPrivs.isAllowed("/Order/reject", a)) {
                        col += "<form action='/Order/reject' class='rejectOrderFromTable'>";
                        col += "<input type='hidden' name='orderId' value=" + orderId + ">";
                        col += "<input type='submit' value='??' name='submit'>";
                        col += "</form>";
                    }
                    if (allowRecoverFromReject && webPrivs.isAllowed("/Order/reject", a)) {
                        col += "<form action='/Order/recoverFromReject' class='recoverFromRejectOrderFromTable'>";
                        col += "<input type='hidden' name='orderId' value=" + orderId + ">";
                        col += "<input type='submit' value='  ' name='submit'>";
                        col += "</form>";
                    }
                    col += "</td>";
                    orderData.add(col);
                }

                orderData.add("</tr>");
                res.add(orderData);
            }
        }
        return res;
    }

    private List<List<String>> getTestAdminOrderListData(Set<Long> rightBranchIds, OrderStatus status,
            List<OrderStatus> commonAvailebleStatusList, OrderSearchData searchData, User authUser, Integer start,
            Integer numberOfRecords, List<OrderStatus> rightStatusList, Boolean overdue) {

        Long starttime = System.currentTimeMillis();

        User currentUser = authManager.getCurrentUser();
        String currentDate = getCurrentDateToString();
        OrderCssManager ocm = new OrderCssManager(currentUser);
        ViewResolver vr = new ViewResolver(currentUser, branchRightsHolder);
        HashMap<Long, HashMap<String, Boolean>> br = branchRightsHolder.getBranchRights();
        HashMap<Rights, Boolean> cr = new HashMap();
        for (Rights r : Rights.values()) {
            cr.put(r, UserRightsUtil.isRight(r));
        }
        List<Long> toWork = branchRightsHolder.getBranches(BranchRights.ORDER_NEW_TO_WORK);
        List<Long> toReject = branchRightsHolder.getBranches(BranchRights.ORDER_NEW_TO_REJECT);
        Authentication a = SecurityContextHolder.getContext().getAuthentication();

        SimpleDateFormat df = new SimpleDateFormat("dd/MM");
        DateFormatter fullDateFormatter = new DateFormatter();

        //LinkedHashMap<Long, HashMap> rawRes = new LinkedHashMap();
        List<List<String>> result = new ArrayList();

        List<Object[]> preRes = orderDao.getTestOrdersAndCountsForAdminBySql(rightBranchIds, status, searchData,
                authUser.getUserId(), start, numberOfRecords, rightStatusList, overdue);

        Set<Long> orderIds = new HashSet();
        for (Object[] rawOrder : preRes) {
            Long orderId = getLong(rawOrder[0]);
            orderIds.add(orderId);
        }

        HashMap<Long, List<HashMap>> otherOrders = new HashMap();
        HashMap<Long, List<HashMap>> orderDirections = new HashMap();
        HashMap<Long, List<HashMap>> orderSalaries = new HashMap();

        //log.warn("searchLogicTime1:" + Long.valueOf(System.currentTimeMillis() - starttime));

        List<Object[]> otherOrdersRawRes = orderDao.getTestOtherOrdersForAdminBySql(orderIds);
        //log.warn("searchLogicTime2:" + Long.valueOf(System.currentTimeMillis() - starttime));
        for (Object[] rawOtherOrder : otherOrdersRawRes) {
            Long orderId = getLong(rawOtherOrder[0]);

            List<HashMap> otherOrdersList = otherOrders.get(orderId);
            if (otherOrdersList == null) {
                otherOrdersList = new ArrayList();
            }
            if (otherOrdersList.size() < 5) {
                HashMap<String, Object> otherOrderData = new HashMap();

                Long otherOrderId = getLong(rawOtherOrder[1]);
                Long otherOrderBranchId = getLong(rawOtherOrder[2]);
                String otherOrderOldId = (String) rawOtherOrder[3];
                String otherOrderNumber = otherOrderOldId;
                if (otherOrderOldId == null || otherOrderOldId.equals("")) {
                    otherOrderNumber = otherOrderId.toString();
                }

                otherOrderData.put("orderId", otherOrderId);
                otherOrderData.put("branchId", otherOrderBranchId);
                otherOrderData.put("number", otherOrderNumber);
                otherOrdersList.add(otherOrderData);
                otherOrders.put(orderId, otherOrdersList);
            }
        }

        List<Object[]> orderDirectionRawRes = orderDao.getTestDirectionsForAdminBySql(orderIds);
        for (Object[] rawDirectionData : orderDirectionRawRes) {
            Long orderId = getLong(rawDirectionData[0]);

            List<HashMap> directionsList = orderDirections.get(orderId);
            if (directionsList == null) {
                directionsList = new ArrayList();
            }
            HashMap<String, Object> directionData = new HashMap();

            Long directionId = getLong(rawDirectionData[1]);
            String directionName = (String) rawDirectionData[2];

            directionData.put("directionId", directionId);
            directionData.put("directionName", directionName);
            directionsList.add(directionData);
            orderDirections.put(orderId, directionsList);
        }

        List<Object[]> authorSalariesRawRes = orderDao.getTestSalariesForAdminBySql(orderIds);
        for (Object[] rawSalaryData : authorSalariesRawRes) {
            Long orderId = getLong(rawSalaryData[0]);

            List<HashMap> salaryList = orderSalaries.get(orderId);
            if (salaryList == null) {
                salaryList = new ArrayList();
            }
            HashMap<String, Object> salaryData = new HashMap();

            Double authorSalaryCost = (Double) rawSalaryData[1];
            Long authorSalaryId = getLong(rawSalaryData[2]);

            salaryData.put("salaryId", authorSalaryId);
            salaryData.put("cost", authorSalaryCost);
            salaryList.add(salaryData);
            orderSalaries.put(orderId, salaryList);
        }
        //log.warn("rawRes= "+rawRes.size());

        /*for (Map.Entry<Long, HashMap> order : rawRes.entrySet()) {
         Long orderId = order.getKey();
         HashMap orderData = order.getValue();
         List<HashMap> otherOrdersData = otherOrders.get(orderId);
         List<HashMap> directionsData = orderDirections.get(orderId);
         List<HashMap> SalaryData = orderSalaries.get(orderId);
         if (otherOrdersData == null) {
         otherOrdersData = new ArrayList();
         }
         if (directionsData == null) {
         directionsData = new ArrayList();
         }
         if (SalaryData == null) {
         SalaryData = new ArrayList();
         }
         orderData.put("otherOrders", otherOrdersData);
         orderData.put("directions", directionsData);
         orderData.put("authorSalaries", SalaryData);
            
         result.add(orderData);
         }*/
        for (Object[] rawOrder : preRes) {
            List<String> orderData = new ArrayList();
            Long orderId = getLong(rawOrder[0]);

            Date deadlineDate = (Date) rawOrder[1];
            Date realDate = (Date) rawOrder[2];
            String clientFio = (String) rawOrder[3];
            String clientPhone = (String) rawOrder[4];
            String clientEmail = (String) rawOrder[5];
            String city = (String) rawOrder[6];
            Double cost = (Double) rawOrder[7];
            Double authorSalary = (Double) rawOrder[8];
            Boolean firstFlag = (Boolean) rawOrder[9];
            Boolean secondFlag = (Boolean) rawOrder[10];
            String statusStr = (String) rawOrder[11];
            OrderStatus orderStatus = OrderStatus.valueOf(statusStr);
            Long branchId = getLong(rawOrder[12]);
            Long orderTypeId = getLong(rawOrder[13]);
            Long authorId = getLong(rawOrder[14]);
            String comment = (String) rawOrder[15];
            String authorComment = (String) rawOrder[16];
            Date readyDate = (Date) rawOrder[17];
            String commentToAuthorSalary = (String) rawOrder[18];
            Boolean unloadedInShop = (Boolean) rawOrder[19];
            Long parentOrderId = getLong(rawOrder[20]);
            Boolean selected = (Boolean) rawOrder[21];
            Boolean childSelected = (Boolean) rawOrder[22];
            Boolean statusOfUser = (Boolean) rawOrder[23];
            /*log.warn("");
             log.warn("oid:"+orderId);
             log.warn("statusOfUser:"+statusOfUser);*/

            String oldId = (String) rawOrder[24];
            String number = oldId;
            if (oldId == null || oldId.equals("")) {
                number = orderId.toString();
            }

            String subject = (String) rawOrder[25];
            Date orderDate = (Date) rawOrder[26];
            String branchName = (String) rawOrder[27];
            String abbrevation = (String) rawOrder[28];
            String orderTypeName = (String) rawOrder[29];
            String authorLogin = (String) rawOrder[30];
            String authorName = (String) rawOrder[31];
            String authorSurname = (String) rawOrder[32];

            Boolean existReject = false;

            BigInteger bi = (BigInteger) rawOrder[33];
            Integer countMess = (bi != null ? bi.intValue() : null);

            Double paymentSum = (Double) rawOrder[34];
            paymentSum = (paymentSum != null ? paymentSum : 0D);

            BigInteger countAllAuthorMess = (BigInteger) rawOrder[35];
            BigInteger countAllAdminMess = (BigInteger) rawOrder[36];
            BigInteger countNotReadyAdminMess = (BigInteger) rawOrder[37];
            BigInteger countAllDelegateMess = (BigInteger) rawOrder[38];
            BigInteger countNotReadyDelegateMess = (BigInteger) rawOrder[39];

            BigInteger countNotReadyAuthorMessages = new BigInteger("0");
            if (countMess != null) {
                countNotReadyAuthorMessages = bi;
            }
            if (countNotReadyDelegateMess != null) {
                countNotReadyAuthorMessages = countNotReadyAuthorMessages.add(countNotReadyDelegateMess);
            }

            List<OrderStatus> availableStatusList = new ArrayList(commonAvailebleStatusList);
            if (statusStr.equals(OrderStatus.NEW.name())) {
                if (!toWork.contains(branchId)) {
                    availableStatusList.remove(OrderStatus.WORKING);
                }
                if (!toReject.contains(branchId)) {
                    availableStatusList.remove(OrderStatus.REJECTION);
                }
            }

            List<HashMap> otherOrdersData = otherOrders.get(orderId);
            List<HashMap> directionsData = orderDirections.get(orderId);
            List<HashMap> SalaryData = orderSalaries.get(orderId);
            if (otherOrdersData == null) {
                otherOrdersData = new ArrayList();
            }
            if (directionsData == null) {
                directionsData = new ArrayList();
            }
            if (SalaryData == null) {
                SalaryData = new ArrayList();
            }

            HashMap<String, Boolean> branchRights = br.get(branchId);
            boolean rightChangeOrder = false;
            if ((childSelected == null || !childSelected) && branchRights.get("CHANGE_ORDER")
                    && webPrivs.isAllowed("/Order/change", a)) {
                rightChangeOrder = true;
            }

            String rowClass = ocm.getRowClass(selected, authorId, cost, statusOfUser, orderStatus, SalaryData,
                    null);

            orderData.add("<tr class=" + rowClass + ">");

            /*log.warn("sou:"+statusOfUser+";");
             log.warn("cost:"+StringAdapter.getString(cost)+";");
             if(cost!=null){
             log.warn("costcomp:"+(cost>0D)+";");
             }*/
            String col = "";
            if (cr.get(Rights.TABLE_FLAGS)) {
                col = "<td><a class='info red " + (firstFlag != null && firstFlag ? "active" : "")
                        + "' data-orderId=" + orderId + " onclick='return changeFirstFlag(this);'></a>";
                col += "<br/>";
                col += "<a class='info blue " + (secondFlag != null && secondFlag ? "active" : "")
                        + "' data-orderId=" + orderId + " onclick='return changeSecondFlag(this);'></a></td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_NUMBER)) {
                if (branchRights.get("GET_ORDER") && webPrivs.isAllowed("/Order/get", a)) {
                    col = "<td><a href='#' class='orderShow flat' data-id=" + orderId + " data-number=" + number
                            + ">";
                    col += "<p class='order-num'><span class='orderCount'>" + abbrevation + "</span>" + number
                            + "</p></a></td>";
                } else {
                    col = "<td>" + StringAdapter.getString(number) + "</td>";
                }
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_DIRECTIONS)) {
                col = "<td class='directionsTd' data-orderId=" + orderId + ">";
                if (branchRights.get("ORDER_CHANGE_DIRECTIONS") && (childSelected == null || !childSelected)) {
                    col += "<div class='directionDiv add-order-select' data-orderId=" + orderId + ">";
                    for (HashMap dir : directionsData) {
                        col += "<select class='directionSelect' data-orderId=" + orderId + " data-value="
                                + dir.get("directionId") + ">";
                        col += "<option value=''></option>";
                        for (Direction d : directionService.getAll()) {
                            col += "<option value=" + d.getDirectionId() + " "
                                    + (d.getDirectionId().equals(dir.get("directionId")) ? "selected" : "") + ">"
                                    + d.getName() + "</option>";
                        }
                        col += "</select></br>";
                    }
                    col += "</div>";
                    col += "<a class='add-direction addDirectionSubmit info add active' data-orderId=" + orderId
                            + ">+</a>";
                } else {
                    for (HashMap d : directionsData) {
                        col += d.get("directionName");
                    }
                }
                col += "</td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_TYPE)) {
                col = "<td><div class='changeDiv dbl-area-select' data-orderId=" + orderId
                        + " data-parameterName='orderType' data-isRight=" + rightChangeOrder + ">";
                col += "<div class='text'>" + orderTypeName + "</div>";
                col += "<select>";
                for (OrderType ot : orderTypeService.getAll()) {
                    col += "<option value=" + ot.getOrderTypeId() + " "
                            + (ot.getOrderTypeId().equals(orderTypeId) ? "selected" : "") + ">" + ot.getName()
                            + "</option>";
                }
                col += "</select></div></td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_SUBJECT)) {
                col = "<td><div class='changeDiv dbl-area-auto' data-orderId=" + orderId
                        + " data-parameterName='subject' data-isRight=" + rightChangeOrder + ">";
                col += "<div class='text'>" + subject + "</div>";
                col += "<textarea>" + subject + "</textarea></div></td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_DATE)) {
                col = "<td><div data-fromTable='true' class='changeDiv dbl-area' data-orderId=" + orderId
                        + " data-parameterName='deadlineDate' style='width: inherit;' data-isRight="
                        + rightChangeOrder + ">";
                col += "<div style='font-size: 0.8em;'>" + (deadlineDate != null ? df.format(deadlineDate) : "")
                        + "</div>";
                col += "<input type='text' class='date' value="
                        + (deadlineDate != null ? fullDateFormatter.date(deadlineDate) : "") + "></div>";
                col += "<div data-fromTable='true' class='changeDiv dbl-area' data-orderId=" + orderId
                        + " data-parameterName='realDate' style='width: inherit;' data-isRight=" + rightChangeOrder
                        + ">";
                col += "<div style='font-size: 0.8em;'>" + (realDate != null ? df.format(realDate) : "") + "</div>";
                col += "<input type='text' class='date' value="
                        + (realDate != null ? fullDateFormatter.date(realDate) : "") + "></div></td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_CLIENT)) {
                col = "<td>";
                if (parentOrderId == null) {
                    col += "<div class='changeDiv dbl-area-auto' data-orderId=" + orderId
                            + " data-parameterName='clientFio' data-isRight=" + rightChangeOrder + ">";
                    col += "<div class='text'>" + clientFio + "</div>";
                    col += "<input type='text' value='" + clientFio + "'></div>";
                    if (branchRights.get("ORDER_SHOW_CLIENT_EMAIL") != null) {
                        col += "<div class='changeDiv dbl-area-auto' data-orderId=" + orderId
                                + " data-parameterName='clientEmail' data-isRight=" + rightChangeOrder + ">";
                        col += "<div class='text'>" + clientEmail + "</div>";
                        col += "<input type='text' value=" + clientEmail + "></div>";
                    }
                    if (branchRights.get("ORDER_SHOW_CLIENT_PHONE") != null) {
                        col += "<div class='changeDiv dbl-area-auto' data-orderId=" + orderId
                                + " data-parameterName='clientPhone' data-isRight=" + rightChangeOrder + ">";
                        col += "<div class='text'>" + clientPhone + "</div>";
                        col += "<input type='text' value=" + clientPhone + "></div>";
                    }
                    if (vr.showButtonsDivInTable(branchId, clientEmail, clientPhone)) {
                        col += "<div class='icon-contacts' style='width: 80px;'>";
                        if (vr.showSendEmailButtomInTable(branchId, clientEmail)
                                && webPrivs.isAllowed("/Notice/addEmailByClient", a)) {
                            col += "<a href='' class='mail orderEmailLink' ";
                            if (webPrivs.isAllowed("/Order/showClientEmailTitle", a)
                                    && branchRights.get("ORDER_SHOW_CLIENT_EMAIL_TITLE") != null) {
                                col += " data=" + clientEmail + " title=" + clientEmail + " ";
                            }
                            col += " onclick='createWindowEmailNotice('/Notice/addEmailByClient?orderId=" + orderId
                                    + "'); return false;' > </a>";
                        }
                        if (vr.showSendSmsButtomInTable(branchId, clientPhone)
                                && webPrivs.isAllowed("/Notice/addSmsByClient", a)) {
                            col += "<a href='' class='sms orderSmsLink' ";
                            if (webPrivs.isAllowed("/Order/showClientPhoneTitle", a)
                                    && branchRights.get("ORDER_SHOW_CLIENT_PHONE_TITLE") != null) {
                                col += " data=" + clientPhone + " title=" + clientPhone + " ";
                            }
                            col += " onclick='createFloatWindow('/Notice/addSmsByClient?orderId=" + orderId
                                    + "'); return false;' > </a>";
                        }
                    }
                    col += "<div class='clearfix'></div>";
                    if (!otherOrdersData.isEmpty()) {
                        col += "<div class='other-order'>";
                        col += "<a class='other-title' onclick='$(this).next().toggle()'> </a>";
                        col += "<ul style='display: none;' > ";
                        for (HashMap od : otherOrdersData) {
                            if (webPrivs.isAllowed("/Order/get", a)
                                    && br.get((Long) od.get("branchId")).get("GET_ORDER") != null) {
                                col += "<li><a href='#' class='orderShow' data-url='/Order/get?orderId="
                                        + od.get("orderId") + "&ajax=1' data-id=" + od.get("orderId")
                                        + " data-number=" + od.get("number") + " > #" + od.get("number")
                                        + "</a></li>";
                            }
                        }
                        col += "</ul>";
                    }
                } else {
                    col += "";
                }
                col += "</td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_PRICE)) {
                if (webPrivs.isAllowed("/Order/changeCost", a) && branchRights.get("ORDER_CHANGE_COST") != null) {
                    col = "<td id='updatableCostTd" + orderId
                            + "' class='updatableTd dbl-area' data-type='cost' data-orderId=" + orderId + ">"
                            + (cost != null ? cost : "") + "</td>";
                } else {
                    if (webPrivs.isAllowed("/Order/showCost", a) && branchRights.get("ORDER_SHOW_COST") != null) {
                        col = "<td><div class='dbl-area'>" + (cost != null ? cost : "") + "</div></td>";
                    }
                }
                orderData.add(col);
            }

            String userString = authUser.getSurname() + " " + authUser.getName();
            if (cr.get(Rights.TABLE_PREPAYMENT)) {
                col = "<td>";
                if (webPrivs.isAllowed("/Payment/search", a) && branchRights.get("PAYMENT_SEARCH") != null) {
                    col += "<div class='advance-payment modal-window'>";
                    col += "<form id='paymentObj' onsubmit='return false;' data-orderid=" + orderId
                            + " class='add-payment-form' action='" + SystemVariables.BASE_URL
                            + "/Payment/add?ajax=true' method='post' enctype='multipart/form-data'>";
                    col += "<div class='value'><span>" + paymentSum + "</span>";
                    col += "<div class='modal-content'><table><tr><td class='title'>?</td><td>"
                            + userString + "</td></tr>";
                    col += "<tr><td class='title'></td><td>" + (currentDate != null ? currentDate : "")
                            + "</td></tr>";
                    col += "<tr><td class='title'></td><td><input id='amount' name='amount' type='text' value='' autocomplete='off'></td></tr>";
                    col += "<tr><td class='title'>C?<br/></td><td><select id='paymentType' name='paymentType'>";
                    for (PaymentType pt : paymentTypeService.getActive()) {
                        col += "<option value=" + pt.getId() + ">" + pt.getName() + "</option>";
                    }
                    col += "</select></td></tr>";
                    col += "<tr><td colspan='2'><div class='uploadify-button' data-id=" + orderId
                            + " data-num='0' style='width: 50%;'> </div><input name='file' type='file' class='hidden ajaxUpload' id='fileInput"
                            + orderId + "' data-id=" + orderId + " data-num='0'></td></tr>";
                    col += "</table><br/><input type='hidden' name='orderId' value=" + orderId + " />";
                    col += "<input type='submit' class='modal-close' value=''></div></div></form></div>";
                }
                col += "</td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_AUTHOR_SALARY)) {
                if (webPrivs.isAllowed("/Order/changeAuthorSalary", a)
                        && branchRights.get("ORDER_CHANGE_AUTHOR_SALARY") != null) {
                    col = "<td class='author-salary dbl-area' data-orderId=" + orderId + ">";
                    col += "<div class='value-area "
                            + (commentToAuthorSalary != null && !commentToAuthorSalary.equals("") ? "warning" : "")
                            + "'>" + (authorSalary != null ? authorSalary : "") + "</div>";
                    col += "<div class='input-area' style='display: none;' >";
                    col += "<input class='author-salary-input' type='text' name='authorSalary' value="
                            + (authorSalary != null ? authorSalary : "") + ">";
                    col += "<textarea class='comment-salary-input' >"
                            + (commentToAuthorSalary != null ? commentToAuthorSalary : "")
                            + "</textarea></div></td>";
                } else {
                    col = "<td>" + (authorSalary != null ? authorSalary : "") + "</td>";
                }
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_STATUS)) {
                col = "<td class=" + ocm.getStatusClass(statusStr, cost, paymentSum)
                        + "><div class='dbl-area-select color' >";
                if (webPrivs.isAllowed("/Order/changeStatus", a)
                        && webPrivs.isAllowed("/Order/changeStatusFromTable", a)
                        && branchRights.get("ORDER_CHANGE_STATUS") != null
                        && branchRights.get("ORDER_CHANGE_STATUS_FROM_TABLE") != null) {
                    col += "<div class='status-in-table text order-status' id='statusDiv" + orderId + "' >"
                            + vr.getStatusName(orderStatus, existReject, cost, statusOfUser) + "</div>";
                    col += "<select id='statuSelect" + orderId + "' data-orderId=" + orderId
                            + " class='statusSelect' name='status'>";
                    for (OrderStatus os : availableStatusList) {
                        col += "<option value=" + os.toString() + " " + (os.equals(orderStatus) ? "selected" : "")
                                + " >" + os.getName() + "</option>";
                    }
                    col += "</select>";
                } else {
                    col += "<div class='text'>" + vr.getStatusName(orderStatus, existReject, cost, statusOfUser)
                            + "</div>";
                }
                col += "</div></td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_AUTHOR)) {
                col = "<td>";
                if (vr.allowShowAuthor()) {
                    col += vr.getAuthorParams(authorId, authorSurname, authorName, authorLogin, branchId, "<br/>");
                }
                col += "</td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_AUTHOR_MESSAGE)) {
                col = "<td>";
                if (!countNotReadyAuthorMessages.equals(BigInteger.valueOf(0L))) {
                    col += "<p class='circle'>" + countNotReadyAuthorMessages + "</p>";
                } else {
                    col += "(" + countAllAuthorMess + ")";
                }
                col += "<br/>";
                if (orderStatus != null && orderStatus.equals(OrderStatus.NEW)) {
                    for (HashMap sal : SalaryData) {
                        col += "<br/> " + sal.get("cost");
                    }
                }
                col += "</td>";
                orderData.add(col);
            }

            if (cr.get(Rights.TABLE_ADMIN_MESSAGE)) {
                col = "<td>";
                if (!countNotReadyAdminMess.equals(BigInteger.valueOf(0L))) {
                    col += "<p class='circle'>" + countNotReadyAdminMess + "</p>";
                } else {
                    col += "(" + countAllAdminMess + ")";
                }
                if (unloadedInShop != null && unloadedInShop) {
                    col += "<br/><span class='info check'></span>";
                }
                col += "</td>";
                orderData.add(col);
            }

            orderData.add("</tr>");

            result.add(orderData);
        }

        //log.warn("searchLogicTime:" + Long.valueOf(System.currentTimeMillis() - starttime));

        return result;
    }

    /*private List<List<String>> getOrderedAdminOrderListData(Set<Long> rightBranchIds, OrderStatus status, List<OrderStatus> commonAvailebleStatusList,
        OrderSearchData searchData, User authUser, Integer start, Integer numberOfRecords, List<OrderStatus> rightStatusList, Boolean overdue) {
        
    Long starttime = System.currentTimeMillis();
        
    User currentUser = authManager.getCurrentUser();
    String currentDate = getCurrentDateToString();
    OrderCssManager ocm = new OrderCssManager(currentUser);
    ViewResolver vr = new ViewResolver(currentUser, branchRightsHolder);
    HashMap<Long, HashMap<String, Boolean>> br = branchRightsHolder.getBranchRights();
    HashMap<Rights, Boolean> cr = new HashMap();
    for (Rights r : Rights.values()) {
        cr.put(r, UserRightsUtil.isRight(r));
    }
    List<Long> toWork = branchRightsHolder.getBranches(BranchRights.ORDER_NEW_TO_WORK);
    List<Long> toReject = branchRightsHolder.getBranches(BranchRights.ORDER_NEW_TO_REJECT);
    Authentication a = SecurityContextHolder.getContext().getAuthentication();
        
    SimpleDateFormat df = new SimpleDateFormat("dd/MM");
    DateFormatter fullDateFormatter = new DateFormatter();
        
    //LinkedHashMap<Long, HashMap> rawRes = new LinkedHashMap();
    List<List<String>> result = new ArrayList();
        
    List<Object[]> preRes = orderDao.getOrderedOrdersAndCountsForAdminBySql(rightBranchIds, status,
            searchData, authUser.getUserId(), start, numberOfRecords, rightStatusList, overdue);
        
    Set<Long> orderIds = new HashSet();
    for (Object[] rawOrder : preRes) {
        Long orderId = getLong(rawOrder[0]);
        orderIds.add(orderId);
    }
        
    HashMap<Long, List<HashMap>> otherOrders = new HashMap();
    HashMap<Long, List<HashMap>> orderDirections = new HashMap();
    HashMap<Long, List<HashMap>> orderSalaries = new HashMap();
        
    //log.warn("searchLogicTime1:" + Long.valueOf(System.currentTimeMillis() - starttime));
        
    List<Object[]> otherOrdersRawRes = orderDao.getTestOtherOrdersForAdminBySql(orderIds);
    //log.warn("searchLogicTime2:" + Long.valueOf(System.currentTimeMillis() - starttime));
    for (Object[] rawOtherOrder : otherOrdersRawRes) {
        Long orderId = getLong(rawOtherOrder[0]);
        
        List<HashMap> otherOrdersList = otherOrders.get(orderId);
        if (otherOrdersList == null) {
            otherOrdersList = new ArrayList();
        }
        if (otherOrdersList.size() < 5) {
            HashMap<String, Object> otherOrderData = new HashMap();
        
            Long otherOrderId = getLong(rawOtherOrder[1]);
            Long otherOrderBranchId = getLong(rawOtherOrder[2]);
            String otherOrderOldId = (String) rawOtherOrder[3];
            String otherOrderNumber = otherOrderOldId;
            if (otherOrderOldId == null || otherOrderOldId.equals("")) {
                otherOrderNumber = otherOrderId.toString();
            }
        
            otherOrderData.put("orderId", otherOrderId);
            otherOrderData.put("branchId", otherOrderBranchId);
            otherOrderData.put("number", otherOrderNumber);
            otherOrdersList.add(otherOrderData);
            otherOrders.put(orderId, otherOrdersList);
        }
    }
        
    List<Object[]> orderDirectionRawRes = orderDao.getTestDirectionsForAdminBySql(orderIds);
    for (Object[] rawDirectionData : orderDirectionRawRes) {
        Long orderId = getLong(rawDirectionData[0]);
        
        List<HashMap> directionsList = orderDirections.get(orderId);
        if (directionsList == null) {
            directionsList = new ArrayList();
        }
        HashMap<String, Object> directionData = new HashMap();
        
        Long directionId = getLong(rawDirectionData[1]);
        String directionName = (String) rawDirectionData[2];
        
        directionData.put("directionId", directionId);
        directionData.put("directionName", directionName);
        directionsList.add(directionData);
        orderDirections.put(orderId, directionsList);
    }
        
    List<Object[]> authorSalariesRawRes = orderDao.getTestSalariesForAdminBySql(orderIds);
    for (Object[] rawSalaryData : authorSalariesRawRes) {
        Long orderId = getLong(rawSalaryData[0]);
        
        List<HashMap> salaryList = orderSalaries.get(orderId);
        if (salaryList == null) {
            salaryList = new ArrayList();
        }
        HashMap<String, Object> salaryData = new HashMap();
        
        Double authorSalaryCost = (Double) rawSalaryData[1];
        Long authorSalaryId = getLong(rawSalaryData[2]);
        
        salaryData.put("salaryId", authorSalaryId);
        salaryData.put("cost", authorSalaryCost);
        salaryList.add(salaryData);
        orderSalaries.put(orderId, salaryList);
    }
    for (Object[] rawOrder : preRes) {
        List<String> orderData = new ArrayList();
        Long orderId = getLong(rawOrder[0]);
        
        Date deadlineDate = (Date) rawOrder[1];
        Date realDate = (Date) rawOrder[2];
        String clientFio = (String) rawOrder[3];
        String clientPhone = (String) rawOrder[4];
        String clientEmail = (String) rawOrder[5];
        String city = (String) rawOrder[6];
        Double cost = (Double) rawOrder[7];
        Double authorSalary = (Double) rawOrder[8];
        Boolean firstFlag = (Boolean) rawOrder[9];
        Boolean secondFlag = (Boolean) rawOrder[10];
        String statusStr = (String) rawOrder[11];
        OrderStatus orderStatus = OrderStatus.valueOf(statusStr);
        Long branchId = getLong(rawOrder[12]);
        Long orderTypeId = getLong(rawOrder[13]);
        Long authorId = getLong(rawOrder[14]);
        String comment = (String) rawOrder[15];
        String authorComment = (String) rawOrder[16];
        Date readyDate = (Date) rawOrder[17];
        String commentToAuthorSalary = (String) rawOrder[18];
        Boolean unloadedInShop = (Boolean) rawOrder[19];
        Long parentOrderId = getLong(rawOrder[20]);
        Boolean selected = (Boolean) rawOrder[21];
        Boolean childSelected = (Boolean) rawOrder[22];
        Boolean statusOfUser = (Boolean) rawOrder[23];
        
        String oldId = (String) rawOrder[24];
        String number = oldId;
        if (oldId == null || oldId.equals("")) {
            number = orderId.toString();
        }
        
        String subject = (String) rawOrder[25];
        Date orderDate = (Date) rawOrder[26];
        String branchName = (String) rawOrder[27];
        String abbrevation = (String) rawOrder[28];
        String orderTypeName = (String) rawOrder[29];
        String authorLogin = (String) rawOrder[30];
        String authorName = (String) rawOrder[31];
        String authorSurname = (String) rawOrder[32];
        
        Boolean existReject = false;
        
        BigInteger bi = (BigInteger) rawOrder[33];
        Integer countMess = (bi != null ? bi.intValue() : null);
        
        Double paymentSum = (Double) rawOrder[34];
        paymentSum = (paymentSum != null ? paymentSum : 0D);
        
        BigInteger countAllAuthorMess = (BigInteger) rawOrder[35];
        BigInteger countAllAdminMess = (BigInteger) rawOrder[36];
        BigInteger countNotReadyAdminMess = (BigInteger) rawOrder[37];
        BigInteger countAllDelegateMess = (BigInteger) rawOrder[38];
        BigInteger countNotReadyDelegateMess = (BigInteger) rawOrder[39];
        
        BigInteger countNotReadyAuthorMessages = new BigInteger("0");
        if (countMess != null) {
            countNotReadyAuthorMessages = bi;
        }
        if (countNotReadyDelegateMess != null) {
            countNotReadyAuthorMessages = countNotReadyAuthorMessages.add(countNotReadyDelegateMess);
        }
        
        List<OrderStatus> availableStatusList = new ArrayList(commonAvailebleStatusList);
        if (statusStr.equals(OrderStatus.NEW.name())) {
            if (!toWork.contains(branchId)) {
                availableStatusList.remove(OrderStatus.WORKING);
            }
            if (!toReject.contains(branchId)) {
                availableStatusList.remove(OrderStatus.REJECTION);
            }
        }
        
        List<HashMap> otherOrdersData = otherOrders.get(orderId);
        List<HashMap> directionsData = orderDirections.get(orderId);
        List<HashMap> SalaryData = orderSalaries.get(orderId);
        if (otherOrdersData == null) {
            otherOrdersData = new ArrayList();
        }
        if (directionsData == null) {
            directionsData = new ArrayList();
        }
        if (SalaryData == null) {
            SalaryData = new ArrayList();
        }
        
        HashMap<String, Boolean> branchRights = br.get(branchId);
        boolean rightChangeOrder = false;
        if ((childSelected == null || !childSelected) && branchRights.get("CHANGE_ORDER") && webPrivs.isAllowed("/Order/change", a)) {
            rightChangeOrder = true;
        }
        
        String rowClass = ocm.getRowClass(selected, authorId, cost, statusOfUser, orderStatus, SalaryData, null);
        
        orderData.add("<tr class=" + rowClass + ">");
        String col = "";
        if (cr.get(Rights.TABLE_FLAGS)) {
            col = "<td><a class='info red " + (firstFlag != null && firstFlag ? "active" : "") + "' data-orderId=" + orderId + " onclick='return changeFirstFlag(this);'></a>";
            col += "<br/>";
            col += "<a class='info blue " + (secondFlag != null && secondFlag ? "active" : "") + "' data-orderId=" + orderId + " onclick='return changeSecondFlag(this);'></a></td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_NUMBER)) {
            if (branchRights.get("GET_ORDER") && webPrivs.isAllowed("/Order/get", a)) {
                col = "<td><a href='#' class='orderShow flat' data-id=" + orderId + " data-number=" + number + ">";
                col += "<p class='order-num'><span class='orderCount'>" + abbrevation + "</span>" + number + "</p></a></td>";
            } else {
                col = "<td>" + StringAdapter.getString(number) + "</td>";
            }
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_DIRECTIONS)) {
            col = "<td class='directionsTd' data-orderId=" + orderId + ">";
            if (branchRights.get("ORDER_CHANGE_DIRECTIONS") && (childSelected == null || !childSelected)) {
                col += "<div class='directionDiv add-order-select' data-orderId=" + orderId + ">";
                for (HashMap dir : directionsData) {
                    col += "<select class='directionSelect' data-orderId=" + orderId + " data-value=" + dir.get("directionId") + ">";
                    col += "<option value=''></option>";
                    for (Direction d : directionService.getAll()) {
                        col += "<option value=" + d.getDirectionId() + " " + (d.getDirectionId().equals(dir.get("directionId")) ? "selected" : "") + ">" + d.getName() + "</option>";
                    }
                    col += "</select></br>";
                }
                col += "</div>";
                col += "<a class='add-direction addDirectionSubmit info add active' data-orderId=" + orderId + ">+</a>";
            } else {
                for (HashMap d : directionsData) {
                    col += d.get("directionName");
                }
            }
            col += "</td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_TYPE)) {
            col = "<td><div class='changeDiv dbl-area-select' data-orderId=" + orderId + " data-parameterName='orderType' data-isRight=" + rightChangeOrder + ">";
            col += "<div class='text'>" + orderTypeName + "</div>";
            col += "<select>";
            for (OrderType ot : orderTypeService.getAll()) {
                col += "<option value=" + ot.getOrderTypeId() + " " + (ot.getOrderTypeId().equals(orderTypeId) ? "selected" : "") + ">" + ot.getName() + "</option>";
            }
            col += "</select></div></td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_SUBJECT)) {
            col = "<td><div class='changeDiv dbl-area-auto' data-orderId=" + orderId + " data-parameterName='subject' data-isRight=" + rightChangeOrder + ">";
            col += "<div class='text'>" + subject + "</div>";
            col += "<textarea>" + subject + "</textarea></div></td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_DATE)) {
            col = "<td><div data-fromTable='true' class='changeDiv dbl-area' data-orderId=" + orderId + " data-parameterName='deadlineDate' style='width: inherit;' data-isRight=" + rightChangeOrder + ">";
            col += "<div style='font-size: 0.8em;'>" + (deadlineDate != null ? df.format(deadlineDate) : "") + "</div>";
            col += "<input type='text' class='date' value=" + (deadlineDate != null ? fullDateFormatter.date(deadlineDate) : "") + "></div>";
            col += "<div data-fromTable='true' class='changeDiv dbl-area' data-orderId=" + orderId + " data-parameterName='realDate' style='width: inherit;' data-isRight=" + rightChangeOrder + ">";
            col += "<div style='font-size: 0.8em;'>" + (realDate != null ? df.format(realDate) : "") + "</div>";
            col += "<input type='text' class='date' value=" + (realDate != null ? fullDateFormatter.date(realDate) : "") + "></div></td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_CLIENT)) {
            col = "<td>";
            if (parentOrderId == null) {
                col += "<div class='changeDiv dbl-area-auto' data-orderId=" + orderId + " data-parameterName='clientFio' data-isRight=" + rightChangeOrder + ">";
                col += "<div class='text'>" + clientFio + "</div>";
                col += "<input type='text' value='" + clientFio + "'></div>";
                if (branchRights.get("ORDER_SHOW_CLIENT_EMAIL") != null) {
                    col += "<div class='changeDiv dbl-area-auto' data-orderId=" + orderId + " data-parameterName='clientEmail' data-isRight=" + rightChangeOrder + ">";
                    col += "<div class='text'>" + clientEmail + "</div>";
                    col += "<input type='text' value=" + clientEmail + "></div>";
                }
                if (branchRights.get("ORDER_SHOW_CLIENT_PHONE") != null) {
                    col += "<div class='changeDiv dbl-area-auto' data-orderId=" + orderId + " data-parameterName='clientPhone' data-isRight=" + rightChangeOrder + ">";
                    col += "<div class='text'>" + clientPhone + "</div>";
                    col += "<input type='text' value=" + clientPhone + "></div>";
                }
                if (vr.showButtonsDivInTable(branchId, clientEmail, clientPhone)) {
                    col += "<div class='icon-contacts' style='width: 80px;'>";
                    if (vr.showSendEmailButtomInTable(branchId, clientEmail) && webPrivs.isAllowed("/Notice/addEmailByClient", a)) {
                        col += "<a href='' class='mail orderEmailLink' ";
                        if (webPrivs.isAllowed("/Order/showClientEmailTitle", a) && branchRights.get("ORDER_SHOW_CLIENT_EMAIL_TITLE") != null) {
                            col += " data=" + clientEmail + " title=" + clientEmail + " ";
                        }
                        col += " onclick='createWindowEmailNotice('/Notice/addEmailByClient?orderId=" + orderId + "'); return false;' > </a>";
                    }
                    if (vr.showSendSmsButtomInTable(branchId, clientPhone) && webPrivs.isAllowed("/Notice/addSmsByClient", a)) {
                        col += "<a href='' class='sms orderSmsLink' ";
                        if (webPrivs.isAllowed("/Order/showClientPhoneTitle", a) && branchRights.get("ORDER_SHOW_CLIENT_PHONE_TITLE") != null) {
                            col += " data=" + clientPhone + " title=" + clientPhone + " ";
                        }
                        col += " onclick='createFloatWindow('/Notice/addSmsByClient?orderId=" + orderId + "'); return false;' > </a>";
                    }
                }
                col += "<div class='clearfix'></div>";
                if (!otherOrdersData.isEmpty()) {
                    col += "<div class='other-order'>";
                    col += "<a class='other-title' onclick='$(this).next().toggle()'> </a>";
                    col += "<ul style='display: none;' > ";
                    for (HashMap od : otherOrdersData) {
                        if (webPrivs.isAllowed("/Order/get", a) && br.get((Long) od.get("branchId")).get("GET_ORDER") != null) {
                            col += "<li><a href='#' class='orderShow' data-url='/Order/get?orderId=" + od.get("orderId") + "&ajax=1' data-id=" + od.get("orderId") + " data-number=" + od.get("number") + " > #" + od.get("number") + "</a></li>";
                        }
                    }
                    col += "</ul>";
                }
            } else {
                col += "";
            }
            col += "</td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_PRICE)) {
            if (webPrivs.isAllowed("/Order/changeCost", a) && branchRights.get("ORDER_CHANGE_COST") != null) {
                col = "<td id='updatableCostTd" + orderId + "' class='updatableTd dbl-area' data-type='cost' data-orderId=" + orderId + ">" + (cost != null ? cost : "") + "</td>";
            } else {
                if (webPrivs.isAllowed("/Order/showCost", a) && branchRights.get("ORDER_SHOW_COST") != null) {
                    col = "<td><div class='dbl-area'>" + (cost != null ? cost : "") + "</div></td>";
                }
            }
            orderData.add(col);
        }
        
        String userString = authUser.getSurname() + " " + authUser.getName();
        if (cr.get(Rights.TABLE_PREPAYMENT)) {
            col = "<td>";
            if (webPrivs.isAllowed("/Payment/search", a) && branchRights.get("PAYMENT_SEARCH") != null) {
                col += "<div class='advance-payment modal-window'>";
                col += "<form id='paymentObj' onsubmit='return false;' data-orderid=" + orderId + " class='add-payment-form' action='" + SystemVariables.BASE_URL + "/Payment/add?ajax=true' method='post' enctype='multipart/form-data'>";
                col += "<div class='value'><span>" + paymentSum + "</span>";
                col += "<div class='modal-content'><table><tr><td class='title'>?</td><td>" + userString + "</td></tr>";
                col += "<tr><td class='title'></td><td>" + (currentDate != null ? currentDate : "") + "</td></tr>";
                col += "<tr><td class='title'></td><td><input id='amount' name='amount' type='text' value='' autocomplete='off'></td></tr>";
                col += "<tr><td class='title'>C?<br/></td><td><select id='paymentType' name='paymentType'>";
                for (PaymentType pt : paymentTypeService.getActive()) {
                    col += "<option value=" + pt.getId() + ">" + pt.getName() + "</option>";
                }
                col += "</select></td></tr>";
                col += "<tr><td colspan='2'><div class='uploadify-button' data-id="+orderId+" data-num='0' style='width: 50%;'> </div><input name='file' type='file' class='hidden ajaxUpload' id='fileInput"+orderId+"' data-id="+orderId+" data-num='0'></td></tr>";
                col += "</table><br/><input type='hidden' name='orderId' value=" + orderId + " />";
                col += "<input type='submit' class='modal-close' value=''></div></div></form></div>";
            }
            col += "</td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_AUTHOR_SALARY)) {
            if (webPrivs.isAllowed("/Order/changeAuthorSalary", a) && branchRights.get("ORDER_CHANGE_AUTHOR_SALARY") != null) {
                col = "<td class='author-salary dbl-area' data-orderId=" + orderId + ">";
                col += "<div class='value-area " + (commentToAuthorSalary != null && !commentToAuthorSalary.equals("") ? "warning" : "") + "'>" + (authorSalary != null ? authorSalary : "") + "</div>";
                col += "<div class='input-area' style='display: none;' >";
                col += "<input class='author-salary-input' type='text' name='authorSalary' value=" + (authorSalary != null ? authorSalary : "") + ">";
                col += "<textarea class='comment-salary-input' >" + (commentToAuthorSalary != null ? commentToAuthorSalary : "") + "</textarea></div></td>";
            } else {
                col = "<td>" + (authorSalary != null ? authorSalary : "") + "</td>";
            }
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_STATUS)) {
            col = "<td class=" + ocm.getStatusClass(statusStr, cost, paymentSum) + "><div class='dbl-area-select color' >";
            if (webPrivs.isAllowed("/Order/changeStatus", a) && webPrivs.isAllowed("/Order/changeStatusFromTable", a)
                    && branchRights.get("ORDER_CHANGE_STATUS") != null && branchRights.get("ORDER_CHANGE_STATUS_FROM_TABLE") != null) {
                col += "<div class='status-in-table text order-status' id='statusDiv" + orderId + "' >" + vr.getStatusName(orderStatus, existReject, cost, statusOfUser) + "</div>";
                col += "<select id='statuSelect" + orderId + "' data-orderId=" + orderId + " class='statusSelect' name='status'>";
                for (OrderStatus os : availableStatusList) {
                    col += "<option value=" + os.toString() + " " + (os.equals(orderStatus) ? "selected" : "") + " >" + os.getName() + "</option>";
                }
                col += "</select>";
            } else {
                col += "<div class='text'>" + vr.getStatusName(orderStatus, existReject, cost, statusOfUser) + "</div>";
            }
            col += "</div></td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_AUTHOR)) {
            col = "<td>";
            if (vr.allowShowAuthor()) {
                col += vr.getAuthorParams(authorId, authorSurname, authorName, authorLogin, branchId, "<br/>");
            }
            col += "</td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_AUTHOR_MESSAGE)) {
            col = "<td>";
            if (!countNotReadyAuthorMessages.equals(BigInteger.valueOf(0L))) {
                col += "<p class='circle'>" + countNotReadyAuthorMessages + "</p>";
            } else {
                col += "(" + countAllAuthorMess + ")";
            }
            col += "<br/>";
            if (orderStatus != null && orderStatus.equals(OrderStatus.NEW)) {
                for (HashMap sal : SalaryData) {
                    col += "<br/> " + sal.get("cost");
                }
            }
            col += "</td>";
            orderData.add(col);
        }
        
        if (cr.get(Rights.TABLE_ADMIN_MESSAGE)) {
            col = "<td>";
            if (!countNotReadyAdminMess.equals(BigInteger.valueOf(0L))) {
                col += "<p class='circle'>" + countNotReadyAdminMess + "</p>";
            } else {
                col += "(" + countAllAdminMess + ")";
            }
            if (unloadedInShop != null && unloadedInShop) {
                col += "<br/><span class='info check'></span>";
            }
            col += "</td>";
            orderData.add(col);
        }
        
        orderData.add("</tr>");
        
        result.add(orderData);
    }
        
    //log.warn("searchLogicTime:" + Long.valueOf(System.currentTimeMillis() - starttime));
        
    return result;
    }*/

    /*private List<HashMap> getTestOrderListData(Set<Long> rightBranchIds, OrderStatus status, List<OrderStatus> commonAvailebleStatusList,
     OrderSearchData searchData, User authUser, Integer start, Integer numberOfRecords, List<OrderStatus> rightStatusList, Boolean overdue) {
        
     LinkedHashMap<Long, HashMap> rawRes = new LinkedHashMap();
     List<HashMap> result = new ArrayList();
        
     List<Long> toWork = branchRightsHolder.getBranches(BranchRights.ORDER_NEW_TO_WORK);
     List<Long> toReject = branchRightsHolder.getBranches(BranchRights.ORDER_NEW_TO_REJECT);
        
     List<Object[]> preRes = orderDao.getTestOrdersAndCountsForAdminBySql(rightBranchIds, status, 
     searchData, authUser.getUserId(), start, numberOfRecords, rightStatusList, overdue);
        
     log.warn("preRes= "+preRes.size());
     String testRes="";
     int i=1;
        
     for (Object[] rawOrder : preRes) {
     HashMap<String, Object> orderData = new HashMap();
     Long orderId = getLong(rawOrder[0]);
            
     testRes+=(i++)+" - "+orderId+"; ";
        
     Date deadlineDate = (Date) rawOrder[1];
     Date realDate = (Date) rawOrder[2];
     String clientFio = (String) rawOrder[3];
     String clientPhone = (String) rawOrder[4];
     String clientEmail = (String) rawOrder[5];
     String city = (String) rawOrder[6];
     Double cost = (Double) rawOrder[7];
     Double authorSalary = (Double) rawOrder[8];
     Boolean firstFlag = (Boolean) rawOrder[9];
     Boolean secondFlag = (Boolean) rawOrder[10];
     String statusStr = (String) rawOrder[11];
     Long branchId = getLong(rawOrder[12]);
     Long orderTypeId = getLong(rawOrder[13]);
     Long authorId = getLong(rawOrder[14]);
     String comment = (String) rawOrder[15];
     String authorComment = (String) rawOrder[16];
     Date readyDate = (Date) rawOrder[17];
     String commentToAuthorSalary = (String) rawOrder[18];
     Boolean unloadedInShop = (Boolean) rawOrder[19];
     Long parentOrderId = getLong(rawOrder[20]);
     Boolean selected = (Boolean) rawOrder[21];
     Boolean childSelected = (Boolean) rawOrder[22];
     Boolean statusOfUser = (Boolean) rawOrder[23];
        
     String oldId = (String) rawOrder[24];
     String number = oldId;
     if (oldId == null || oldId.equals("")) {
     number = orderId.toString();
     }
        
     String subject = (String) rawOrder[25];
     Date orderDate = (Date) rawOrder[26];
     String branchName = (String) rawOrder[27];
     String abbrevation = (String) rawOrder[28];
     String orderTypeName = (String) rawOrder[29];
     String authorLogin = (String) rawOrder[30];
     String authorName = (String) rawOrder[31];
     String authorSurname = (String) rawOrder[32];
        
     BigInteger bi = (BigInteger) rawOrder[33];
     Integer countMess = (bi != null ? bi.intValue() : null);
        
     Double paymentSum = (Double) rawOrder[34];
     paymentSum=(paymentSum!=null?paymentSum:0D);
            
     BigInteger countAllAuthorMess = (BigInteger) rawOrder[35];
     BigInteger countAllAdminMess = (BigInteger) rawOrder[36];
     BigInteger countNotReadyAdminMess = (BigInteger) rawOrder[37];
     BigInteger countAllDelegateMess = (BigInteger) rawOrder[38];
     BigInteger countNotReadyDelegateMess = (BigInteger) rawOrder[39];
     //Boolean watched = ((Number)rawOrder[40]).longValue()==1L;
            
     BigInteger countNotReadyAuthorMessages=new BigInteger("0");
     if(countMess!=null){
     countNotReadyAuthorMessages=bi;
     }
     if(countNotReadyDelegateMess!=null){
     countNotReadyAuthorMessages=countNotReadyAuthorMessages.add(countNotReadyDelegateMess);
     }
            
     List<OrderStatus> availableStatusList = new ArrayList(commonAvailebleStatusList);
     if (statusStr.equals(OrderStatus.NEW.name())) {
     if (!toWork.contains(branchId)) {
     availableStatusList.remove(OrderStatus.WORKING);
     }
     if (!toReject.contains(branchId)) {
     availableStatusList.remove(OrderStatus.REJECTION);
     }
     }
        
     orderData.put("orderId", orderId);
     orderData.put("deadLineDate", deadlineDate);
     orderData.put("realDate", realDate);
     orderData.put("clientFio", clientFio);
     orderData.put("clientPhone", clientPhone);
     orderData.put("clientEmail", clientEmail);
     orderData.put("city", city);
     orderData.put("cost", cost);
     orderData.put("authorSalary", authorSalary);
     orderData.put("firstFlag", firstFlag);
     orderData.put("secondFlag", secondFlag);
     orderData.put("status", statusStr);
     orderData.put("branchId", branchId);
     orderData.put("orderTypeId", orderTypeId);
     orderData.put("authorId", authorId);
     orderData.put("comment", comment);
     orderData.put("authorComment", authorComment);
     orderData.put("readyDate", readyDate);
     orderData.put("commentToAuthorSalary", commentToAuthorSalary);
     orderData.put("unloadedInShop", unloadedInShop);
     orderData.put("parentOrderId", parentOrderId);
     orderData.put("selected", selected);
     orderData.put("childSelected", childSelected);
     orderData.put("statusOfUser", statusOfUser);
     orderData.put("number", number);
     orderData.put("subject", subject);
     orderData.put("orderDate", orderDate);
     orderData.put("branchName", branchName);
     orderData.put("abbrevation", abbrevation);
     orderData.put("orderTypeName", orderTypeName);
     orderData.put("authorLogin", authorLogin);
     orderData.put("authorName", authorName);
     orderData.put("authorSurname", authorSurname);
     orderData.put("countMess", countMess);
     orderData.put("paymentSum", paymentSum);
     orderData.put("countAllAuthorMesages", countAllAuthorMess.intValue());
     orderData.put("countAllAdminMessages", countAllAdminMess.intValue());
     orderData.put("countNotReadyAdminMessages", countNotReadyAdminMess.intValue());
     orderData.put("countAllDelegateMess", countAllDelegateMess.intValue());
     orderData.put("countNotReadyDelegateMess", countNotReadyDelegateMess.intValue());
     orderData.put("countNotReadyAuthorMessages", countNotReadyAuthorMessages);
     orderData.put("availableStatusList", availableStatusList);
     //orderData.put("watched", watched);
     rawRes.put(orderId, orderData);
     }
        
     log.warn("testRes="+testRes);
     log.warn("");
     log.warn("semiRawRes="+rawRes.size());
        
     HashMap<Long, List<HashMap>> otherOrders = new HashMap();
     HashMap<Long, List<HashMap>> orderDirections = new HashMap();
     HashMap<Long, List<HashMap>> orderSalaries = new HashMap();
        
     List<Object[]> otherOrdersRawRes = orderDao.getTestOtherOrdersForAdminBySql(rawRes.keySet());
     for (Object[] rawOtherOrder : otherOrdersRawRes) {
     Long orderId = getLong(rawOtherOrder[0]);
        
     List<HashMap> otherOrdersList = otherOrders.get(orderId);
     if (otherOrdersList == null) {
     otherOrdersList = new ArrayList();
     }
     if(otherOrdersList.size()<5){
     HashMap<String, Object> otherOrderData = new HashMap();
        
     Long otherOrderId = getLong(rawOtherOrder[1]);
     Long otherOrderBranchId = getLong(rawOtherOrder[2]);
     String otherOrderOldId = (String) rawOtherOrder[3];
     String otherOrderNumber = otherOrderOldId;
     if (otherOrderOldId == null || otherOrderOldId.equals("")) {
     otherOrderNumber = otherOrderId.toString();
     }
        
     otherOrderData.put("orderId", otherOrderId);
     otherOrderData.put("branchId", otherOrderBranchId);
     otherOrderData.put("number", otherOrderNumber);
     otherOrdersList.add(otherOrderData);
     otherOrders.put(orderId, otherOrdersList);
     }
     }*/
    private List<OrderListData> getDataListBySqlMap(Set<Long> rightBranchIds, OrderStatus status,
            datastructure.OrderSearchData searchData, Integer start, Integer numberOfRecords,
            List<OrderStatus> rightStatusList, Boolean overdue) {
        User authUser = authManager.getCurrentUser();
        List<Map> mapList;
        if (authUser instanceof Admin) {
            List<OrderStatus> statusList = new ArrayList();
            mapList = orderDao.getForAdminBySql(rightBranchIds, status, statusList, searchData,
                    authUser.getUserId(), start, numberOfRecords, rightStatusList, overdue);
        } else {
            Author author = (Author) authUser;
            if (author.getActive()) {
                Set<Long> authorDirectionIds = getAuthorDirectionIds(author);
                mapList = orderDao.getForAuthorBySql(author, status, authorDirectionIds, rightBranchIds, searchData,
                        start, numberOfRecords, null, rightStatusList, overdue);
            } else {
                mapList = new ArrayList();
            }
        }

        List<OrderListData> list = transformBySqlMap(mapList);

        return list;
    }

    private List<OrderListData> transformBySqlMap(List<Map> mapList) {
        Map<Long, OrderListData> dataMap = new LinkedHashMap();
        int n = 1;
        for (Map map : mapList) {
            Long orderId = getLong(map.get("order_id"));
            String subject = (String) map.get("subject");
            Date orderDate = (Date) map.get("order_date");
            Date deadlineDate = (Date) map.get("deadline_date");
            Date realDate = (Date) map.get("real_date");
            String clientFio = (String) map.get("client_fio");
            String clientPhone = (String) map.get("client_phone");
            String clientEmail = (String) map.get("client_email");
            String city = (String) map.get("city");
            Double cost = (Double) map.get("cost");
            Double authorSalary = (Double) map.get("author_salary");
            Boolean firstFlag = (Boolean) map.get("first_flag");
            Boolean secondFlag = (Boolean) map.get("second_flag");
            Boolean statusOfUser = (Boolean) map.get("status_of_user");
            String statusStr = (String) map.get("status");
            Long otherOrderId = getLong(map.get("other_order_id"));
            Long branchId = getLong(map.get("branch_id"));
            String branchName = (String) map.get("branch_name");
            Long directionId = getLong(map.get("direction_id"));
            String directionName = (String) map.get("direction_name");
            Long orderTypeId = getLong(map.get("order_type_id"));
            String orderTypeName = (String) map.get("order_type_name");
            Long authorId = getLong(map.get("author_id"));
            String authorLogin = (String) map.get("author_login");
            BigInteger bi = (BigInteger) map.get("count_mess");
            Integer countMess = (bi != null ? bi.intValue() : null);
            String abbrevation = (String) map.get("abbrevation");
            String comment = (String) map.get("comment");
            String oldId = (String) map.get("old_id");
            String authorComment = (String) map.get("author_comment");
            Date readyDate = (Date) map.get("ready_date");
            Long otherOrderBranchId = getLong(map.get("other_order_branch_id"));
            String otherOrderOldId = (String) map.get("other_order_old_id");
            String authorName = (String) map.get("author_name");
            String authorSurname = (String) map.get("author_surname");
            Long authorSalaryId = getLong(map.get("author_salary_id"));
            Double authorSalaryCost = (Double) map.get("author_salary_cost");
            Double paymentSum = (Double) map.get("payment_sum");
            String commentToAuthorSalary = (String) map.get("comment_to_author_salary");
            BigInteger countAllAuthorMess = (BigInteger) map.get("count_author_mess_all");
            BigInteger countAllAdminMess = (BigInteger) map.get("count_admin_mess_all");
            BigInteger countNotReadyAdminMess = (BigInteger) map.get("count_admin_mess_not_ready");
            Boolean unloadedInShop = (Boolean) map.get("unloaded_in_shop");
            Long parentOrderId = getLong(map.get("parent_order_id"));
            Boolean selected = (Boolean) map.get("selected");
            Boolean childSelected = (Boolean) map.get("child_selected");
            BigInteger countAllDelegateMess = (BigInteger) map.get("delegate_mess_all");
            BigInteger countNotReadyDelegateMess = (BigInteger) map.get("delegate_mess_not_ready");

            if (!dataMap.containsKey(orderId)) {

                Order order = new Order();
                order.setOrderId(orderId);
                order.setCity(city);
                order.setSubject(subject);
                order.setOrderDate(orderDate);
                order.setDeadlineDate(deadlineDate);
                order.setRealDate(realDate);
                order.setClientFio(clientFio);
                order.setClientPhone(clientPhone);
                order.setClientEmail(clientEmail);
                order.setCost(cost);
                order.setAuthor_salary(authorSalary);
                order.setFirstFlag(firstFlag);
                order.setSecondFlag(secondFlag);
                order.setComment(comment);
                order.setAuthorComment(authorComment);
                order.setReadyDate(readyDate);
                order.setCommentToAuthorSalary(commentToAuthorSalary);
                order.setUnloadedInShop(unloadedInShop);
                order.setSelected(selected);
                order.setChildSelected(childSelected);
                order.setStatusOfUser(statusOfUser);
                order.setOldId(oldId);
                if (parentOrderId != null) {
                    Order parentOrder = new Order();
                    parentOrder.setOrderId(parentOrderId);
                    order.setParentOrder(parentOrder);
                }

                OrderStatus orderStatus = null;
                try {
                    orderStatus = OrderStatus.valueOf(statusStr);
                } catch (Exception e) {
                    log.warn(StringAdapter.getStackExeption(e));
                }
                order.setStatus(orderStatus);

                entity.Branch branch = new entity.Branch();
                branch.setBranchId(branchId);
                branch.setName(branchName);
                branch.setAbbrevation(abbrevation);
                order.setBranch(branch);

                entity.OrderType orderType = new entity.OrderType();
                orderType.setOrderTypeId(orderTypeId);
                orderType.setName(orderTypeName);
                order.setOrderType(orderType);

                Author author = null;
                if (authorId != null) {
                    author = new Author();
                    author.setUserId(authorId);
                    author.setLogin(authorLogin);
                    author.setName(authorName);
                    author.setSurname(authorSurname);
                    order.setAuthor(author);
                }

                OrderListData data = new OrderListData();
                data.order = order;

                data.countNotReadyAuthorMessages = 0;
                if (countMess != null) {
                    data.countNotReadyAuthorMessages += countMess;
                }
                if (countNotReadyDelegateMess != null) {
                    data.countNotReadyAuthorMessages += countNotReadyDelegateMess.intValue();
                }

                if (paymentSum != null) {
                    data.paymentSum = paymentSum;
                }
                data.countAllAuthorMesages = 0;
                if (countAllAuthorMess != null) {
                    data.countAllAuthorMesages += countAllAuthorMess.intValue();
                }
                if (countAllDelegateMess != null) {
                    data.countAllAuthorMesages += countAllDelegateMess.intValue();
                }
                if (countAllAdminMess != null) {
                    data.countAllAdminMessages = countAllAdminMess.intValue();
                }
                if (countNotReadyAdminMess != null) {
                    data.countNotReadyAdminMessages = countNotReadyAdminMess.intValue();
                }

                dataMap.put(orderId, data);
            }

            OrderListData data = dataMap.get(orderId);

            if (authorSalaryId != null) {
                AuthorSalary authorSalaryObj = new AuthorSalary();
                authorSalaryObj.setAuthorSalaryId(authorSalaryId);
                authorSalaryObj.setCost(authorSalaryCost);
                if (!containsAuthorSalary(data.order, authorSalaryObj)) {
                    data.order.addAuthorSalary(authorSalaryObj);
                }
            }

            if (otherOrderId != null) {
                Order otherOrder = new Order();
                otherOrder.setOrderId(otherOrderId);
                Branch otherOrderBranch = new Branch();
                otherOrderBranch.setBranchId(otherOrderBranchId);
                otherOrder.setBranch(otherOrderBranch);
                otherOrder.setOldId(otherOrderOldId);
                if (!containsOtherOrder(data, otherOrder)) {
                    data.otherOrders.add(otherOrder);
                }
            }

            if (directionId != null) {
                Direction dir = new Direction();
                dir.setDirectionId(directionId);
                dir.setName(directionName);
                if (!containsDirection(data.order, dir)) {
                    data.order.addDirection(dir);
                }
            }
            n++;
        }
        List<OrderListData> dataList = new ArrayList();
        dataList.addAll(dataMap.values());
        setOrderViews(dataList);
        setInfoAboutReject(dataList);
        return dataList;
    }

    private void setOrderViews(List<OrderListData> dataList) {
        List<Long> orderIds = new ArrayList();
        Map<Long, Order> orderMap = new HashMap();
        for (OrderListData data : dataList) {
            orderIds.add(data.order.getOrderId());
            orderMap.put(data.order.getOrderId(), data.order);
        }
        List<OrderView> views = orderViewDao.getByOrderIds(orderIds);
        for (OrderView view : views) {
            Long orderId = view.getOrder().getOrderId();
            Order order = orderMap.get(orderId);
            if (order != null) {
                order.addOrderView(view);
            }
        }
    }

    private Long getLong(Object value) {
        if (value == null) {
            return null;
        } else {
            if (value instanceof Long) {
                return (Long) value;
            } else if (value instanceof BigInteger) {
                BigInteger bi = (BigInteger) value;
                return bi.longValue();
            } else if (value instanceof Integer) {
                Integer i = (Integer) value;
                return i.longValue();
            }
        }
        return null;
    }

    private boolean containsOtherOrder(OrderListData data, Order otherOrder) {
        for (Order ord : data.otherOrders) {
            if (ord.getOrderId().equals(otherOrder.getOrderId())) {
                return true;
            }
        }
        return false;
    }

    private boolean containsAuthorSalary(Order order, AuthorSalary authorSalary) {
        if (order.getAuthorSalaryList() != null) {
            for (AuthorSalary sal : order.getAuthorSalaryList()) {
                if (sal.getAuthorSalaryId().equals(authorSalary.getAuthorSalaryId())) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean containsDirection(Order order, Direction dir) {
        if (order.getDirections() != null) {
            for (Direction orderDir : order.getDirections()) {
                if (orderDir.getDirectionId().equals(dir.getDirectionId())) {
                    return true;
                }
            }
        }
        return false;
    }

    public Long getOverdueCount() {
        User authUser = authManager.getCurrentUser();
        Set<Long> branchIds = branchRightsHolder.getBranchIds(BranchRights.SEARCH_ORDER);
        if (authUser instanceof Admin) {
            return orderDao.getOverdueCountForAdmin(branchIds);
        } else {
            Author author = (Author) authUser;
            return orderDao.getOverdueCountForAuthor(branchIds, author);
        }
    }

    private List<Order> _getOrderList(Set<Long> rightBrancheIds, OrderStatus status, OrderSearchData searchData,
            Integer start, Integer numberOfRecords) {
        User currentUser = authManager.getCurrentUser();
        if (currentUser instanceof Admin) {
            return orderDao.getForAdmin(rightBrancheIds, status, searchData, start, numberOfRecords);
        } else {
            Author author = (Author) authManager.getCurrentUser();
            if (status == null) {
                List<Order> list = new ArrayList();
                list.addAll(orderDao.getForAuthorNotReject(author, getAuthorDirectionIds(author), rightBrancheIds,
                        null, searchData, start, numberOfRecords));
                list.addAll(orderDao.getForAuthorReject(author, getAuthorDirectionIds(author), rightBrancheIds,
                        searchData, start, numberOfRecords));
                return list;
            } else if (status.equals(OrderStatus.REJECTION)) {
                return orderDao.getForAuthorReject(author, getAuthorDirectionIds(author), rightBrancheIds,
                        searchData, start, numberOfRecords);
            } else {
                return orderDao.getForAuthorNotReject(author, getAuthorDirectionIds(author), rightBrancheIds,
                        status, searchData, start, numberOfRecords);
            }
        }
    }

    private Set<Long> getAuthorDirectionIds(Author author) {
        Set<Long> list = new HashSet();
        for (Direction dir : author.getDirections()) {
            list.add(dir.getDirectionId());
        }
        return list;
    }

    private List<OrderListData> transformAndAddParameters(List<Order> list) {
        List<OrderListData> dataList = transform(list);
        addOtherOrders(dataList);
        setInfoAboutReject(dataList);
        return dataList;
    }

    private void setInfoAboutReject(List<OrderListData> dataList) {
        User authUser = authManager.getCurrentUser();
        if (authUser instanceof Author) {
            for (OrderListData data : dataList) {
                if (orderService.allowReject(data.order)) {
                    data.allowReject = true;
                }
                if (orderService.allowRecoverFromReject(data.order)) {
                    data.allowRecoverFromReject = true;
                }
                data.existReject = orderService.existRejectForAuthUser(data.order);
            }
        }
    }

    private List<OrderListData> transform(List<Order> orders) {
        List<OrderListData> resultList = new ArrayList();
        for (Order order : orders) {
            OrderListData data = new OrderListData();
            data.order = order;
            resultList.add(data);
        }
        return resultList;
    }

    private void addOtherOrders(List<OrderListData> orders) {
        for (OrderListData data : orders) {
            Order order = data.order;
            String email = order.getClientEmail();
            Long orderId = order.getOrderId();
            List<Order> otherOrders;
            if (email == null || email.isEmpty()) {
                otherOrders = new ArrayList();
            } else {
                otherOrders = orderDao.getOtherOrders(email, order);
            }
            data.otherOrders = otherOrders;
        }
    }

    private String getCurrentDateToString() {
        return (new SimpleDateFormat("dd/MM/yy").format(new Date()));
    }

}