cheng gong de daima

/**
 * Copyright (c) 2012-2016 ebizwindow, Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.ebizwindow.crm.portlet.module.sales;

import java.io.IOException;
import java.util.Map.Entry;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.ebizwindow.crm.bean.Page;
import com.ebizwindow.crm.model.SalesTarget;
import com.ebizwindow.crm.portlet.base.BasePortlet;
import com.ebizwindow.crm.service.OpportunityLocalServiceUtil;
import com.ebizwindow.crm.service.SalesTargetLocalServiceUtil;
import com.ebizwindow.crm.utils.IDGenerator;
import com.ebizwindow.crm.utils.LogUtil;
import com.ebizwindow.crm.utils.PermissionUtil;
import com.ebizwindow.crm.utils.SQLUtil;
import com.ebizwindow.crm.utils.Target;
import com.ebizwindow.crm.utils.TextUtil;
import com.ebizwindow.crm.utils.Validator;
import com.ebizwindow.operator.model.Department;
import com.ebizwindow.operator.model.Operator;
import com.ebizwindow.operator.service.DepartmentLocalServiceUtil;
import com.ebizwindow.operator.service.OperatorLocalServiceUtil;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.util.PortalUtil;

/**
 * <a href="JSPPortlet.java.html"><b><i>View Source</i></b></a>
 *
 * @author eonmain
 *
 */
public class SaleTargetPortlet extends BasePortlet {
    
    @Override
    public void doView(RenderRequest renderRequest,RenderResponse renderResponse) throws IOException, PortletException {
        super.doView(renderRequest, renderResponse);

        String jspPage = (String) renderRequest.getAttribute(FORWARD);

        try {
            if (jspPage == null){
                
                if (PermissionUtil.checkSpecialPermission(renderRequest)) {
                    listSpecialSaleTarget(renderRequest);
                    jspPage = "/jsp/sales/saleTarget/specialRoleView.jsp";
                } else {
                
                    this.listSaleTarget(renderRequest);
                    //画的那个表格
                    this.createXMLDataOfColumn2D(renderRequest);
                    jspPage = this.viewJSP;
                }
            }
        } catch (Exception e) {
            _log.error(e);
        }

        jspPage = jspPage == null ? this.viewJSP : jspPage;
        include(jspPage, renderRequest, renderResponse);
    }

    @Override
    public void processAction(ActionRequest actionRequest,
            ActionResponse actionResponse) throws IOException, PortletException {
        super.processAction(actionRequest, actionResponse);
        
        long companyId = PortalUtil.getCompanyId(actionRequest);
        String operation = ParamUtil.getString(actionRequest,OPERATION);
        if (operation != null) {
            LogUtil.info(_log, actionRequest);
            String forward = null;
            try {
                if (operation.equals("sale.target.search")) {
                    //列出的数据
                    this.listSaleTarget(actionRequest);
                    //根据数据把图表画出来
                    this.createXMLDataOfColumn2D(actionRequest);
                    
                    
                }else if (operation.equals("sale.target.search.view")) {
                    //列出的数据
                    this.listSaleTarget(actionRequest);
                    //根据数据把图表画出来
                    this.createXMLDataOfColumn2D(actionRequest);
                    forward = "/jsp/sales/saleTarget/view.jsp";
                }
                
                
                
                else if (operation.equals("special.sale.target.search.view")){
                    
                    long userRange = ParamUtil.getLong(actionRequest, "userRange", 0);
                    String saleIndex = ParamUtil.getString(actionRequest, "saleIndex", "amount");
                    Integer startYear = ParamUtil.getInteger(actionRequest, "startYear");
                    Integer startMonth = ParamUtil.getInteger(actionRequest, "startMonth", 1);
                    Integer endYear = ParamUtil.getInteger(actionRequest, "endYear");
                    Integer endMonth = ParamUtil.getInteger(actionRequest, "endMonth", 12);
                    
                    _log.info(userRange+","+saleIndex+","+startYear+","+startMonth+","+endYear+","+endMonth);
                    
                    //列出的数据
                    this.listSaleTarget(actionRequest);
                    //根据数据把图表画出来
                    this.createXMLDataOfColumn2D(actionRequest);
                    //必须加上forWord不然这个路径就是null
                    forward = "/jsp/sales/saleTarget/view.jsp";
                }
                
                
                else if (operation.equals("special.sale.target.search")){
                    this.listSpecialSaleTarget(actionRequest);
                    forward = "/jsp/sales/saleTarget/specialRoleView.jsp";
                }
                
                else if(operation.equals("sale.target.set.page")) {//设置销售目标
                    this.listSaleTargetSet(actionRequest);
                    forward = "/jsp/sales/saleTarget/setSaleTarget.jsp";
                } else if (operation.equals("sale.target.edit.page")) {//跳到编辑的页面
                    //跳到编辑的页面
                    Operator operator_operator = OperatorLocalServiceUtil.getOperator(PortalUtil.getUserId(actionRequest));
                    long departmentId = operator_operator.getDepartmentId();
                    long userId = operator_operator.getOperatorId();
                    String sql = SQLUtil.getOperatorSQL(userId);
                    //调用上述的sql语句。
                    List<Long> operatorIds = OperatorLocalServiceUtil.searchBySQLQueryString(sql, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
                    //得到所有的id
                    List<Operator> operators = new ArrayList<Operator>();
                    if (operatorIds != null && operatorIds.size() > 0) {
                        for (int i = 0; i < operatorIds.size(); i++) {
                            long opreatorId = Long.valueOf(String.valueOf(operatorIds.get(i)));
                            Operator operator = OperatorLocalServiceUtil.getOperator(opreatorId);
                            operators.add(operator);
                        }
                    }
                    
                    Page page = new Page();
                    int pageSize = 20;
                    int pageNo = ParamUtil.getInteger(actionRequest, "pageNo" , 0);
                    if (pageNo == 0){
                        if (actionRequest.getPortletSession().getAttribute("pageNo") != null){
                            pageNo = (Integer)actionRequest.getPortletSession().getAttribute("pageNo");
                        } else {
                            pageNo = 1;
                        }
                    }
                    page.setPageNo(pageNo);
                    
                    page.setPageSize(pageSize);
                    
                    int pageCount = operators.size();
                    if (pageCount % page.getPageSize() == 0) {
                        page.setPageCount(pageCount / page.getPageSize());
                    } else {
                        page.setPageCount(pageCount / page.getPageSize() + 1);
                    }
                    int start = (page.getPageNo() - 1) * page.getPageSize() ;
                    int end = page.getPageSize() * page.getPageNo() ;
                    List<Operator> operatorsTemp = new ArrayList<Operator>();
                    
                    for (;start <= end && start <= pageCount-1; start++){
                        operatorsTemp.add(operators.get(start));
                    }
                    operators = operatorsTemp;
                    
                    //List<Operator> operators = OperatorLocalServiceUtil.searchByCompanyId(companyId);
                    actionRequest.setAttribute("operators", operators);
                    
                    forward = "/jsp/sales/saleTarget/editSaleTarget.jsp";

                } else if (operation.equals("sale.target.edit")) {//真正的保存的方法
                    //得到公司所有的操作员
                    List<Operator> operators = OperatorLocalServiceUtil.searchByCompanyId(companyId);
                    //得到日期
                    String targetDate = ParamUtil.getString(actionRequest, "targetDate", StringPool.BLANK);
                    
                    if (!targetDate.equals(StringPool.BLANK)){
                        for(Operator operator : operators){
                            //得到操作员的id
                            long operatorId = operator.getOperatorId();
                            //销售额
                            double salesAmount = ParamUtil.getDouble(actionRequest, "salesAmount" + operatorId, 0);
                            //客户数
                            int salesNum = ParamUtil.getInteger(actionRequest, "salesNum" + operatorId, 0);
                            if (salesAmount != 0 || salesNum != 0){
                                SalesTarget salesTarget = null;
                                salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operatorId, targetDate);
                                if (salesTarget == null){
                                    salesTarget = SalesTargetLocalServiceUtil.createSalesTarget(IDGenerator.increment(SalesTarget.class.getName()));
                                    salesTarget.setCompanyId(companyId);
                                    salesTarget.setUserId(operatorId);
                                    salesTarget.setTargetDate(targetDate);
                                }
                                salesTarget.setSalesAmount(salesAmount);
                                salesTarget.setSalesNum(salesNum);
                                LogUtil.logInfo(_log, actionRequest, salesTarget, "编辑");
                                SalesTargetLocalServiceUtil.updateSalesTarget(salesTarget);
                            }
                        }
                    }
                    
                    this.listSaleTargetSet(actionRequest);
                    //跳转到列表的界面
                    forward = "/jsp/sales/saleTarget/setSaleTarget.jsp";

                }
                //这个是干什么用的???
                PortalUtil.copyRequestParameters(actionRequest, actionResponse);
            } catch (Exception e) {
                _log.error(e);
            }
            _log.debug(FORWARD + " = " + forward);

            if (forward != null){
                actionResponse.setRenderParameter(FORWARD, forward);
            }
        }
    }

    
    
    //需求:这个方法也是要修改的,根据登录的操作员,找到这个操作员的部门中的用户。
    private void listSaleTarget(PortletRequest portletRequest) throws SystemException, PortalException {
        
        
        
        
        long companyId = PortalUtil.getCompanyId(portletRequest);
        
        Calendar calendar = Calendar.getInstance();
        //部门的id
        long userRange = ParamUtil.getLong(portletRequest, "userRange", 0);
        Operator operator_operator = OperatorLocalServiceUtil.getOperator(PortalUtil.getUserId(portletRequest));
        long departmentId = operator_operator.getDepartmentId();
        
        _log.info("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK"+departmentId);
        
        
    
       
        //这个的默认值是amount,就是下拉框的默认值是销售额
        String saleIndex = ParamUtil.getString(portletRequest, "saleIndex", "amount");
        Integer startYear = ParamUtil.getInteger(portletRequest, "startYear", calendar.get(Calendar.YEAR));
        Integer startMonth = ParamUtil.getInteger(portletRequest, "startMonth", 1);
        Integer endYear = ParamUtil.getInteger(portletRequest, "endYear", calendar.get(Calendar.YEAR));
        Integer endMonth = ParamUtil.getInteger(portletRequest, "endMonth", 12);
        
        StringBuffer sql = new StringBuffer();
        //检索销售额数据写的sql。
        if (saleIndex.equals("amount")){    
            sql.append("select sum(opportunity.amount) from CRM_Opportunity opportunity where opportunity.companyId = "+companyId+" and opportunity.status = '已结束/赢得客户' ");
        } else if (saleIndex.equals("num")){
            //检索客户数数据写的sql。
            sql.append("select count(*) from CRM_Customer customer where customer.companyId = " + companyId +" ");
        } else {
            return;
        }
        
        LinkedHashMap<Long, Map<String, String>> entities = null;
        LinkedHashMap<Long, String> userTotalTargetValue = null;
        List<Operator> operators = null;
        
        if (userRange >= 0){
            if (userRange == 0){
                operators = getOperatorByDepartmentId(departmentId);
            } else {
                long deptId = userRange;
                if (deptId > 0){
                    operators = new ArrayList<Operator>();        
                    operators = getOperatorByDepartmentId(deptId);
                }
            }
        }
        //分页
        Page page = new Page();
        int pageSize = 20;
        int pageNo = ParamUtil.getInteger(portletRequest, "pageNo" , 0);
        if (pageNo == 0){
            if (portletRequest.getPortletSession().getAttribute("pageNo") != null){
                pageNo = (Integer)portletRequest.getPortletSession().getAttribute("pageNo");
            } else {
                pageNo = 1;
            }
        }
        page.setPageNo(pageNo);
        
        page.setPageSize(pageSize);
        
        int pageCount = operators.size();
        if (pageCount % page.getPageSize() == 0) {
            page.setPageCount(pageCount / page.getPageSize());
        } else {
            page.setPageCount(pageCount / page.getPageSize() + 1);
        }
        int start = (page.getPageNo() - 1) * page.getPageSize() ;
        int end = page.getPageSize() * page.getPageNo() ;
        List<Operator> operatorsTemp = new ArrayList<Operator>();
        
        for (;start <= end && start <= pageCount-1; start++){
            operatorsTemp.add(operators.get(start));
        }
        operators = operatorsTemp;
        if (operators != null && operators.size() > 0){
            entities = new LinkedHashMap<Long, Map<String, String>>();
            userTotalTargetValue = new LinkedHashMap<Long, String>();
            for (Operator operator : operators){
                Map<String, String> values = new HashMap<String, String>();
                long operatorId = operator.getOperatorId();
                StringBuffer operatorSql = new StringBuffer();
                operatorSql.append(sql.toString());
                if (saleIndex.equals("amount")){
                    operatorSql.append(" and opportunity.ownerId = " + operatorId + " ");
                } else {
                    operatorSql.append(" and customer.ownerId = " + operatorId + " ");
                }
                
                double totalCompleteValue = 0;
                double totalTargetValue = 0;
                double totalCompleteProbability = 0;
                String totalCompleteValueStr = "0";
                String totalTargetValueStr = "0";
                String totalCompleteProbabilityStr = "0%";
                for (int year = startYear; year <= endYear; year++){
                    int startMonthOfYear = 1;
                    int endMonthOfYear = 12;
                    if (year == startYear){
                        startMonthOfYear = startMonth;
                    }
                    if (year == endYear){
                        endMonthOfYear = endMonth;
                    }
                    for (int month = startMonthOfYear; month <= endMonthOfYear; month++){
                        String targetDate = year + "-" + (month > 0 && month < 10 ? "0" + month : month);
                        double completeValue = 0;
                        double targetValue = 0;
                        double completeProbability = 0;
                        StringBuffer dateSql = new StringBuffer();
                        dateSql.append(operatorSql.toString());
                        if (saleIndex.equals("amount")){                            
                            dateSql.append(" and year(opportunity.completeDate) = " + year + " and month(opportunity.completeDate) = " + month);
                        } else {
                            dateSql.append(" and year(customer.createDate) = " + year + " and month(customer.createDate) = " + month);
                        }
                        
                        Object value = OpportunityLocalServiceUtil.searchByQueryStringOfSaleFunnel(dateSql.toString());
                        if (value == null){
                            value = 0;
                        }
                        completeValue = Double.valueOf(value.toString());
                        //根据用户的id和销售日期查找某一个人的在某一个月的销售目标。
                        SalesTarget salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operatorId, targetDate);
                        if (salesTarget != null){
                            if (saleIndex.equals("num")){
                                targetValue = salesTarget.getSalesNum();
                            } else {
                                targetValue = salesTarget.getSalesAmount();
                            }
                        }
                        if (completeValue != 0 && targetValue != 0){
                            completeProbability = completeValue/targetValue;
                        }
                        totalCompleteValue += completeValue;
                        totalTargetValue += targetValue;
                        
                        String completeValueStr = "0";
                        String targetValueStr = "0";
                        String completeProbabilityStr = "0%";
                        if (saleIndex.equals("num")){
                            if (completeValue != 0){
                                completeValueStr = TextUtil.doubleToText(completeValue, 0);
                            }
                            if (targetValue != 0){
                                targetValueStr = TextUtil.doubleToText(targetValue, 0);                                
                            }
                        } else {
                            if (completeValue != 0){
                                completeValueStr = TextUtil.doubleToText(completeValue, 2);
                            }
                            if (targetValue != 0){
                                targetValueStr = TextUtil.doubleToText(targetValue, 2);
                            }
                        }
                        if (completeProbability != 0){
                            completeProbabilityStr = TextUtil.doubleToText(completeProbability*100, 0)+"%";
                            completeProbabilityStr.replaceAll(",", "");
                        }
                        values.put(targetDate, targetValueStr + "-" + completeValueStr + "-" + completeProbabilityStr);
                    }
                    
                }
                if (totalCompleteValue != 0 && totalTargetValue != 0){
                    totalCompleteProbability = totalCompleteValue/totalTargetValue;
                }
                if (totalCompleteValue != 0){
                    totalCompleteValueStr = TextUtil.doubleToText(totalCompleteValue, 2);
                }
                if (totalTargetValue != 0){
                    totalTargetValueStr = TextUtil.doubleToText(totalTargetValue, 2);
                }
                if (totalCompleteProbability != 0){
                    totalCompleteProbabilityStr = TextUtil.doubleToText(totalCompleteProbability*100, 0)+"%";
                    totalCompleteProbabilityStr.replaceAll(",", "");
                }
                userTotalTargetValue.put(operatorId, totalTargetValueStr + "-" + totalCompleteValueStr + "-" + totalCompleteProbabilityStr);
                entities.put(operatorId, values);
            }
        }
        
        portletRequest.setAttribute("entities", entities);
        portletRequest.setAttribute("userTotalTargetValue", userTotalTargetValue);
        portletRequest.setAttribute("userRange", userRange);
        portletRequest.setAttribute("saleIndex", saleIndex);
        portletRequest.setAttribute("startYear", startYear);
        portletRequest.setAttribute("startMonth", startMonth);
        portletRequest.setAttribute("endYear", endYear);
        portletRequest.setAttribute("endMonth", endMonth);
        portletRequest.setAttribute("pageCount", page.getPageCount());
        portletRequest.getPortletSession().setAttribute("pageNo", page.getPageNo());
        
    }
    
    
    private void createXMLDataOfColumn2D(PortletRequest portletRequest) throws SystemException{
        long companyId = PortalUtil.getCompanyId(portletRequest);
        
        Calendar calendar = Calendar.getInstance();
        
        long userRange = ParamUtil.getLong(portletRequest, "userRange", 0);
        String saleIndex = ParamUtil.getString(portletRequest, "saleIndex", "amount");
        Integer startYear = ParamUtil.getInteger(portletRequest, "startYear", calendar.get(Calendar.YEAR));
        Integer startMonth = ParamUtil.getInteger(portletRequest, "startMonth", 1);
        Integer endYear = ParamUtil.getInteger(portletRequest, "endYear", calendar.get(Calendar.YEAR));
        Integer endMonth = ParamUtil.getInteger(portletRequest, "endMonth", 12);
        
        StringBuffer sql = new StringBuffer();
        StringBuffer dataXml = new StringBuffer();
        
        if (saleIndex.equals("amount")){    
            sql.append("select sum(opportunity.amount) from CRM_Opportunity opportunity where opportunity.companyId = "+companyId+" and opportunity.status = '已结束/赢得客户' ");
        } else if (saleIndex.equals("num")){
            sql.append("select count(*) from CRM_Opportunity opportunity where opportunity.companyId = "+companyId+" and opportunity.status = '已结束/赢得客户' ");
        } else {
            return;
        }
        dataXml.append("<chart manageResize='1' caption='完成情况统计表'  decimals='1' formatNumberScale='0' baseFontSize='11' >");
        
        if (userRange >= 0){
            if (userRange != 0){
                long deptId = userRange;
                if (deptId > 0){
                    List<Operator> operators = OperatorLocalServiceUtil.searchByDepartmentId(deptId);
                    String userIdsStr = convert(operators);
                    if (!userIdsStr.equals("")){
                        sql.append(" and opportunity.ownerId in " + userIdsStr + " ");
                    }
                    
                }
                
            }
        }
        _log.info("---------------"+sql);
        StringBuffer dateCategories = new StringBuffer();
        StringBuffer completeValuesXml = new StringBuffer();
        StringBuffer targetValuesXml = new StringBuffer();
        
        dateCategories.append("<categories>");
        completeValuesXml.append("<dataset seriesName='完成' color='c4e3f7' >");
        targetValuesXml.append("<dataset seriesName='目标' color='Fad35e' >");
        
        for (int year = startYear; year <= endYear; year++){
            int startMonthOfYear = 1;
            int endMonthOfYear = 12;
            if (year == startYear){
                startMonthOfYear = startMonth;
            }
            if (year == endYear){
                endMonthOfYear = endMonth;
            }
            for (int month = startMonthOfYear; month <= endMonthOfYear; month++){
                String targetDate = year + "-" + (month > 0 && month < 10 ? "0" + month : month);
                
                dateCategories.append("<category label='" + targetDate + "' />");
                
                String completeValue = "0";
                Double targetValue = 0.0;
                //sql
                StringBuffer dateSql = new StringBuffer();
                dateSql.append(sql.toString());
                dateSql.append(" and year(opportunity.completeDate) = " + year + " and month(opportunity.completeDate) = " + month);
                //complete
                Object value = OpportunityLocalServiceUtil.searchByQueryStringOfSaleFunnel(dateSql.toString());
                if (value == null){
                    value = "0";
                }
                completeValue = value.toString();
                //target
                List<SalesTarget> salesTargets = new ArrayList<SalesTarget>();
                if (userRange >= 0){
                    if (userRange == 0){
                        salesTargets = SalesTargetLocalServiceUtil.searchByTargetDate(companyId, targetDate);
                    } else {
                        long deptId = userRange;
                        if (deptId > 0){
                            List<Operator> operators = OperatorLocalServiceUtil.searchByDepartmentId(deptId);
                            for (Operator operator : operators){
                                long operatorId = operator.getOperatorId();
                                SalesTarget salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operatorId, targetDate);
                                if (salesTarget != null){
                                    salesTargets.add(salesTarget);
                                }
                            }
                            
                        }
                    }
                } else {
                    salesTargets = SalesTargetLocalServiceUtil.searchByTargetDate(companyId, targetDate);
                }
                if (salesTargets != null && salesTargets.size() > 0){
                    for (SalesTarget salesTarget : salesTargets){
                        if (saleIndex.equals("num")){
                            targetValue += Double.valueOf(salesTarget.getSalesNum());
                        } else {
                            targetValue += Double.valueOf(salesTarget.getSalesAmount());
                        }
                    }
                }
                completeValuesXml.append("<set value='" + completeValue + "' />");
                targetValuesXml.append("<set value='" + targetValue + "' />");
                
            }
            
        }
        
        dateCategories.append("</categories>");
        completeValuesXml.append("</dataset>");
        targetValuesXml.append("</dataset>");
        dataXml.append(dateCategories.toString());
        dataXml.append(targetValuesXml.toString());
        dataXml.append(completeValuesXml.toString());
        dataXml.append("</chart>");
        portletRequest.setAttribute("dataXml", dataXml.toString());
        
    }
    
    //这个方法是干什么用的
    private void listSaleTargetSet(PortletRequest portletRequest) throws SystemException, PortalException {
        long companyId = PortalUtil.getCompanyId(portletRequest);
        //列出这个公司的所有的操作员。现在的需求是根据条件查询出来用户
        //首先得到这个部门的id
        Operator operator_operator = OperatorLocalServiceUtil.getOperator(PortalUtil.getUserId(portletRequest));
        long departmentId = operator_operator.getDepartmentId();
        long userId = operator_operator.getOperatorId();
        String sql = SQLUtil.getOperatorSQL(userId);
        //调用上述的sql语句。QueryUtil.ALL_POS这个默认的是查找的所有的
        List<Long> operatorIds = OperatorLocalServiceUtil.searchBySQLQueryString(sql, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
        //得到所有的id
        List<Operator> operators = new ArrayList<Operator>();
        if (operatorIds != null && operatorIds.size() > 0) {
            for (int i = 0; i < operatorIds.size(); i++) {
                long opreatorId = Long.valueOf(String.valueOf(operatorIds.get(i)));
                Operator operator = OperatorLocalServiceUtil.getOperator(opreatorId);
                operators.add(operator);
            }
        }
        
        
        
        
        
        //List<Operator> operators = OperatorLocalServiceUtil.searchByCompanyId(companyId);
        
        //日历
        Calendar calendar = Calendar.getInstance();
        Integer startYear = ParamUtil.getInteger(portletRequest, "startYear", calendar.get(Calendar.YEAR));
        Integer startMonth = ParamUtil.getInteger(portletRequest, "startMonth", 1);
        Integer endYear = ParamUtil.getInteger(portletRequest, "endYear", calendar.get(Calendar.YEAR));
        Integer endMonth = ParamUtil.getInteger(portletRequest, "endMonth", 12);
        

        LinkedHashMap<Long, String> userTotalTargetValue = null;
        
        
        if (operators != null && operators.size() > 0){
            userTotalTargetValue = new LinkedHashMap<Long, String>();
            for (Operator operator : operators){
                double totalSalesAmount = 0;
                int totalSalesNum = 0;
                for (int year = startYear; year <= endYear; year++){
                    int startMonthOfYear = 1;
                    int endMonthOfYear = 12;
                    if (year == startYear){
                        startMonthOfYear = startMonth;
                    }
                    if (year == endYear){
                        endMonthOfYear = endMonth;
                    }
                    for (int month = startMonthOfYear; month <= endMonthOfYear; month++){
                        String targetDate = year + "-" + (month > 0 && month < 10 ? "0" + month : month);
                        
                        SalesTarget salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operator.getOperatorId(), targetDate);
                        if (salesTarget != null){
                            totalSalesAmount += salesTarget.getSalesAmount();
                            totalSalesNum += salesTarget.getSalesNum();
                        }
                    }
                }
                userTotalTargetValue.put(operator.getOperatorId(), TextUtil.doubleToText(totalSalesAmount, 2) + "-" + totalSalesNum);
            }
        }
        
        
        //分页
        Page page = new Page();
        //int pageSize = 20;
        int pageSize = 20;
        int pageNo = ParamUtil.getInteger(portletRequest, "pageNo" , 0);
        if (pageNo == 0){
            if (portletRequest.getPortletSession().getAttribute("pageNo") != null){
                pageNo = (Integer)portletRequest.getPortletSession().getAttribute("pageNo");
            } else {
                pageNo = 1;
            }
        }
        page.setPageNo(pageNo);
        
        page.setPageSize(pageSize);
        
        int pageCount = operators.size();
        if (pageCount % page.getPageSize() == 0) {
            page.setPageCount(pageCount / page.getPageSize());
        } else {
            page.setPageCount(pageCount / page.getPageSize() + 1);
        }
        int start = (page.getPageNo() - 1) * page.getPageSize() ;
        int end = page.getPageSize() * page.getPageNo() ;
        //把分页的数据添加到operatorsTemp集合中
        List<Operator> operatorsTemp = new ArrayList<Operator>();
//////////////////////////////////////////////////////////////////////////////////        
        for (;start <= end && start <= pageCount-1; start++){
            operatorsTemp.add(operators.get(start));
        }
////////////////////////////////////////////////////////////////////////////////////
        
//        //分页查询调用的是持久层中的方法
//        List<Long> tempoperatorIds = OperatorLocalServiceUtil.searchBySQLQueryString(sql, start, end);
//        
//        _log.info("...........................fxr--"+tempoperatorIds);
//        if (tempoperatorIds != null && tempoperatorIds.size() > 0) {
//            for (int i = 0; i < tempoperatorIds.size(); i++) {
//                long opreatorId = Long.valueOf(String.valueOf(tempoperatorIds.get(i)));
//                Operator operator = OperatorLocalServiceUtil.getOperator(opreatorId);
//                operatorsTemp.add(operator);
//            }
//        }
//        
        operators = operatorsTemp;
        
        
        _log.info("..........................."+pageNo);
        
        
        portletRequest.setAttribute("operators", operators);
        portletRequest.setAttribute("userTotalTargetValue", userTotalTargetValue);
        portletRequest.setAttribute("startYear", startYear);
        portletRequest.setAttribute("startMonth", startMonth);
        portletRequest.setAttribute("endYear", endYear);
        portletRequest.setAttribute("endMonth", endMonth);
        portletRequest.setAttribute("pageCount", page.getPageCount());
        portletRequest.getPortletSession().setAttribute("pageNo", page.getPageNo());
    }
    
    private String convert(List<Operator> operators){
        String result = "";
        if (Validator.isNotNull(operators)){
            result += "(";
            for (Operator operator : operators) {
                long operatorId = operator.getOperatorId();
                result += operatorId + ",";
            }
            result = result.substring(0, result.length()-1);
            result += ")";
        }
        
        return result;
    }
    //通过departmentId得到操作员
    public static List<Operator> getOperatorByDepartmentId(long departmentId) throws SystemException, PortalException {
        List<Operator> operators = new ArrayList<Operator>();
        if (departmentId > 0) {
            //根据departmentId得到操作员的集合
            List<Operator> deptOperators = OperatorLocalServiceUtil.searchByDepartmentId(departmentId);
            operators.addAll(deptOperators);
            //通过父节点查找所有的子节点。
            List<Department> departments = DepartmentLocalServiceUtil.searchByParentDepartmentId(departmentId);
            if (Validator.isNotNull(departments)) {
                for (Department entity : departments) {
                    //这个是父节点的departmentId
                    long entityId = entity.getDepartmentId();
                    //得到父节点的操作员
                    deptOperators = OperatorLocalServiceUtil.searchByDepartmentId(entityId);
                    operators.addAll(deptOperators);
                    
                    getAllSubDepartment(entityId, operators);
                }
            }
        }
        return operators;
    }
    
    private static void getAllSubDepartment(long departmentId, List<Operator> operators) throws SystemException, PortalException {
        List<Department> departments = DepartmentLocalServiceUtil.searchByParentDepartmentId(departmentId);
        if (Validator.isNotNull(departments)) {
            for (Department entity : departments) {
                long entityId = entity.getDepartmentId();
                List<Operator> deptOperators = OperatorLocalServiceUtil.searchByDepartmentId(entityId);
                operators.addAll(deptOperators);
                getAllSubDepartment(entityId, operators);
            }
        }
    }

    
    
    ////////////////////////////////////////////////////////////////////////////////
    
private void listSpecialSaleTarget(PortletRequest portletRequest) throws SystemException, PortalException {
        
        _log.info("执行listSpecialSaleTarget");
    
    
        long companyId = PortalUtil.getCompanyId(portletRequest);
        //首先根据companyId找到所有的部门
        List<Department> departments = DepartmentLocalServiceUtil.searchByCompanyId(companyId);
        String key1 = "大区一";
        String key2 = "大区二";
        String key3 = "大区三";
        String key4 = "大区四";
        String key5 = "大区五";
        String key6 = "大区六";
         //这个集合是用来保存大区一中Long 指的是大区域id,map里放的是月份和对应的总的值
        LinkedHashMap<Long, Map<String, String>> entities = null;
        LinkedHashMap<Long, Map<String, String>> dateentities = new LinkedHashMap<Long, Map<String,String>>();
        LinkedHashMap<Long, String> userDateTotal = new LinkedHashMap<Long, String>();
        List<Operator> speacialoperators = new ArrayList<Operator>();
        long userRange = ParamUtil.getLong(portletRequest, "userRange", 0);
        _log.info(userRange+"............");
        Calendar calendar = Calendar.getInstance();
        Operator operator_operator = OperatorLocalServiceUtil.getOperator(PortalUtil.getUserId(portletRequest));
        long departmentId = operator_operator.getDepartmentId();
        String saleIndex = ParamUtil.getString(portletRequest, "saleIndex", "amount");
        Integer startYear = ParamUtil.getInteger(portletRequest, "startYear", calendar.get(Calendar.YEAR));
        Integer startMonth = ParamUtil.getInteger(portletRequest, "startMonth", 1);
        Integer endYear = ParamUtil.getInteger(portletRequest, "endYear", calendar.get(Calendar.YEAR));
        Integer endMonth = ParamUtil.getInteger(portletRequest, "endMonth", 12);
        
        StringBuffer sql = new StringBuffer();
        //检索销售额数据写的sql。
        if (saleIndex.equals("amount")){    
            sql.append("select sum(opportunity.amount) from CRM_Opportunity opportunity where opportunity.companyId = "+companyId+" and opportunity.status = '已结束/赢得客户' ");
        } else if (saleIndex.equals("num")){
            //检索客户数数据写的sql。
            sql.append("select count(*) from CRM_Customer customer where customer.companyId = " + companyId +" ");
        } else {
            return;
        }
        
        
        LinkedHashMap<Long, String> userTotalTargetValue = null;
        
        //存放部门和部门的ID
        List<String> departmtntAndIDString = new ArrayList<String>();
        
        for (int i = 0;i<departments.size();i++) {
            if (departments.get(i).getDepartmentName().equals(key1)) {
                String bianhaoString = departments.get(i).getDepartmentId()+"-"+key1;
                departmtntAndIDString.add(bianhaoString);
                //大区一中所有的用户
                speacialoperators = getOperatorByDepartmentId(departments.get(i).getDepartmentId());
                
                 if (speacialoperators != null && speacialoperators.size() > 0){
                    entities = new LinkedHashMap<Long, Map<String, String>>();
                    userTotalTargetValue = new LinkedHashMap<Long, String>();
                    
                    String totalCompleteValueStr = "0";
                    String totalTargetValueStr = "0";
                    String totalCompleteProbabilityStr = "0%";
                    for (Operator operator : speacialoperators){
                        Map<String, String> values = new HashMap<String, String>();
                        long operatorId = operator.getOperatorId();
                        StringBuffer operatorSql = new StringBuffer();
                        operatorSql.append(sql.toString());
                        if (saleIndex.equals("amount")){
                            operatorSql.append(" and opportunity.ownerId = " + operatorId + " ");
                        } else {
                            operatorSql.append(" and customer.ownerId = " + operatorId + " ");
                        }
                        
                        
                        double totalCompleteValue = 0;
                        double totalTargetValue = 0;
                        double totalCompleteProbability = 0;
                        
                        for (int year = startYear; year <= endYear; year++){
                            //定义三个变量用来计算这个部门中所有的用户的总的总和
                            double total_totalCompleteValue = 0;
                            double total_totalTargetValue = 0;
                            double total_totalCompleteProbability = 0;
                            int startMonthOfYear = 1;
                            int endMonthOfYear = 12;
                            if (year == startYear){
                                startMonthOfYear = startMonth;
                            }
                            if (year == endYear){
                                endMonthOfYear = endMonth;
                            }
                            for (int month = startMonthOfYear; month <= endMonthOfYear; month++){
                                String targetDate = year + "-" + (month > 0 && month < 10 ? "0" + month : month);
                                double completeValue = 0;
                                double targetValue = 0;
                                double completeProbability = 0;
                                StringBuffer dateSql = new StringBuffer();
                                dateSql.append(operatorSql.toString());
                                if (saleIndex.equals("amount")){                            
                                    dateSql.append(" and year(opportunity.completeDate) = " + year + " and month(opportunity.completeDate) = " + month);
                                } else {
                                    dateSql.append(" and year(customer.createDate) = " + year + " and month(customer.createDate) = " + month);
                                }
                                
                                Object value = OpportunityLocalServiceUtil.searchByQueryStringOfSaleFunnel(dateSql.toString());
                                if (value == null){
                                    value = 0;
                                }
                                completeValue = Double.valueOf(value.toString());
                                //根据用户的id和销售日期查找某一个人的在某一个月的销售目标。
                                SalesTarget salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operatorId, targetDate);
                                if (salesTarget != null){
                                    if (saleIndex.equals("num")){
                                        targetValue = salesTarget.getSalesNum();
                                    } else {
                                        targetValue = salesTarget.getSalesAmount();
                                    }
                                }
                                if (completeValue != 0 && targetValue != 0){
                                    completeProbability = completeValue/targetValue;
                                }
                                totalCompleteValue += completeValue;
                                totalTargetValue += targetValue;
                                //求和
                                total_totalTargetValue += totalTargetValue;
                                total_totalCompleteValue += totalCompleteValue;
                                
                                String completeValueStr = "0";
                                String targetValueStr = "0";
                                String completeProbabilityStr = "0%";
                                if (saleIndex.equals("num")){
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 0);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 0);                                
                                    }
                                } else {
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 2);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 2);
                                    }
                                }
                                if (completeProbability != 0){
                                    completeProbabilityStr = TextUtil.doubleToText(completeProbability*100, 0)+"%";
                                    completeProbabilityStr.replaceAll(",", "");
                                }
                                values.put(targetDate, targetValueStr + "-" + completeValueStr + "-" + completeProbabilityStr);
                                
                                
                            }
                            
                            if (totalCompleteValue != 0 && totalTargetValue != 0){
                                totalCompleteProbability = totalCompleteValue/totalTargetValue;
                                total_totalCompleteProbability += totalCompleteProbability;
                            }
                            if (totalCompleteValue != 0){
                                totalCompleteValueStr = TextUtil.doubleToText(total_totalCompleteValue, 2);
                            }
                            if (totalTargetValue != 0){
                                totalTargetValueStr = TextUtil.doubleToText(total_totalTargetValue, 2);
                            }
                            if (totalCompleteProbability != 0){
                                totalCompleteProbabilityStr = TextUtil.doubleToText(total_totalCompleteProbability*100, 0)+"%";
                                totalCompleteProbabilityStr.replaceAll(",", "");
                            }
                            
                            
                            entities.put(operatorId, values);
                        }
                        //求的总的总和
                        //userDateTotal.put(departments.get(i).getDepartmentId(), totalTargetValueStr + "-" + totalCompleteValueStr + "-" + totalCompleteProbabilityStr);
                        
                        }
                    
                        
                }
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                
                //下面开始计算
                    String targetDate = "";
                    // 我要对上述的集合做求和的处理

                    List<Target> list = new ArrayList<Target>();
                    //为什么是一个Long不能转化成一个字符串
                    Iterator entitiesIterator = entities.entrySet().iterator();
                    while (entitiesIterator.hasNext()) {
                        Map.Entry entry = (Entry) entitiesIterator.next();
                        Long name = (Long) entry.getKey();
                        _log.info("..........................--"+name);
                        Map<String, String> valMap = (Map<String, String>) entry.getValue();
                        System.out.println(name + " " + valMap.toString());
                        Iterator values_iter = valMap.entrySet().iterator();
                        String keydateString = "";
                        String vvvString = "";
                        while (values_iter.hasNext()) {
                            Map.Entry entryvaEntry = (Map.Entry) values_iter.next();// 得到map中的每一条的数据
                            keydateString = (String) entryvaEntry.getKey();
                            vvvString = (String) entryvaEntry.getValue();
                            // 在这个地方我需要处理的就是把这些数据存到ArrayList中
                            Target target = new Target();
                            target.setKetDate(keydateString);
                            target.setValue(vvvString);
                            list.add(target);

                        }

                    }
                    System.out.println(list.size());
                    
                    ////遍历values中的值计算总的和就可以了。
                    double sum1 = 0;
                    double sum2 = 0;
                    double sum3 = 0;
                    String str_totalCompleteValueStr = "0";
                    String str_totalTargetValueStr = "0";
                    String str_totalCompleteProbabilityStr = "0%";
                    for (int k = 0;k<list.size();k++) {
                        final Target target = list.get(k);
                        String[] values = target.getValue().split("-");
                        sum1 += Double.parseDouble(values[0].replace(",", ""));
                        sum2 += Double.parseDouble(values[1].replace(",",""));
                        sum3 += Double.parseDouble(values[2].substring(0, values[2].length() - 1));
                        if (sum2 != 0){
                                str_totalCompleteValueStr = TextUtil.doubleToText(sum2, 2);
                        }
                        if (sum1 != 0){
                                str_totalTargetValueStr = TextUtil.doubleToText(sum1, 2);
                        }
                        if (sum3 != 0){
                                str_totalCompleteProbabilityStr = TextUtil.doubleToText(sum3*100, 0)+"%";
                                str_totalCompleteProbabilityStr.replaceAll(",", "");
                        }
                        
                        userDateTotal.put(departments.get(i).getDepartmentId(), str_totalTargetValueStr + "-" + str_totalCompleteValueStr + "-" + str_totalCompleteProbabilityStr);
                    }
                    
                    
                    
                    
                
                    Map<String, String> map = new HashMap<String,String>();
                    //计算每个月的和返回一个map
                    for (int year = startYear; year <= endYear; year++){
                        int startMonthOfYear = 1;
                        int endMonthOfYear = 12;
                        if (year == startYear){
                            startMonthOfYear = startMonth;
                        }
                        if (year == endYear){
                            endMonthOfYear = endMonth;
                        }
                    for (int month = startMonthOfYear; month <= endMonthOfYear; month++) {
                        targetDate = year + "-"
                                + (month > 0 && month < 10 ? "0" + month : month);
                        
                        
                        map.putAll(CalReturn(list, targetDate));
                        
                        
                    }
                    }
                    //这个就是得到每个月的消费的记录的和.这个就是得到的就是这个部门下的所有的用户在每个月的销售目标的总的和
                    
                    dateentities.put(departments.get(i).getDepartmentId(), map);
                    
                    
            }
            if (departments.get(i).getDepartmentName().equals(key2)) {
                String bianhaoString = departments.get(i).getDepartmentId()+"-"+key2;
                departmtntAndIDString.add(bianhaoString);
                //大区二中所有的用户
                speacialoperators = getOperatorByDepartmentId(departments.get(i).getDepartmentId());
                
                 if (speacialoperators != null && speacialoperators.size() > 0){
                    entities = new LinkedHashMap<Long, Map<String, String>>();
                    userTotalTargetValue = new LinkedHashMap<Long, String>();
                
                   String totalCompleteValueStr = "0";
                String totalTargetValueStr = "0";
                String totalCompleteProbabilityStr = "0%";
                    for (Operator operator : speacialoperators){
                        Map<String, String> values = new HashMap<String, String>();
                        long operatorId = operator.getOperatorId();
                        StringBuffer operatorSql = new StringBuffer();
                        operatorSql.append(sql.toString());
                        if (saleIndex.equals("amount")){
                            operatorSql.append(" and opportunity.ownerId = " + operatorId + " ");
                        } else {
                            operatorSql.append(" and customer.ownerId = " + operatorId + " ");
                        }
                        
                        
                        double totalCompleteValue = 0;
                        double totalTargetValue = 0;
                        double totalCompleteProbability = 0;
                        
                        for (int year = startYear; year <= endYear; year++){
                            //定义三个变量用来计算这个部门中所有的用户的总的总和
                            double total_totalCompleteValue = 0;
                               double total_totalTargetValue = 0;
                               double total_totalCompleteProbability = 0;
                            int startMonthOfYear = 1;
                            int endMonthOfYear = 12;
                            if (year == startYear){
                                startMonthOfYear = startMonth;
                            }
                            if (year == endYear){
                                endMonthOfYear = endMonth;
                            }
                            for (int month = startMonthOfYear; month <= endMonthOfYear; month++){
                                String targetDate = year + "-" + (month > 0 && month < 10 ? "0" + month : month);
                                double completeValue = 0;
                                double targetValue = 0;
                                double completeProbability = 0;
                                StringBuffer dateSql = new StringBuffer();
                                dateSql.append(operatorSql.toString());
                                if (saleIndex.equals("amount")){                            
                                    dateSql.append(" and year(opportunity.completeDate) = " + year + " and month(opportunity.completeDate) = " + month);
                                } else {
                                    dateSql.append(" and year(customer.createDate) = " + year + " and month(customer.createDate) = " + month);
                                }
                                
                                Object value = OpportunityLocalServiceUtil.searchByQueryStringOfSaleFunnel(dateSql.toString());
                                if (value == null){
                                    value = 0;
                                }
                                completeValue = Double.valueOf(value.toString());
                                //根据用户的id和销售日期查找某一个人的在某一个月的销售目标。
                                SalesTarget salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operatorId, targetDate);
                                if (salesTarget != null){
                                    if (saleIndex.equals("num")){
                                        targetValue = salesTarget.getSalesNum();
                                    } else {
                                        targetValue = salesTarget.getSalesAmount();
                                    }
                                }
                                if (completeValue != 0 && targetValue != 0){
                                    completeProbability = completeValue/targetValue;
                                }
                                totalCompleteValue += completeValue;
                                totalTargetValue += targetValue;
                                //求和
                                total_totalTargetValue += totalTargetValue;
                                total_totalCompleteValue += totalCompleteValue;
                                
                                String completeValueStr = "0";
                                String targetValueStr = "0";
                                String completeProbabilityStr = "0%";
                                if (saleIndex.equals("num")){
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 0);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 0);                                
                                    }
                                } else {
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 2);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 2);
                                    }
                                }
                                if (completeProbability != 0){
                                    completeProbabilityStr = TextUtil.doubleToText(completeProbability*100, 0)+"%";
                                    completeProbabilityStr.replaceAll(",", "");
                                }
                                values.put(targetDate, targetValueStr + "-" + completeValueStr + "-" + completeProbabilityStr);
                                
                                
                            }

                            if (totalCompleteValue != 0 && totalTargetValue != 0){
                                totalCompleteProbability = totalCompleteValue/totalTargetValue;
                                total_totalCompleteProbability += totalCompleteProbability;
                            }
                            if (totalCompleteValue != 0){
                                totalCompleteValueStr = TextUtil.doubleToText(total_totalCompleteValue, 2);
                            }
                            if (totalTargetValue != 0){
                                totalTargetValueStr = TextUtil.doubleToText(total_totalTargetValue, 2);
                            }
                            if (totalCompleteProbability != 0){
                                totalCompleteProbabilityStr = TextUtil.doubleToText(total_totalCompleteProbability*100, 0)+"%";
                                totalCompleteProbabilityStr.replaceAll(",", "");
                            }
                            
                            entities.put(operatorId, values);
                        }
                        //求的总的总和
                        //userDateTotal.put(departments.get(i).getDepartmentId(), totalTargetValueStr + "-" + totalCompleteValueStr + "-" + totalCompleteProbabilityStr);
                        }
                    
                }
                //下面开始计算
                    String targetDate = "";
                    // 我要对上述的集合做求和的处理

                    List<Target> list = new ArrayList<Target>();
                    Iterator entitiesIterator = entities.entrySet().iterator();
                    while (entitiesIterator.hasNext()) {
                        Map.Entry entry = (Entry) entitiesIterator.next();
                        Long name = (Long) entry.getKey();
                        Map<String, String> valMap = (Map<String, String>) entry.getValue();
                        System.out.println(name + " " + valMap.toString());
                        Iterator values_iter = valMap.entrySet().iterator();
                        String keydateString = "";
                        String vvvString = "";
                        while (values_iter.hasNext()) {
                            Map.Entry entryvaEntry = (Map.Entry) values_iter.next();// 得到map中的每一条的数据
                            keydateString = (String) entryvaEntry.getKey();
                            vvvString = (String) entryvaEntry.getValue();
                            // 在这个地方我需要处理的就是把这些数据存到ArrayList中
                            Target target = new Target();
                            target.setKetDate(keydateString);
                            target.setValue(vvvString);
                            list.add(target);

                        }

                    }
                    System.out.println(list.size());
                ////遍历values中的值计算总的和就可以了。
                    double sum1 = 0;
                    double sum2 = 0;
                    double sum3 = 0;
                    String str_totalCompleteValueStr = "0";
                    String str_totalTargetValueStr = "0";
                    String str_totalCompleteProbabilityStr = "0%";
                    for (int k = 0;k<list.size();k++) {
                        final Target target = list.get(k);
                        String[] values = target.getValue().split("-");
                        sum1 += Double.parseDouble(values[0].replace(",", ""));
                        sum2 += Double.parseDouble(values[1].replace(",",""));
                        sum3 += Double.parseDouble(values[2].substring(0, values[2].length() - 1));
                        if (sum2 != 0){
                                str_totalCompleteValueStr = TextUtil.doubleToText(sum2, 2);
                        }
                        if (sum1 != 0){
                                str_totalTargetValueStr = TextUtil.doubleToText(sum1, 2);
                        }
                        if (sum3 != 0){
                                str_totalCompleteProbabilityStr = TextUtil.doubleToText(sum3*100, 0)+"%";
                                str_totalCompleteProbabilityStr.replaceAll(",", "");
                        }
                        
                        userDateTotal.put(departments.get(i).getDepartmentId(), str_totalTargetValueStr + "-" + str_totalCompleteValueStr + "-" + str_totalCompleteProbabilityStr);
                    }
                
                    Map<String, String> map = new HashMap<String,String>();
                    //计算每个月的和返回一个map
                    for (int year = startYear; year <= endYear; year++){
                        int startMonthOfYear = 1;
                        int endMonthOfYear = 12;
                        if (year == startYear){
                            startMonthOfYear = startMonth;
                        }
                        if (year == endYear){
                            endMonthOfYear = endMonth;
                        }
                    for (int month = startMonthOfYear; month <= endMonthOfYear; month++) {
                        targetDate = year + "-"
                                + (month > 0 && month < 10 ? "0" + month : month);
                        
                        
                         map.putAll(CalReturn(list, targetDate));
                        
                        
                    }
                    }
                    //这个就是得到每个月的消费的记录的和.这个就是得到的就是这个部门下的所有的用户在每个月的销售目标的总的和
                     
                     dateentities.put(departments.get(i).getDepartmentId(), map);
                    
                
                
                
                
            }
            if (departments.get(i).getDepartmentName().equals(key3)) {
                String bianhaoString = departments.get(i).getDepartmentId()+"-"+key3;
                departmtntAndIDString.add(bianhaoString);
                //大区三中所有的用户
                speacialoperators = getOperatorByDepartmentId(departments.get(i).getDepartmentId());
                
                
                 if (speacialoperators != null && speacialoperators.size() > 0){
                    entities = new LinkedHashMap<Long, Map<String, String>>();
                    userTotalTargetValue = new LinkedHashMap<Long, String>();
                    
                   String totalCompleteValueStr = "0";
                String totalTargetValueStr = "0";
                String totalCompleteProbabilityStr = "0%";
                    for (Operator operator : speacialoperators){
                        Map<String, String> values = new HashMap<String, String>();
                        long operatorId = operator.getOperatorId();
                        StringBuffer operatorSql = new StringBuffer();
                        operatorSql.append(sql.toString());
                        if (saleIndex.equals("amount")){
                            operatorSql.append(" and opportunity.ownerId = " + operatorId + " ");
                        } else {
                            operatorSql.append(" and customer.ownerId = " + operatorId + " ");
                        }
                        
                        
                        double totalCompleteValue = 0;
                        double totalTargetValue = 0;
                        double totalCompleteProbability = 0;
                        
                        for (int year = startYear; year <= endYear; year++){
                            //定义三个变量用来计算这个部门中所有的用户的总的总和
                            double total_totalCompleteValue = 0;
                           double total_totalTargetValue = 0;
                           double total_totalCompleteProbability = 0;
                            int startMonthOfYear = 1;
                            int endMonthOfYear = 12;
                            if (year == startYear){
                                startMonthOfYear = startMonth;
                            }
                            if (year == endYear){
                                endMonthOfYear = endMonth;
                            }
                            for (int month = startMonthOfYear; month <= endMonthOfYear; month++){
                                String targetDate = year + "-" + (month > 0 && month < 10 ? "0" + month : month);
                                double completeValue = 0;
                                double targetValue = 0;
                                double completeProbability = 0;
                                StringBuffer dateSql = new StringBuffer();
                                dateSql.append(operatorSql.toString());
                                if (saleIndex.equals("amount")){                            
                                    dateSql.append(" and year(opportunity.completeDate) = " + year + " and month(opportunity.completeDate) = " + month);
                                } else {
                                    dateSql.append(" and year(customer.createDate) = " + year + " and month(customer.createDate) = " + month);
                                }
                                
                                Object value = OpportunityLocalServiceUtil.searchByQueryStringOfSaleFunnel(dateSql.toString());
                                if (value == null){
                                    value = 0;
                                }
                                completeValue = Double.valueOf(value.toString());
                                //根据用户的id和销售日期查找某一个人的在某一个月的销售目标。
                                SalesTarget salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operatorId, targetDate);
                                if (salesTarget != null){
                                    if (saleIndex.equals("num")){
                                        targetValue = salesTarget.getSalesNum();
                                    } else {
                                        targetValue = salesTarget.getSalesAmount();
                                    }
                                }
                                if (completeValue != 0 && targetValue != 0){
                                    completeProbability = completeValue/targetValue;
                                }
                                totalCompleteValue += completeValue;
                                totalTargetValue += targetValue;
                                //求和
                                total_totalTargetValue += totalTargetValue;
                                total_totalCompleteValue += totalCompleteValue;
                                
                                String completeValueStr = "0";
                                String targetValueStr = "0";
                                String completeProbabilityStr = "0%";
                                if (saleIndex.equals("num")){
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 0);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 0);                                
                                    }
                                } else {
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 2);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 2);
                                    }
                                }
                                if (completeProbability != 0){
                                    completeProbabilityStr = TextUtil.doubleToText(completeProbability*100, 0)+"%";
                                    completeProbabilityStr.replaceAll(",", "");
                                }
                                values.put(targetDate, targetValueStr + "-" + completeValueStr + "-" + completeProbabilityStr);
                                
                                
                            }
                            if (totalCompleteValue != 0 && totalTargetValue != 0){
                                totalCompleteProbability = totalCompleteValue/totalTargetValue;
                                total_totalCompleteProbability += totalCompleteProbability;
                            }
                            if (totalCompleteValue != 0){
                                totalCompleteValueStr = TextUtil.doubleToText(total_totalCompleteValue, 2);
                            }
                            if (totalTargetValue != 0){
                                totalTargetValueStr = TextUtil.doubleToText(total_totalTargetValue, 2);
                            }
                            if (totalCompleteProbability != 0){
                                totalCompleteProbabilityStr = TextUtil.doubleToText(total_totalCompleteProbability*100, 0)+"%";
                                totalCompleteProbabilityStr.replaceAll(",", "");
                            }
                            
                            entities.put(operatorId, values);
                        }
                        //求的总的总和
                        //userDateTotal.put(departments.get(i).getDepartmentId(), totalTargetValueStr + "-" + totalCompleteValueStr + "-" + totalCompleteProbabilityStr);
                        }
                    
                        
                }
                //下面开始计算
                    String targetDate = "";
                    // 我要对上述的集合做求和的处理

                    List<Target> list = new ArrayList<Target>();
                    Iterator entitiesIterator = entities.entrySet().iterator();
                    while (entitiesIterator.hasNext()) {
                        Map.Entry entry = (Entry) entitiesIterator.next();
                        Long name = (Long) entry.getKey();
                        Map<String, String> valMap = (Map<String, String>) entry.getValue();
                        System.out.println(name + " " + valMap.toString());
                        Iterator values_iter = valMap.entrySet().iterator();
                        String keydateString = "";
                        String vvvString = "";
                        while (values_iter.hasNext()) {
                            Map.Entry entryvaEntry = (Map.Entry) values_iter.next();// 得到map中的每一条的数据
                            keydateString = (String) entryvaEntry.getKey();
                            vvvString = (String) entryvaEntry.getValue();
                            // 在这个地方我需要处理的就是把这些数据存到ArrayList中
                            Target target = new Target();
                            target.setKetDate(keydateString);
                            target.setValue(vvvString);
                            list.add(target);

                        }

                    }
                    System.out.println(list.size());
                ////遍历values中的值计算总的和就可以了。
                    double sum1 = 0;
                    double sum2 = 0;
                    double sum3 = 0;
                    String str_totalCompleteValueStr = "0";
                    String str_totalTargetValueStr = "0";
                    String str_totalCompleteProbabilityStr = "0%";
                    for (int k = 0;k<list.size();k++) {
                        final Target target = list.get(k);
                        String[] values = target.getValue().split("-");
                        sum1 += Double.parseDouble(values[0].replace(",", ""));
                        sum2 += Double.parseDouble(values[1].replace(",",""));
                        sum3 += Double.parseDouble(values[2].substring(0, values[2].length() - 1));
                        if (sum2 != 0){
                                str_totalCompleteValueStr = TextUtil.doubleToText(sum2, 2);
                        }
                        if (sum1 != 0){
                                str_totalTargetValueStr = TextUtil.doubleToText(sum1, 2);
                        }
                        if (sum3 != 0){
                                str_totalCompleteProbabilityStr = TextUtil.doubleToText(sum3*100, 0)+"%";
                                str_totalCompleteProbabilityStr.replaceAll(",", "");
                        }
                        
                        userDateTotal.put(departments.get(i).getDepartmentId(), str_totalTargetValueStr + "-" + str_totalCompleteValueStr + "-" + str_totalCompleteProbabilityStr);
                    }
                
                    Map<String, String> map = new HashMap<String,String>();
                    //计算每个月的和返回一个map
                    for (int year = startYear; year <= endYear; year++){
                        int startMonthOfYear = 1;
                        int endMonthOfYear = 12;
                        if (year == startYear){
                            startMonthOfYear = startMonth;
                        }
                        if (year == endYear){
                            endMonthOfYear = endMonth;
                        }
                    for (int month = startMonthOfYear; month <= endMonthOfYear; month++) {
                        targetDate = year + "-"
                                + (month > 0 && month < 10 ? "0" + month : month);
                        
                        
                         map.putAll(CalReturn(list, targetDate));
                        
                        
                    }
                    }
                    //这个就是得到每个月的消费的记录的和.这个就是得到的就是这个部门下的所有的用户在每个月的销售目标的总的和
                    
                     dateentities.put(departments.get(i).getDepartmentId(), map);
                    
            }
            if (departments.get(i).getDepartmentName().equals(key4)) {
                String bianhaoString = departments.get(i).getDepartmentId()+"-"+key4;
                departmtntAndIDString.add(bianhaoString);
                //大区四中所有的用户
                speacialoperators = getOperatorByDepartmentId(departments.get(i).getDepartmentId());
                
                
                 if (speacialoperators != null && speacialoperators.size() > 0){
                    entities = new LinkedHashMap<Long, Map<String, String>>();
                    userTotalTargetValue = new LinkedHashMap<Long, String>();
                    
                   String totalCompleteValueStr = "0";
                String totalTargetValueStr = "0";
                String totalCompleteProbabilityStr = "0%";
                    for (Operator operator : speacialoperators){
                        Map<String, String> values = new HashMap<String, String>();
                        long operatorId = operator.getOperatorId();
                        StringBuffer operatorSql = new StringBuffer();
                        operatorSql.append(sql.toString());
                        if (saleIndex.equals("amount")){
                            operatorSql.append(" and opportunity.ownerId = " + operatorId + " ");
                        } else {
                            operatorSql.append(" and customer.ownerId = " + operatorId + " ");
                        }
                        
                        
                        double totalCompleteValue = 0;
                        double totalTargetValue = 0;
                        double totalCompleteProbability = 0;
                        
                        for (int year = startYear; year <= endYear; year++){
                            //定义三个变量用来计算这个部门中所有的用户的总的总和
                            double total_totalCompleteValue = 0;
                           double total_totalTargetValue = 0;
                           double total_totalCompleteProbability = 0;
                            int startMonthOfYear = 1;
                            int endMonthOfYear = 12;
                            if (year == startYear){
                                startMonthOfYear = startMonth;
                            }
                            if (year == endYear){
                                endMonthOfYear = endMonth;
                            }
                            for (int month = startMonthOfYear; month <= endMonthOfYear; month++){
                                String targetDate = year + "-" + (month > 0 && month < 10 ? "0" + month : month);
                                double completeValue = 0;
                                double targetValue = 0;
                                double completeProbability = 0;
                                StringBuffer dateSql = new StringBuffer();
                                dateSql.append(operatorSql.toString());
                                if (saleIndex.equals("amount")){                            
                                    dateSql.append(" and year(opportunity.completeDate) = " + year + " and month(opportunity.completeDate) = " + month);
                                } else {
                                    dateSql.append(" and year(customer.createDate) = " + year + " and month(customer.createDate) = " + month);
                                }
                                
                                Object value = OpportunityLocalServiceUtil.searchByQueryStringOfSaleFunnel(dateSql.toString());
                                if (value == null){
                                    value = 0;
                                }
                                completeValue = Double.valueOf(value.toString());
                                //根据用户的id和销售日期查找某一个人的在某一个月的销售目标。
                                SalesTarget salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operatorId, targetDate);
                                if (salesTarget != null){
                                    if (saleIndex.equals("num")){
                                        targetValue = salesTarget.getSalesNum();
                                    } else {
                                        targetValue = salesTarget.getSalesAmount();
                                    }
                                }
                                if (completeValue != 0 && targetValue != 0){
                                    completeProbability = completeValue/targetValue;
                                }
                                totalCompleteValue += completeValue;
                                totalTargetValue += targetValue;
                                //求和
                                total_totalTargetValue += totalTargetValue;
                                total_totalCompleteValue += totalCompleteValue;
                                
                                String completeValueStr = "0";
                                String targetValueStr = "0";
                                String completeProbabilityStr = "0%";
                                if (saleIndex.equals("num")){
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 0);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 0);                                
                                    }
                                } else {
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 2);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 2);
                                    }
                                }
                                if (completeProbability != 0){
                                    completeProbabilityStr = TextUtil.doubleToText(completeProbability*100, 0)+"%";
                                    completeProbabilityStr.replaceAll(",", "");
                                }
                                values.put(targetDate, targetValueStr + "-" + completeValueStr + "-" + completeProbabilityStr);
                                
                                
                            }
                            if (totalCompleteValue != 0 && totalTargetValue != 0){
                                totalCompleteProbability = totalCompleteValue/totalTargetValue;
                                total_totalCompleteProbability += totalCompleteProbability;
                            }
                            if (totalCompleteValue != 0){
                                totalCompleteValueStr = TextUtil.doubleToText(total_totalCompleteValue, 2);
                            }
                            if (totalTargetValue != 0){
                                totalTargetValueStr = TextUtil.doubleToText(total_totalTargetValue, 2);
                            }
                            if (totalCompleteProbability != 0){
                                totalCompleteProbabilityStr = TextUtil.doubleToText(total_totalCompleteProbability*100, 0)+"%";
                                totalCompleteProbabilityStr.replaceAll(",", "");
                            }
                            
                            
                            entities.put(operatorId, values);
                        }
                        //userDateTotal.put(departments.get(i).getDepartmentId(), totalTargetValueStr + "-" + totalCompleteValueStr + "-" + totalCompleteProbabilityStr);
                        }
                    
                    
                }
                //下面开始计算
                    String targetDate = "";
                    // 我要对上述的集合做求和的处理

                    List<Target> list = new ArrayList<Target>();
                    Iterator entitiesIterator = entities.entrySet().iterator();
                    while (entitiesIterator.hasNext()) {
                        Map.Entry entry = (Entry) entitiesIterator.next();
                        Long name = (Long) entry.getKey();
                        Map<String, String> valMap = (Map<String, String>) entry.getValue();
                        System.out.println(name + " " + valMap.toString());
                        Iterator values_iter = valMap.entrySet().iterator();
                        String keydateString = "";
                        String vvvString = "";
                        while (values_iter.hasNext()) {
                            Map.Entry entryvaEntry = (Map.Entry) values_iter.next();// 得到map中的每一条的数据
                            keydateString = (String) entryvaEntry.getKey();
                            vvvString = (String) entryvaEntry.getValue();
                            // 在这个地方我需要处理的就是把这些数据存到ArrayList中
                            Target target = new Target();
                            target.setKetDate(keydateString);
                            target.setValue(vvvString);
                            list.add(target);

                        }

                    }
                    System.out.println(list.size());
                ////遍历values中的值计算总的和就可以了。
                    double sum1 = 0;
                    double sum2 = 0;
                    double sum3 = 0;
                    String str_totalCompleteValueStr = "0";
                    String str_totalTargetValueStr = "0";
                    String str_totalCompleteProbabilityStr = "0%";
                    for (int k = 0;k<list.size();k++) {
                        final Target target = list.get(k);
                        String[] values = target.getValue().split("-");
                        sum1 += Double.parseDouble(values[0].replace(",", ""));
                        sum2 += Double.parseDouble(values[1].replace(",",""));
                        sum3 += Double.parseDouble(values[2].substring(0, values[2].length() - 1));
                        if (sum2 != 0){
                                str_totalCompleteValueStr = TextUtil.doubleToText(sum2, 2);
                        }
                        if (sum1 != 0){
                                str_totalTargetValueStr = TextUtil.doubleToText(sum1, 2);
                        }
                        if (sum3 != 0){
                                str_totalCompleteProbabilityStr = TextUtil.doubleToText(sum3*100, 0)+"%";
                                str_totalCompleteProbabilityStr.replaceAll(",", "");
                        }
                        
                        userDateTotal.put(departments.get(i).getDepartmentId(), str_totalTargetValueStr + "-" + str_totalCompleteValueStr + "-" + str_totalCompleteProbabilityStr);
                    }
                
                    Map<String, String> map = new HashMap<String,String>();
                    //计算每个月的和返回一个map
                    for (int year = startYear; year <= endYear; year++){
                        int startMonthOfYear = 1;
                        int endMonthOfYear = 12;
                        if (year == startYear){
                            startMonthOfYear = startMonth;
                        }
                        if (year == endYear){
                            endMonthOfYear = endMonth;
                        }
                    for (int month = startMonthOfYear; month <= endMonthOfYear; month++) {
                        targetDate = year + "-"
                                + (month > 0 && month < 10 ? "0" + month : month);
                        
                        
                         map.putAll(CalReturn(list, targetDate));
                        
                        
                    }
                    }
                    //这个就是得到每个月的消费的记录的和.这个就是得到的就是这个部门下的所有的用户在每个月的销售目标的总的和
                     dateentities.put(departments.get(i).getDepartmentId(), map);
                    
            }
            if (departments.get(i).getDepartmentName().equals(key5)) {
                String bianhaoString = departments.get(i).getDepartmentId()+"-"+key5;
                departmtntAndIDString.add(bianhaoString);
                //大区五中所有的用户
                speacialoperators = getOperatorByDepartmentId(departments.get(i).getDepartmentId());
                
                
                 if (speacialoperators != null && speacialoperators.size() > 0){
                    entities = new LinkedHashMap<Long, Map<String, String>>();
                    userTotalTargetValue = new LinkedHashMap<Long, String>();
                    
                   String totalCompleteValueStr = "0";
                String totalTargetValueStr = "0";
                String totalCompleteProbabilityStr = "0%";
                    for (Operator operator : speacialoperators){
                        Map<String, String> values = new HashMap<String, String>();
                        long operatorId = operator.getOperatorId();
                        StringBuffer operatorSql = new StringBuffer();
                        operatorSql.append(sql.toString());
                        if (saleIndex.equals("amount")){
                            operatorSql.append(" and opportunity.ownerId = " + operatorId + " ");
                        } else {
                            operatorSql.append(" and customer.ownerId = " + operatorId + " ");
                        }
                        
                        
                        double totalCompleteValue = 0;
                        double totalTargetValue = 0;
                        double totalCompleteProbability = 0;
                        
                        for (int year = startYear; year <= endYear; year++){
                            //定义三个变量用来计算这个部门中所有的用户的总的总和
                            double total_totalCompleteValue = 0;
                           double total_totalTargetValue = 0;
                           double total_totalCompleteProbability = 0;
                            int startMonthOfYear = 1;
                            int endMonthOfYear = 12;
                            if (year == startYear){
                                startMonthOfYear = startMonth;
                            }
                            if (year == endYear){
                                endMonthOfYear = endMonth;
                            }
                            for (int month = startMonthOfYear; month <= endMonthOfYear; month++){
                                String targetDate = year + "-" + (month > 0 && month < 10 ? "0" + month : month);
                                double completeValue = 0;
                                double targetValue = 0;
                                double completeProbability = 0;
                                StringBuffer dateSql = new StringBuffer();
                                dateSql.append(operatorSql.toString());
                                if (saleIndex.equals("amount")){                            
                                    dateSql.append(" and year(opportunity.completeDate) = " + year + " and month(opportunity.completeDate) = " + month);
                                } else {
                                    dateSql.append(" and year(customer.createDate) = " + year + " and month(customer.createDate) = " + month);
                                }
                                
                                Object value = OpportunityLocalServiceUtil.searchByQueryStringOfSaleFunnel(dateSql.toString());
                                if (value == null){
                                    value = 0;
                                }
                                completeValue = Double.valueOf(value.toString());
                                //根据用户的id和销售日期查找某一个人的在某一个月的销售目标。
                                SalesTarget salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operatorId, targetDate);
                                if (salesTarget != null){
                                    if (saleIndex.equals("num")){
                                        targetValue = salesTarget.getSalesNum();
                                    } else {
                                        targetValue = salesTarget.getSalesAmount();
                                    }
                                }
                                if (completeValue != 0 && targetValue != 0){
                                    completeProbability = completeValue/targetValue;
                                }
                                totalCompleteValue += completeValue;
                                totalTargetValue += targetValue;
                                //求和
                                total_totalTargetValue += totalTargetValue;
                                total_totalCompleteValue += totalCompleteValue;
                                
                                String completeValueStr = "0";
                                String targetValueStr = "0";
                                String completeProbabilityStr = "0%";
                                if (saleIndex.equals("num")){
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 0);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 0);                                
                                    }
                                } else {
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 2);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 2);
                                    }
                                }
                                if (completeProbability != 0){
                                    completeProbabilityStr = TextUtil.doubleToText(completeProbability*100, 0)+"%";
                                    completeProbabilityStr.replaceAll(",", "");
                                }
                                values.put(targetDate, targetValueStr + "-" + completeValueStr + "-" + completeProbabilityStr);
                                
                                
                            }
                            if (totalCompleteValue != 0 && totalTargetValue != 0){
                                totalCompleteProbability = totalCompleteValue/totalTargetValue;
                                total_totalCompleteProbability += totalCompleteProbability;
                            }
                            if (totalCompleteValue != 0){
                                totalCompleteValueStr = TextUtil.doubleToText(total_totalCompleteValue, 2);
                            }
                            if (totalTargetValue != 0){
                                totalTargetValueStr = TextUtil.doubleToText(total_totalTargetValue, 2);
                            }
                            if (totalCompleteProbability != 0){
                                totalCompleteProbabilityStr = TextUtil.doubleToText(total_totalCompleteProbability*100, 0)+"%";
                                totalCompleteProbabilityStr.replaceAll(",", "");
                            }
                            
                            entities.put(operatorId, values);
                        }
                        //求的总的总和
                        //userDateTotal.put(departments.get(i).getDepartmentId(), totalTargetValueStr + "-" + totalCompleteValueStr + "-" + totalCompleteProbabilityStr);
                        }
                    
                        
                }
                //下面开始计算
                    String targetDate = "";
                    // 我要对上述的集合做求和的处理

                    List<Target> list = new ArrayList<Target>();
                    Iterator entitiesIterator = entities.entrySet().iterator();
                    while (entitiesIterator.hasNext()) {
                        Map.Entry entry = (Entry) entitiesIterator.next();
                        Long name = (Long) entry.getKey();
                        Map<String, String> valMap = (Map<String, String>) entry.getValue();
                        System.out.println(name + " " + valMap.toString());
                        Iterator values_iter = valMap.entrySet().iterator();
                        String keydateString = "";
                        String vvvString = "";
                        while (values_iter.hasNext()) {
                            Map.Entry entryvaEntry = (Map.Entry) values_iter.next();// 得到map中的每一条的数据
                            keydateString = (String) entryvaEntry.getKey();
                            vvvString = (String) entryvaEntry.getValue();
                            // 在这个地方我需要处理的就是把这些数据存到ArrayList中
                            Target target = new Target();
                            target.setKetDate(keydateString);
                            target.setValue(vvvString);
                            list.add(target);

                        }

                    }
                    System.out.println(list.size());
                ////遍历values中的值计算总的和就可以了。
                    double sum1 = 0;
                    double sum2 = 0;
                    double sum3 = 0;
                    String str_totalCompleteValueStr = "0";
                    String str_totalTargetValueStr = "0";
                    String str_totalCompleteProbabilityStr = "0%";
                    for (int k = 0;k<list.size();k++) {
                        final Target target = list.get(k);
                        String[] values = target.getValue().split("-");
                        sum1 += Double.parseDouble(values[0].replace(",", ""));
                        sum2 += Double.parseDouble(values[1].replace(",",""));
                        sum3 += Double.parseDouble(values[2].substring(0, values[2].length() - 1));
                        if (sum2 != 0){
                                str_totalCompleteValueStr = TextUtil.doubleToText(sum2, 2);
                        }
                        if (sum1 != 0){
                                str_totalTargetValueStr = TextUtil.doubleToText(sum1, 2);
                        }
                        if (sum3 != 0){
                                str_totalCompleteProbabilityStr = TextUtil.doubleToText(sum3*100, 0)+"%";
                                str_totalCompleteProbabilityStr.replaceAll(",", "");
                        }
                        
                        userDateTotal.put(departments.get(i).getDepartmentId(), str_totalTargetValueStr + "-" + str_totalCompleteValueStr + "-" + str_totalCompleteProbabilityStr);
                    }
                
                    Map<String, String> map = new HashMap<String,String>();
                    //计算每个月的和返回一个map
                    for (int year = startYear; year <= endYear; year++){
                        int startMonthOfYear = 1;
                        int endMonthOfYear = 12;
                        if (year == startYear){
                            startMonthOfYear = startMonth;
                        }
                        if (year == endYear){
                            endMonthOfYear = endMonth;
                        }
                    for (int month = startMonthOfYear; month <= endMonthOfYear; month++) {
                        targetDate = year + "-"
                                + (month > 0 && month < 10 ? "0" + month : month);
                        
                        
                         map.putAll(CalReturn(list, targetDate));
                        
                        
                    }
                    }
                    //这个就是得到每个月的消费的记录的和.这个就是得到的就是这个部门下的所有的用户在每个月的销售目标的总的和
                     dateentities.put(departments.get(i).getDepartmentId(), map);
                    
            }
            if (departments.get(i).getDepartmentName().equals(key6)) {
                String bianhaoString = departments.get(i).getDepartmentId()+"-"+key6;
                departmtntAndIDString.add(bianhaoString);
                //大区六中所有的用户
                speacialoperators = getOperatorByDepartmentId(departments.get(i).getDepartmentId());
                
                 if (speacialoperators != null && speacialoperators.size() > 0){
                    entities = new LinkedHashMap<Long, Map<String, String>>();
                    userTotalTargetValue = new LinkedHashMap<Long, String>();
                    
                   String totalCompleteValueStr = "0";
                String totalTargetValueStr = "0";
                String totalCompleteProbabilityStr = "0%";
                    for (Operator operator : speacialoperators){
                        Map<String, String> values = new HashMap<String, String>();
                        long operatorId = operator.getOperatorId();
                        StringBuffer operatorSql = new StringBuffer();
                        operatorSql.append(sql.toString());
                        if (saleIndex.equals("amount")){
                            operatorSql.append(" and opportunity.ownerId = " + operatorId + " ");
                        } else {
                            operatorSql.append(" and customer.ownerId = " + operatorId + " ");
                        }
                        
                        
                        double totalCompleteValue = 0;
                        double totalTargetValue = 0;
                        double totalCompleteProbability = 0;
                        
                        for (int year = startYear; year <= endYear; year++){
                            //定义三个变量用来计算这个部门中所有的用户的总的总和
                            double total_totalCompleteValue = 0;
                           double total_totalTargetValue = 0;
                           double total_totalCompleteProbability = 0;
                            int startMonthOfYear = 1;
                            int endMonthOfYear = 12;
                            if (year == startYear){
                                startMonthOfYear = startMonth;
                            }
                            if (year == endYear){
                                endMonthOfYear = endMonth;
                            }
                            for (int month = startMonthOfYear; month <= endMonthOfYear; month++){
                                String targetDate = year + "-" + (month > 0 && month < 10 ? "0" + month : month);
                                double completeValue = 0;
                                double targetValue = 0;
                                double completeProbability = 0;
                                StringBuffer dateSql = new StringBuffer();
                                dateSql.append(operatorSql.toString());
                                if (saleIndex.equals("amount")){                            
                                    dateSql.append(" and year(opportunity.completeDate) = " + year + " and month(opportunity.completeDate) = " + month);
                                } else {
                                    dateSql.append(" and year(customer.createDate) = " + year + " and month(customer.createDate) = " + month);
                                }
                                
                                Object value = OpportunityLocalServiceUtil.searchByQueryStringOfSaleFunnel(dateSql.toString());
                                if (value == null){
                                    value = 0;
                                }
                                completeValue = Double.valueOf(value.toString());
                                //根据用户的id和销售日期查找某一个人的在某一个月的销售目标。
                                SalesTarget salesTarget = SalesTargetLocalServiceUtil.searchByUserIdAndTargetDate(companyId, operatorId, targetDate);
                                if (salesTarget != null){
                                    if (saleIndex.equals("num")){
                                        targetValue = salesTarget.getSalesNum();
                                    } else {
                                        targetValue = salesTarget.getSalesAmount();
                                    }
                                }
                                if (completeValue != 0 && targetValue != 0){
                                    completeProbability = completeValue/targetValue;
                                }
                                totalCompleteValue += completeValue;
                                totalTargetValue += targetValue;
                                //求和
                                total_totalTargetValue += totalTargetValue;
                                total_totalCompleteValue += totalCompleteValue;
                                
                                String completeValueStr = "0";
                                String targetValueStr = "0";
                                String completeProbabilityStr = "0%";
                                if (saleIndex.equals("num")){
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 0);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 0);                                
                                    }
                                } else {
                                    if (completeValue != 0){
                                        completeValueStr = TextUtil.doubleToText(completeValue, 2);
                                    }
                                    if (targetValue != 0){
                                        targetValueStr = TextUtil.doubleToText(targetValue, 2);
                                    }
                                }
                                if (completeProbability != 0){
                                    completeProbabilityStr = TextUtil.doubleToText(completeProbability*100, 0)+"%";
                                    completeProbabilityStr.replaceAll(",", "");
                                }
                                values.put(targetDate, targetValueStr + "-" + completeValueStr + "-" + completeProbabilityStr);
                                
                                
                            }
                            if (totalCompleteValue != 0 && totalTargetValue != 0){
                                totalCompleteProbability = totalCompleteValue/totalTargetValue;
                                total_totalCompleteProbability += totalCompleteProbability;
                            }
                            if (totalCompleteValue != 0){
                                totalCompleteValueStr = TextUtil.doubleToText(total_totalCompleteValue, 2);
                            }
                            if (totalTargetValue != 0){
                                totalTargetValueStr = TextUtil.doubleToText(total_totalTargetValue, 2);
                            }
                            if (totalCompleteProbability != 0){
                                totalCompleteProbabilityStr = TextUtil.doubleToText(total_totalCompleteProbability*100, 0)+"%";
                                totalCompleteProbabilityStr.replaceAll(",", "");
                            }
                            
                            entities.put(operatorId, values);
                        }
                        //userDateTotal.put(departments.get(i).getDepartmentId(), totalTargetValueStr + "-" + totalCompleteValueStr + "-" + totalCompleteProbabilityStr);
                    }
                    
                        
                }
                
                   
                    // 我要对上述的集合做求和的处理

                    List<Target> list = new ArrayList<Target>();
                    Iterator entitiesIterator = entities.entrySet().iterator();
                    while (entitiesIterator.hasNext()) {
                        Map.Entry entry = (Entry) entitiesIterator.next();
                        Long name = (Long) entry.getKey();
                        Map<String, String> valMap = (Map<String, String>) entry.getValue();
                        System.out.println(name + " " + valMap.toString());
                        Iterator values_iter = valMap.entrySet().iterator();
                        String keydateString = "";
                        String vvvString = "";
                        while (values_iter.hasNext()) {
                            Map.Entry entryvaEntry = (Map.Entry) values_iter.next();// 得到map中的每一条的数据
                            keydateString = (String) entryvaEntry.getKey();
                            vvvString = (String) entryvaEntry.getValue();
                            // 在这个地方我需要处理的就是把这些数据存到ArrayList中
                            Target target = new Target();
                            target.setKetDate(keydateString);
                            target.setValue(vvvString);
                            list.add(target);

                        }

                    }
                    System.out.println("................size="+list.size());
                ////遍历values中的值计算总的和就可以了。
                    double sum1 = 0;
                    double sum2 = 0;
                    double sum3 = 0;
                    String str_totalCompleteValueStr = "0";
                    String str_totalTargetValueStr = "0";
                    String str_totalCompleteProbabilityStr = "0%";
                    for (int k = 0;k<list.size();k++) {
                        final Target target = list.get(k);
                        String[] values = target.getValue().split("-");
                        sum1 += Double.parseDouble(values[0].replace(",", ""));
                        sum2 += Double.parseDouble(values[1].replace(",",""));
                        sum3 += Double.parseDouble(values[2].substring(0, values[2].length() - 1));
                        if (sum2 != 0){
                                str_totalCompleteValueStr = TextUtil.doubleToText(sum2, 2);
                        }
                        if (sum1 != 0){
                                str_totalTargetValueStr = TextUtil.doubleToText(sum1, 2);
                        }
                        if (sum3 != 0){
                                str_totalCompleteProbabilityStr = TextUtil.doubleToText(sum3*100, 0)+"%";
                                str_totalCompleteProbabilityStr.replaceAll(",", "");
                        }
                        
                        userDateTotal.put(departments.get(i).getDepartmentId(), str_totalTargetValueStr + "-" + str_totalCompleteValueStr + "-" + str_totalCompleteProbabilityStr);
                    }
                
                    Map<String, String> map = new HashMap<String,String>();
                    //计算每个月的和返回一个map
                    for (int year = startYear; year <= endYear; year++){
                        int startMonthOfYear = 1;
                        int endMonthOfYear = 12;
                        if (year == startYear){
                            startMonthOfYear = startMonth;
                        }
                        if (year == endYear){
                            endMonthOfYear = endMonth;
                        }
                    for (int month = startMonthOfYear; month <= endMonthOfYear; month++) {
                        String targetDate = year + "-"
                                + (month > 0 && month < 10 ? "0" + month : month);
                        
                        
                         map.putAll(CalReturn(list, targetDate));
                        
                        
                        
                    }
                    }
                 //这个就是得到每个月的消费的记录的和.这个就是得到的就是这个部门下的所有的用户在每个月的销售目标的总的和
                    dateentities.put(departments.get(i).getDepartmentId(), map);
                    
                    
            }
        }
       
        //输出数据
        _log.info("==========================="+dateentities.toString());
        _log.info("==========================="+userDateTotal.toString());
        
        _log.info("==========================="+userRange);
        _log.info("==========================="+saleIndex);
        
        _log.info("==========================="+startYear);
        _log.info("==========================="+startMonth);
            
        _log.info("==========================="+endYear);
        _log.info("==========================="+endMonth);
        
        portletRequest.setAttribute("dateentities", dateentities);
        portletRequest.setAttribute("userDateTotal", userDateTotal);
        portletRequest.setAttribute("userRange", userRange);
        portletRequest.setAttribute("saleIndex", saleIndex);
        portletRequest.setAttribute("startYear", startYear);
        portletRequest.setAttribute("startMonth", startMonth);
        portletRequest.setAttribute("endYear", endYear);
        portletRequest.setAttribute("endMonth", endMonth);
        
        portletRequest.setAttribute("departmtntAndIDString", departmtntAndIDString);
        
        
        
        
    }
    
    //////////////////////////////////////////////////////////////////////////////////
    
    



//计算之后就返回一个map
private static Map<String, String> CalReturn(List<Target> list, String date){
    Map<String, String> mapvaMap = new HashMap<String, String>();
    double total_targetValue = 0;
    double total_completeValue = 0;
    double total_completeProbability = 0;
    
    String totalCompleteValueStr = "0";
    String totalTargetValueStr = "0";
    String totalCompleteProbabilityStr = "0%";
    
    for (int i = 0; i < list.size(); i++) {
        Target target = list.get(i);// 得到每一条的数据
        if (target.getKetDate().equals(date)) {// 如果日期相同的话就求和

            String[] vvss = target.getValue().split("-");

            total_targetValue += Double.parseDouble(vvss[0]
                    .replace(",", ""));
            total_completeValue += Double.parseDouble(vvss[1].replace(",",
                    ""));
            total_completeProbability += Double.parseDouble(vvss[2]
                    .substring(0, vvss[2].length() - 1));
            
            
            
            if (total_completeValue != 0){
                totalCompleteValueStr = TextUtil.doubleToText(total_completeValue, 2);
            }
            if (total_targetValue != 0){
                totalTargetValueStr = TextUtil.doubleToText(total_targetValue, 2);
            }
            if (total_completeProbability != 0){
                totalCompleteProbabilityStr = TextUtil.doubleToText(total_completeProbability*100, 0)+"%";
                totalCompleteProbabilityStr.replaceAll(",", "");
            }
            
            mapvaMap.put(target.getKetDate(), totalTargetValueStr+"-"
                    + totalCompleteValueStr+"-"+ totalCompleteProbabilityStr);
            
        }

    }
    
    return mapvaMap;
    
}

    private static Log _log = LogFactoryUtil.getLog(SaleTargetPortlet.class);

    
}

原文地址:https://www.cnblogs.com/airycode/p/4988849.html