package com.house365.web.controller;

import com.beust.jcommander.internal.Lists;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.po.BarComparePo;
import com.house365.beans.po.BarPo;
import com.house365.beans.po.ProjectSrouceParaPo;
import com.house365.beans.po.ProjectSrouceRePo;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.beans.vo.LocalReportFormVo;
import com.house365.beans.vo.ReportMarketingFormVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.*;
import com.house365.web.util.Constant.CustomerStatusEnum;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.*;
import com.house365.ws.interfaces.server.*;
import com.house365.ws.system.House365SearchResponse;
import net.sf.json.JSONArray;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 状态来源分析 statusSourceStatistic
 * 项目来源分析 projectSource
 * 客户分析 customerStatistic
 * 客户转化分析 customerTransStatistic
 * 项目转化分析 projectTransform
 *
 * @author house365
 */

@Controller
@RequestMapping("/statistic")
public class StatisticController extends BaseController {

    private final static String[] projectTranExcelTitles = {"转化率", "约看", "到访", "认筹", "认购", "签约", "退房"};
    private final static String[] projectSourExcelTitles = {"城市", "客户状态", "项目", "来源", "日期", "客户数量", "环比"};

    private static final String CITY_CODE = "cityCode";

    private Logger LOGGER = LoggerFactory.getLogger(StatisticController.class);

    @Autowired
    private IProject project;
    @Autowired
    private IUser user;
    @Autowired
    private ICustomerStatusLog customerStatusLog;
    @Autowired
    private IProjectSourceStatistics projectSourceStatistics;
    @Autowired
    private IDeptSourceStatistics deptSourceStatistics;
    @Autowired
    private IUserSourceStatistics userSourceStatistics;
    @Autowired
    private IStatusSourceStatistics statusSourceStatistics;
    @Autowired
    private IDepartment department;
    @Autowired
    private IReportChannel reportChannel;
    @Autowired
    private ILocalReport localReportService;
    @Autowired
    private IReportMarketing reportMarketingService;
    @Autowired
    private ICityDepConfig cityDepConfig;

    @Autowired
    private IExportExcelInterface anInterface;
    @Autowired
    private ICustomerProject customerProject;
    @Autowired
    private ICloudActivityInterface activityInterface;

    @SuppressWarnings("deprecation")
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyww");
        Calendar c = Calendar.getInstance();
        c.setMinimalDaysInFirstWeek(7);
        int i = c.get(Calendar.WEEK_OF_YEAR);
        System.out.println(i);
        sdf.setCalendar(c);
        System.out.println(sdf.format(c.getTime()));
    }

    /**
     * 状态来源分析
     * 根据查询条件，查询所选条件下全部项目的客户数量，并根据来源列举
     *
     * @param number
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "statusSourceStatistic")
    public String statusSourceStatistic(
            Integer number, Model model, HttpServletRequest request
    ) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);

        DepartmentEntity city = null;
        String cityId = dept.getCityID();

        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        city = departmentResponse.getEntity();

        String urlPath = "";
        if (userEntity.getDeptId() == 1) {
            urlPath = city.getUrlPath();
        } else {
            urlPath = userEntity.getDeptUrlPath() + "/";
        }

        String status = request.getParameter("status");
        String dateViewType = request.getParameter("dateViewType");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String displayTab = Strings.isNullOrEmpty(request.getParameter("displayTab")) ? "1" : request.getParameter(
                "displayTab");

        //设置显示tab
        model.addAttribute("displayTab", displayTab);

        Page queryPage = new Page(30);
        if (null != number) {
            queryPage.setCurrentPage(number);
        }
        QueryParams queryParams = new QueryParams();
        queryParams.setPaging(queryPage);
        Map<String, Object> queryMap = new HashMap<>();

        if (!Strings.isNullOrEmpty(status)) {
            queryMap.put("EQ_customerStatus", status);
        }

        if (!Strings.isNullOrEmpty(city.getName())) {
            queryMap.put("EQ_cityName", city.getName());
        }

        String yAxis = "";
        String reportData = "'未约看','约看','到访','认筹','认购','签约','退房'";
        List<String> statusList = Lists.newArrayList("未约看", "约看", "到访", "认筹", "认购", "签约", "退房");
        model.addAttribute("report_data", reportData);
        model.addAttribute("yAxis_data", yAxis);
        model.addAttribute("viewList", JSONArray.fromObject(new LinkedList<BarPo>()));

        //根据状态来源数量设置报表显示高度
        String divHeight = "650px";
        if (Strings.isNullOrEmpty(dateViewType)) {
            model.addAttribute("divLength", divHeight);
            model.addAttribute("page", queryPage);
            return getAutoUrl();
        }

        // 处理日期查询条件
        setQueryDate(dateViewType, startTime, endTime, queryMap, model);

        // 按部门分析或按职员分析
        SourceStatisticsListResponse pssr = null;
        StatusSourceStatisticsListRequest pssl = new StatusSourceStatisticsListRequest();
        pssl.setPaging(queryPage);
        pssl.setSearchParams(queryMap);
        pssl.setOrderColumn("cityname asc ");
        pssl.setOrderMode(" ,customerStatus asc,sourcename asc,createTime desc");
        // 导出用
        request.getSession().setAttribute("statisticType", "1");
        request.getSession().setAttribute("statusSourceQueryRequest", pssl);
        request.getSession().setAttribute("dateViewType", dateViewType);

        //从汇总统计表查询数据，汇总统计表通过定时任务插入数据
        pssr = statusSourceStatistics.statusSourceStatistic(pssl, dateViewType);
        model.addAttribute("tableData", pssr.getObjectList());
        model.addAttribute("page", pssr.getPaging());

        // 报表数据，excel导出数据放入session，避免2次查询
        SourceStatisticsListResponse pssr1 = null;
        // 多于30条，导出数据需要查一次全量数据，否则直接使用本次查询结果
        if (pssr.getPaging().getRecords() > 30) {
            StatusSourceStatisticsListRequest pssl1 = (StatusSourceStatisticsListRequest) request.getSession().getAttribute(
                    "statusSourceQueryRequest");
            pssl1.getPaging().setPageSize(Integer.MAX_VALUE);
            pssl1.getPaging().setCurrentPage(1);
            pssr1 = statusSourceStatistics.statusSourceStatistic(pssl1, dateViewType);
        } else {
            pssr1 = pssr;
        }

        //设置y轴来源数据
        Set<String> sourceName = new HashSet<>();
        for (Map entity : pssr1.getObjectList()) {
            sourceName.add(String.valueOf(entity.get("sourcename")));
        }

        String ystr = "";
        for (String yaxis : sourceName) {
            ystr += "'" + yaxis + "',";
        }
        ystr = ystr.endsWith(",") ? ystr.substring(0, ystr.length() - 1) : ystr;

        if (pssr1 != null) {
            // 来源列表
            List<String> sourceList = Lists.newArrayList(sourceName);

            List<BarPo> resultList = new LinkedList<>();
            BarPo tmpMap;
            List<Long> tmpList;
            // 计算每个状态客户数量
            for (String status1 : statusList) {
                tmpMap = new BarPo();
                tmpMap.setName(status1);
                tmpMap.setType("bar");
                tmpMap.setBarMaxWidth(35);
                tmpMap.setBarMinHeight(10);
                tmpList = new LinkedList<Long>();
                Long[] seriesData = new Long[sourceList.size()];

                for (int ui = 0; ui < sourceList.size(); ui++) {
                    String un = sourceList.get(ui);
                    long cn = 0;
                    for (Map entity : pssr1.getObjectList()) {
                        String cStatus = String.valueOf(entity.get("customerStatus"));
                        if ("1".equalsIgnoreCase(cStatus)) {
                            cStatus = "约看";
                        } else if ("2".equalsIgnoreCase(cStatus)) {
                            cStatus = "到访";
                        } else if ("3".equalsIgnoreCase(cStatus)) {
                            cStatus = "认筹";
                        } else if ("4".equalsIgnoreCase(cStatus)) {
                            cStatus = "认购";
                        } else if ("5".equalsIgnoreCase(cStatus)) {
                            cStatus = "签约";
                        } else if ("6".equalsIgnoreCase(cStatus)) {
                            cStatus = "退房";
                        } else if ("0".equalsIgnoreCase(cStatus)) {
                            cStatus = "未约看";
                        }
                        if (status1.equalsIgnoreCase(cStatus) && un.equalsIgnoreCase(
                                String.valueOf(entity.get("sourcename")))) {
                            long tn = entity.get("customerNum") == null ? 0 : ((BigDecimal) entity.get(
                                    "customerNum")).longValue();
                            cn = (seriesData[ui] == null ? 0 : seriesData[ui]) + tn;
                            seriesData[ui] = cn;
                        }
                    }
                    seriesData[ui] = cn;
                }
                tmpMap.setData(Arrays.asList(seriesData));
                resultList.add(tmpMap);
            }

            // 每个来源所有状态和，排序用
            Long[] resort = new Long[sourceList.size()];
            for (int i = 0; i < resort.length; i++) {
                Long sourceSum = 0L;
                for (BarPo barPo : resultList) {
                    List<Long> sourceArray = barPo.getData();
                    sourceSum += sourceArray.get(i);
                }
                resort[i] = sourceSum;
            }

            for (BarPo barPo : resultList) {
                Long[] cloneResort = new Long[resort.length];
                for (int i = 0; i < resort.length; i++) {
                    cloneResort[i] = resort[i];
                }

                barPo.setData(Arrays.asList(resortSeries(cloneResort, barPo.getData())));
            }

            Long[] cloneResort = new Long[resort.length];
            for (int i = 0; i < resort.length; i++) {
                cloneResort[i] = resort[i];
            }
            String[] ysa = resortSeries(cloneResort, ystr.split(","));

            //Y 轴超过110个无法正常展示，暂时限制一下数量
            int threshold = 110;
            if (ysa.length > threshold) {
                ysa = Arrays.copyOfRange(ysa, ysa.length - threshold, ysa.length);

                for (BarPo barPo : resultList) {
                    barPo.setData(barPo.getData().subList(barPo.getData().size() - threshold, barPo.getData().size()));
                }
            }

            divHeight = ysa.length > 3 ? (ysa.length / 3 * 450 + "px") : "650px";

            model.addAttribute("yAxis_data", Joiner.on(",").join(ysa));
            model.addAttribute("divLength", divHeight);

            model.addAttribute("viewList", JSONArray.fromObject(resultList));
        }

        return getAutoUrl();
    }

    private String[] resortSeries(Long[] data, String[] needSort) {
        // 冒泡
        for (int i = 0; i < data.length - 1; i++) {
            for (int j = 0; j < data.length - i - 1; j++) {
                if (data[j] > data[j + 1]) {
                    String stmp = needSort[j];
                    needSort[j] = needSort[j + 1];
                    needSort[j + 1] = stmp;
                    Long tmp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = tmp;
                }
            }
        }
        return needSort;
    }

    private Long[] resortSeries(Long[] data, List<Long> needSortList) {
        Long[] needSort = (Long[]) needSortList.toArray(new Long[needSortList.size()]);

        // 冒泡
        for (int i = 0; i < data.length - 1; i++) {
            for (int j = 0; j < data.length - i - 1; j++) {
                if (data[j] > data[j + 1]) {
                    Long stmp = needSort[j];
                    needSort[j] = needSort[j + 1];
                    needSort[j + 1] = stmp;
                    Long tmp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = tmp;
                }
            }
        }
        return needSort;
    }

    /**
     * 客户分析
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "customerStatistic")
    public String customerStatistic(
            Integer number, Model model, HttpServletRequest request
    ) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);

        List<DepartmentEntity> departmentEntities = new ArrayList<>();
        List<UserEntity> userEntities = new ArrayList<>();

        DepartmentEntity city = null;
        String cityId = dept.getCityID();
        Map<String, Object> searchParams = new HashMap<>();

        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        city = departmentResponse.getEntity();

        String urlPath = "";
        if (userEntity.getDeptId() == 1) {
            urlPath = city.getUrlPath();
        } else {
            urlPath = userEntity.getDeptUrlPath() + "/";
        }

        DepartmentListRequest dlr = new DepartmentListRequest();
        Page dPage = new Page(Integer.MAX_VALUE);
        Map<String, Object> dmap = new HashMap<>();
        dmap.put("LIKE_urlPath", urlPath);
        dlr.setParamMap(dmap);
        dlr.setOrderColumn("id");
        dlr.setOrderMode("asc");
        dlr.setSearchParams(dmap);
        dlr.setPaging(dPage);
        departmentEntities = department.getDepartmentList(dlr).getObjectList();

        searchParams.put("LIKE_deptUrlPath", urlPath);
        Page page = new Page(Integer.MAX_VALUE);
        UserListRequest listRequest = new UserListRequest();
        listRequest.setPaging(page);
        listRequest.setOrderColumn("name");
        listRequest.setOrderMode("asc");
        listRequest.setSearchParams(searchParams);
        UserListResponse response = user.getUserList(listRequest);
        userEntities = response.getObjectList();

        String status = request.getParameter("status");
        String statisticType = request.getParameter("statisticType");
        String dateViewType = request.getParameter("dateViewType");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String[] department = request.getParameterValues("department");
        String[] user = request.getParameterValues("user");
        String departmentNames = request.getParameter("departmentNames");
        String userNames = request.getParameter("userNames");
        String displayTab = Strings.isNullOrEmpty(request.getParameter("displayTab")) ? "1" : request.getParameter(
                "displayTab");

        model.addAttribute("displayTab", displayTab);

        Page queryPage = new Page(30);
        if (null != number) {
            queryPage.setCurrentPage(number);
        }
        QueryParams queryParams = new QueryParams();
        queryParams.setPaging(queryPage);
        Map<String, Object> queryMap = new HashMap<>();

        if (!Strings.isNullOrEmpty(status)) {
            queryMap.put("EQ_customerStatus", status);
        }

        if (!Strings.isNullOrEmpty(city.getDescripition())) {
            queryMap.put("EQ_city", city.getDescripition());
        }

        // 设置页面多选框选中效果
        setPageSelectedFlag(departmentEntities, userEntities, department, user);

        model.addAttribute("departmentList", departmentEntities);
        model.addAttribute("userList", userEntities);

        String yAxis = "";
        String reportData = "'未约看','约看','到访','认筹','认购','签约','退房'";
        List<String> statusList = Lists.newArrayList("未约看", "约看", "到访", "认筹", "认购", "签约", "退房");
        model.addAttribute("report_data", reportData);
        model.addAttribute("yAxis_data", yAxis);
        model.addAttribute("viewList", JSONArray.fromObject(new LinkedList<BarPo>()));

        if (Strings.isNullOrEmpty(dateViewType)) {
            dateViewType = "1";
        }

        if (Strings.isNullOrEmpty(statisticType)) {
            model.addAttribute("page", queryPage);
            return getAutoUrl();
        }

        if ("1".equals(statisticType)) {
            queryMap.put("IN_projectIds", Lists.newArrayList(department));
        } else if ("2".equals(statisticType)) {
            queryMap.put("IN_projectIds", Lists.newArrayList(user));
        }
        // 处理日期查询条件
        setQueryDate(dateViewType, startTime, endTime, queryMap, model);

        // 1 按部门分析 2 按职员分析
        SourceStatisticsListResponse pssr = null;
        if ("1".equals(statisticType)) {
            DeptSourceStatisticsListRequest pssl = new DeptSourceStatisticsListRequest();
            pssl.setPaging(queryPage);
            pssl.setSearchParams(queryMap);
            pssl.setOrderColumn("projectName asc");
            pssl.setOrderMode(" ,customerStatus asc,createTime desc");

            // 导出用
            request.getSession().setAttribute("statisticType", statisticType);
            request.getSession().setAttribute("queryRequest", pssl);
            request.getSession().setAttribute("dateViewType", dateViewType);

            pssr = deptSourceStatistics.statisticCustomer(pssl, dateViewType);
            model.addAttribute("tableData", pssr.getObjectList());
            model.addAttribute("page", pssr.getPaging());
        } else if ("2".equals(statisticType)) {
            UserSourceStatisticsListRequest pssl = new UserSourceStatisticsListRequest();
            pssl.setPaging(queryPage);
            pssl.setSearchParams(queryMap);
            pssl.setOrderColumn("projectName asc");
            pssl.setOrderMode(" ,customerStatus asc,createTime desc");

            // 导出用
            request.getSession().setAttribute("statisticType", statisticType);
            request.getSession().setAttribute("queryRequest", pssl);
            request.getSession().setAttribute("dateViewType", dateViewType);

            pssr = userSourceStatistics.statisticCustomer(pssl, dateViewType);
            model.addAttribute("tableData", pssr.getObjectList());
            model.addAttribute("page", pssr.getPaging());
        }

        // 报表数据
        departmentNames = departmentNames.endsWith(",") ? departmentNames.substring(0,
                departmentNames.length() - 1) : departmentNames;
        departmentNames = departmentNames.startsWith(",") ? departmentNames.substring(1,
                departmentNames.length()) : departmentNames;
        userNames = userNames.endsWith(",") ? userNames.substring(0, userNames.length() - 1) : userNames;
        userNames = userNames.startsWith(",") ? userNames.substring(1, userNames.length()) : userNames;

        model.addAttribute("departmentNames", departmentNames);
        model.addAttribute("userNames", userNames);

        //1 by department , 2 by user
        SourceStatisticsListResponse pssr1 = null;
        if ("1".equals(statisticType)) {
            yAxis = departmentNames;
            if (pssr.getPaging().getRecords() > 30) {
                DeptSourceStatisticsListRequest pssl = (DeptSourceStatisticsListRequest) request.getSession().getAttribute(
                        "queryRequest");
                pssl.getPaging().setPageSize(Integer.MAX_VALUE);
                pssl.getPaging().setCurrentPage(1);
                pssr1 = deptSourceStatistics.statisticCustomer(pssl, dateViewType);
            } else {
                pssr1 = pssr;
            }

        } else if ("2".equals(statisticType)) {
            yAxis = userNames;
            if (pssr.getPaging().getRecords() > 30) {
                UserSourceStatisticsListRequest pssl = (UserSourceStatisticsListRequest) request.getSession().getAttribute(
                        "queryRequest");
                pssl.getPaging().setPageSize(Integer.MAX_VALUE);
                pssl.getPaging().setCurrentPage(1);
                pssr1 = userSourceStatistics.statisticCustomer(pssl, dateViewType);
            } else {
                pssr1 = pssr;
            }

        }

        String ystr = "";
        for (String yaxis : yAxis.split(",")) {
            ystr += "'" + yaxis + "',";
        }
        ystr = ystr.endsWith(",") ? ystr.substring(0, ystr.length() - 1) : ystr;
        String divHeight = "650px";
        if (pssr1 != null) {
            List<String> userList = Lists.newArrayList(yAxis.split(","));

            List<BarPo> resultList = new LinkedList<>();
            BarPo tmpMap;
            List<Long> tmpList;
            for (String status1 : statusList) {
                tmpMap = new BarPo();
                tmpMap.setName(status1);
                tmpMap.setType("bar");
                tmpMap.setBarMaxWidth(35);
                tmpList = new LinkedList<>();
                Long[] seriesData = new Long[userList.size()];
                for (int ui = 0; ui < userList.size(); ui++) {
                    String un = userList.get(ui);
                    long cn = 0;
                    for (Map entity : pssr1.getObjectList()) {
                        String cStatus = String.valueOf(entity.get("customerStatus"));
                        if ("1".equalsIgnoreCase(cStatus)) {
                            cStatus = "约看";
                        } else if ("2".equalsIgnoreCase(cStatus)) {
                            cStatus = "到访";
                        } else if ("3".equalsIgnoreCase(cStatus)) {
                            cStatus = "认筹";
                        } else if ("4".equalsIgnoreCase(cStatus)) {
                            cStatus = "认购";
                        } else if ("5".equalsIgnoreCase(cStatus)) {
                            cStatus = "签约";
                        } else if ("6".equalsIgnoreCase(cStatus)) {
                            cStatus = "退房";
                        } else if ("0".equalsIgnoreCase(cStatus)) {
                            cStatus = "未约看";
                        }
                        if (status1.equalsIgnoreCase(cStatus) && un.equalsIgnoreCase(
                                String.valueOf(entity.get("projectName")))) {
                            long tn = entity.get("customerNum") == null ? 0 : ((BigDecimal) entity.get(
                                    "customerNum")).longValue();
                            cn = (seriesData[ui] == null ? 0 : seriesData[ui]) + tn;
                            seriesData[ui] = cn;
                        }
                    }
                    seriesData[ui] = cn;
                }

                tmpMap.setData(Arrays.asList(seriesData));
                resultList.add(tmpMap);
            }

            // 每个来源所有状态和，排序用
            Long[] resort = new Long[userList.size()];
            for (int i = 0; i < resort.length; i++) {
                Long sourceSum = 0L;
                for (BarPo barPo : resultList) {
                    List<Long> sourceArray = barPo.getData();
                    sourceSum += sourceArray.get(i);
                }
                resort[i] = sourceSum;
            }

            for (BarPo barPo : resultList) {
                Long[] cloneResort = new Long[resort.length];
                for (int i = 0; i < resort.length; i++) {
                    cloneResort[i] = resort[i];
                }

                barPo.setData(Arrays.asList(resortSeries(cloneResort, barPo.getData())));
            }

            Long[] cloneResort = new Long[resort.length];
            for (int i = 0; i < resort.length; i++) {
                cloneResort[i] = resort[i];
            }
            String[] ysa = resortSeries(cloneResort, ystr.split(","));

            divHeight = ysa.length > 7 ? (ysa.length / 7 * 650 + "px") : "650px";

            model.addAttribute("yAxis_data", Joiner.on(",").join(ysa));

            model.addAttribute("viewList", JSONArray.fromObject(resultList));
        }

        model.addAttribute("divLength", divHeight);
        model.addAttribute("statisticType", statisticType);
        return getAutoUrl();
    }

    /**
     * 客户转化分析
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "customerTransStatistic")
    public String customerTransStatistic(
            Integer number, Model model, HttpServletRequest request
    ) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);

        List<DepartmentEntity> departmentEntities = new ArrayList<>();
        List<UserEntity> userEntities = new ArrayList<>();

        DepartmentEntity city = null;
        String cityId = dept.getCityID();
        Map<String, Object> searchParams = new HashMap<>();

        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        city = departmentResponse.getEntity();

        String urlPath = "";
        if (userEntity.getDeptId() == 1) {
            urlPath = city.getUrlPath();
        } else {
            urlPath = userEntity.getDeptUrlPath() + "/";
        }

        DepartmentListRequest dlr = new DepartmentListRequest();
        Page dPage = new Page(Integer.MAX_VALUE);
        Map<String, Object> dmap = new HashMap<>();
        dmap.put("LIKE_urlPath", urlPath);
        dlr.setOrderColumn("id");
        dlr.setOrderMode("asc");
        dlr.setSearchParams(dmap);
        dlr.setPaging(dPage);
        departmentEntities = department.getDepartmentList(dlr).getObjectList();

        searchParams.put("LIKE_deptUrlPath", urlPath);
        Page page = new Page(Integer.MAX_VALUE);
        UserListRequest listRequest = new UserListRequest();
        listRequest.setPaging(page);
        listRequest.setOrderColumn("name");
        listRequest.setOrderMode("asc");
        listRequest.setSearchParams(searchParams);
        UserListResponse response = user.getUserList(listRequest);
        userEntities = response.getObjectList();

        String status = request.getParameter("status");
        String statisticType = request.getParameter("statisticType");
        String dateViewType = request.getParameter("dateViewType");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String[] department = request.getParameterValues("department");
        String[] user = request.getParameterValues("user");

        Page queryPage = new Page(Integer.MAX_VALUE);
        if (null != number) {
            queryPage.setCurrentPage(number);
        }
        QueryParams queryParams = new QueryParams();
        queryParams.setPaging(queryPage);
        Map<String, Object> queryMap = new HashMap<>();

        if (!Strings.isNullOrEmpty(status)) {
            queryMap.put("EQ_customerStatus", status);
        }

        if (!Strings.isNullOrEmpty(city.getName())) {
            queryMap.put("EQ_cityName", city.getName());
        }

        // 设置页面多选框选中效果
        setPageSelectedFlag(departmentEntities, userEntities, department, user);

        model.addAttribute("departmentList", departmentEntities);
        model.addAttribute("userList", userEntities);

        List<String> statusList = Lists.newArrayList("未约看", "约看", "到访", "认筹", "认购", "签约", "退房");

        if (Strings.isNullOrEmpty(dateViewType)) {
            dateViewType = "1";
        }

        if (Strings.isNullOrEmpty(statisticType)) {
            model.addAttribute("page", queryPage);
            return getAutoUrl();
        }

        if ("1".equals(statisticType)) {
            queryMap.put("IN_projectIds", Lists.newArrayList(department));
        } else if ("2".equals(statisticType)) {
            queryMap.put("IN_projectIds", Lists.newArrayList(user));
        }

        // 处理日期查询条件
        setQueryDate(dateViewType, startTime, endTime, queryMap, model);

        // 按部门分析或按职员分析
        SourceStatisticsListResponse pssr = null;
        if ("1".equals(statisticType)) {
            DeptSourceStatisticsListRequest pssl = new DeptSourceStatisticsListRequest();
            pssl.setPaging(queryPage);
            pssl.setSearchParams(queryMap);
            pssl.setOrderColumn("projectName asc");
            pssl.setOrderMode(" ,customerStatus asc,createTime desc");

            // 导出用
            request.getSession().setAttribute("statisticType", statisticType);
            request.getSession().setAttribute("queryRequest", pssl);
            request.getSession().setAttribute("dateViewType", dateViewType);

            pssr = deptSourceStatistics.customerTrans(pssl, dateViewType);

            BigDecimal status1 = BigDecimal.ZERO;
            BigDecimal status2 = BigDecimal.ZERO;
            BigDecimal status3 = BigDecimal.ZERO;
            BigDecimal status4 = BigDecimal.ZERO;
            BigDecimal status5 = BigDecimal.ZERO;
            BigDecimal status6 = BigDecimal.ZERO;
            List<Map> ml = pssr.getObjectList();
            if (ml != null) {
                for (Map map : ml) {
                    if (map.containsKey("customerStatus") && "1".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status1 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "2".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status2 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "3".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status3 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "4".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status4 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "5".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status5 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "6".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status6 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                }
            }

            BigDecimal[] stat = {status1, status2, status3, status4, status5, status6};

            List<List<String>> tableData = new ArrayList<>();
            for (int i = 1; i <= 6; i++) {
                List<String> rowData = new ArrayList<>();
                if (1 == i) {
                    rowData.add("约看");
                } else if (2 == i) {
                    rowData.add("到访");
                } else if (3 == i) {
                    rowData.add("认筹");
                } else if (4 == i) {
                    rowData.add("认购");
                } else if (5 == i) {
                    rowData.add("签约");
                } else if (6 == i) {
                    rowData.add("退房");
                } else if (0 == i) {
                    rowData.add("未约看");
                }

                for (int j = 1; j <= 6; j++) {
                    if (j > i) {
                        BigDecimal divide = stat[j - 1];
                        BigDecimal divided = stat[i - 1];
                        if (divided.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal res = divide.divide(divided, 4, BigDecimal.ROUND_UP).multiply(
                                    new BigDecimal(100)).setScale(2);
                            rowData.add("" + res + "%");
                        } else {
                            rowData.add("-");
                        }
                    } else {
                        rowData.add("-");
                    }
                }

                tableData.add(rowData);
            }

            request.getSession().setAttribute("transCustomerData", tableData);
            model.addAttribute("tableData", tableData);
            model.addAttribute("page", pssr.getPaging());
        } else if ("2".equals(statisticType)) {
            UserSourceStatisticsListRequest pssl = new UserSourceStatisticsListRequest();
            pssl.setPaging(queryPage);
            pssl.setSearchParams(queryMap);
            pssl.setOrderColumn("projectName asc");
            pssl.setOrderMode(" ,customerStatus asc,createTime desc");

            // 导出用
            request.getSession().setAttribute("statisticType", statisticType);
            request.getSession().setAttribute("queryRequest", pssl);
            request.getSession().setAttribute("dateViewType", dateViewType);

            pssr = userSourceStatistics.customerTrans(pssl, dateViewType);

            BigDecimal status1 = BigDecimal.ZERO;
            BigDecimal status2 = BigDecimal.ZERO;
            BigDecimal status3 = BigDecimal.ZERO;
            BigDecimal status4 = BigDecimal.ZERO;
            BigDecimal status5 = BigDecimal.ZERO;
            BigDecimal status6 = BigDecimal.ZERO;
            List<Map> ml = pssr.getObjectList();
            if (ml != null) {
                for (Map map : ml) {
                    if (map.containsKey("customerStatus") && "1".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status1 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "2".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status2 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "3".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status3 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "4".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status4 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "5".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status5 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                    if (map.containsKey("customerStatus") && "6".equalsIgnoreCase(
                            String.valueOf(map.get("customerStatus")))) {
                        status6 = new BigDecimal(String.valueOf(map.get("customerNum")));
                    }
                }
            }

            BigDecimal[] stat = {status1, status2, status3, status4, status5, status6};

            List<List<String>> tableData = new ArrayList<>();
            for (int i = 1; i <= 6; i++) {
                List<String> rowData = new ArrayList<>();
                if (1 == i) {
                    rowData.add("约看");
                } else if (2 == i) {
                    rowData.add("到访");
                } else if (3 == i) {
                    rowData.add("认筹");
                } else if (4 == i) {
                    rowData.add("认购");
                } else if (5 == i) {
                    rowData.add("签约");
                } else if (6 == i) {
                    rowData.add("退房");
                } else if (0 == i) {
                    rowData.add("未约看");
                }
                for (int j = 1; j <= 6; j++) {
                    if (j > i) {
                        BigDecimal divide = stat[j - 1];
                        BigDecimal divided = stat[i - 1];
                        if (divided.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal res = divide.divide(divided, 4, BigDecimal.ROUND_UP).multiply(
                                    new BigDecimal(100)).setScale(2);
                            if (res.intValue() == 0) {
                                rowData.add("-");
                            } else {
                                rowData.add("" + res + "%");
                            }
                        } else {
                            rowData.add("-");
                        }
                    } else {
                        rowData.add("-");
                    }
                }
                tableData.add(rowData);
            }

            request.getSession().setAttribute("transCustomerData", tableData);
            model.addAttribute("tableData", tableData);
            model.addAttribute("page", pssr.getPaging());
        }

        model.addAttribute("statisticType", statisticType);
        return getAutoUrl();
    }

    @RequestMapping(value = "customerTransExportExcel", method = RequestMethod.GET)
    public void customerTransExportExcel(
            Model model, HttpServletRequest request, HttpServletResponse response
    ) {
        final String[] excelTitles = {"转化率", "约看", "到访", "认筹", "认购", "签约", "退房"};
        SourceStatisticsListResponse pssr = null;
        List<List<Object>> pssl = (List<List<Object>>) request.getSession().getAttribute("transCustomerData");
        List<List<Object>> recordList = new ArrayList<>();

        if (pssr != null) {
            for (List<Object> s1 : pssl) {
                String status = String.valueOf(s1.get(0));
                if ("1".equalsIgnoreCase(status)) {
                    status = "约看";
                } else if ("2".equalsIgnoreCase(status)) {
                    status = "到访";
                } else if ("3".equalsIgnoreCase(status)) {
                    status = "认筹";
                } else if ("4".equalsIgnoreCase(status)) {
                    status = "认购";
                } else if ("5".equalsIgnoreCase(status)) {
                    status = "签约";
                } else if ("6".equalsIgnoreCase(status)) {
                    status = "退房";
                } else if ("0".equalsIgnoreCase(status)) {
                    status = "未约看";
                }
            }
        }
        recordList = pssl;
        ExcelUtil.exportExcel("客户转化分析统计数据导出.xlsx", "客户转化分析统计数据导出", excelTitles, recordList, response);
    }

    @RequestMapping(value = "statusSourceExportExcel", method = RequestMethod.GET)
    public void statusSourceExportExcel(
            Model model, HttpServletRequest request, HttpServletResponse response
    ) {
        final String[] excelTitles = {"城市", "客户状态", "日期", "来源", "客户数量", "环比"};
        SourceStatisticsListResponse pssr = null;
        StatusSourceStatisticsListRequest pssl = (StatusSourceStatisticsListRequest) request.getSession().getAttribute(
                "statusSourceQueryRequest");
        List<List<Object>> recordList = new ArrayList<>();
        if (pssl != null) {
            String dateViewType = String.valueOf(request.getSession().getAttribute("dateViewType"));
            pssl.getPaging().setPageSize(Integer.MAX_VALUE);
            pssl.getPaging().setCurrentPage(1);
            pssr = statusSourceStatistics.statusSourceStatistic(pssl, dateViewType);

            if (pssr != null) {
                for (Map entity : pssr.getObjectList()) {
                    List<Object> record = new ArrayList<>();
                    record.add(entity.get("cityname"));
                    String status = String.valueOf(entity.get("customerStatus"));
                    if ("1".equalsIgnoreCase(status)) {
                        status = "约看";
                    } else if ("2".equalsIgnoreCase(status)) {
                        status = "到访";
                    } else if ("3".equalsIgnoreCase(status)) {
                        status = "认筹";
                    } else if ("4".equalsIgnoreCase(status)) {
                        status = "认购";
                    } else if ("5".equalsIgnoreCase(status)) {
                        status = "签约";
                    } else if ("6".equalsIgnoreCase(status)) {
                        status = "退房";
                    } else if ("0".equalsIgnoreCase(status)) {
                        status = "未约看";
                    }
                    record.add(status);
                    record.add(entity.get("createTime"));
                    record.add(entity.get("sourcename"));
                    record.add(entity.get("customerNum"));
                    record.add(entity.get("huanbi"));
                    recordList.add(record);
                }
            }
        }
        ExcelUtil.exportExcel("状态来源分布统计数据导出.xlsx", "状态来源分布统计数据导出", excelTitles, recordList, response);
    }

    @RequestMapping(value = "exportExcel", method = RequestMethod.GET)
    public void exportExcel(
            Model model, HttpServletRequest request, HttpServletResponse response
    ) {
        String statisticType = request.getSession().getAttribute("statisticType") == null ? "" : String.valueOf(
                request.getSession().getAttribute("statisticType"));

        if (!Strings.isNullOrEmpty(statisticType)) {
            final String[] excelTitles = {"城市", "客户状态", "日期", "部门", "客户数量", "环比"};
            SourceStatisticsListResponse pssr = null;
            if ("1".equalsIgnoreCase(statisticType)) {
                DeptSourceStatisticsListRequest pssl = (DeptSourceStatisticsListRequest) request.getSession().getAttribute(
                        "queryRequest");
                String dateViewType = String.valueOf(request.getSession().getAttribute("dateViewType"));
                pssl.getPaging().setPageSize(Integer.MAX_VALUE);
                pssl.getPaging().setCurrentPage(1);
                pssr = deptSourceStatistics.statisticCustomer(pssl, dateViewType);

            } else if ("2".equalsIgnoreCase(statisticType)) {
                UserSourceStatisticsListRequest pssl = (UserSourceStatisticsListRequest) request.getSession().getAttribute(
                        "queryRequest");
                String dateViewType = String.valueOf(request.getSession().getAttribute("dateViewType"));
                pssl.getPaging().setPageSize(Integer.MAX_VALUE);
                pssl.getPaging().setCurrentPage(1);
                pssr = userSourceStatistics.statisticCustomer(pssl, dateViewType);

            }

            if (pssr != null) {
                List<List<Object>> recordList = new ArrayList<>();
                for (Map entity : pssr.getObjectList()) {
                    List<Object> record = new ArrayList<>();
                    record.add(entity.get("cityname"));
                    String status = String.valueOf(entity.get("customerStatus"));
                    if ("1".equalsIgnoreCase(status)) {
                        status = "约看";
                    } else if ("2".equalsIgnoreCase(status)) {
                        status = "到访";
                    } else if ("3".equalsIgnoreCase(status)) {
                        status = "认筹";
                    } else if ("4".equalsIgnoreCase(status)) {
                        status = "认购";
                    } else if ("5".equalsIgnoreCase(status)) {
                        status = "签约";
                    } else if ("6".equalsIgnoreCase(status)) {
                        status = "退房";
                    } else if ("0".equalsIgnoreCase(status)) {
                        status = "未约看";
                    }
                    record.add(status);
                    record.add(entity.get("createTime"));
                    record.add(entity.get("projectName"));
                    record.add(entity.get("customerNum"));
                    record.add(entity.get("huanbi"));
                    recordList.add(record);
                }
                ExcelUtil.exportExcel("客户分析统计数据导出.xlsx", "客户分析统计数据导出", excelTitles, recordList, response);
            }

        }

    }

    /**
     * 设置查询时间
     *
     * @param dateViewType
     * @param startTime
     * @param endTime
     * @param queryMap
     */
    private void setQueryDate(String dateViewType, String startTime, String endTime, Map<String, Object> queryMap, Model model) {
        handleDate(dateViewType, startTime, endTime, queryMap, model, new Date());
    }

    private void setQueryDateLocalReport(
            String dateViewType, String startTime, String endTime, Map<String, Object> queryMap, Model model
    ) {
        Date startDate = new Date();
        handleDate(dateViewType, startTime, endTime, queryMap, model, startDate);
    }

    private void handleDate(String dateViewType, String startTime, String endTime, Map<String, Object> queryMap, Model model, Date beginDate) {
        String startTimeStr = "";
        String endTimeStr = "";
        SimpleDateFormat sdf;
        try {
            if (Strings.isNullOrEmpty(dateViewType)) {
                dateViewType = "1";
            }
            if (dateViewType.equals("1")) {
                // 没选日期，默认前一个时间单位
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");

                if (Strings.isNullOrEmpty(startTime) && Strings.isNullOrEmpty(endTime)) {
                    startTimeStr = sdf1.format(beginDate);
                    endTimeStr = sdf2.format(beginDate);
                } else {
                    // 如果选择了一个时间，取那一天/周/月的数据
                    if (!StringUtils.isEmpty(startTime)) {
                        startTimeStr = sdf1.format(sdf.parse(startTime));
                        if (StringUtils.isEmpty(endTime)) {
                            endTimeStr = sdf2.format(sdf.parse(startTime));
                        }
                    }

                    if (!StringUtils.isEmpty(endTime)) {
                        endTimeStr = sdf2.format(sdf.parse(endTime));
                        if (StringUtils.isEmpty(startTime)) {
                            startTimeStr = sdf1.format(sdf.parse(endTime));
                        }
                    }
                }

            } else if (dateViewType.equals("2")) {
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
                // 没选日期，默认前一个时间单位
                Date startDate = DateUtil.getLastWeekMonday(new Date());
                if (Strings.isNullOrEmpty(startTime) && Strings.isNullOrEmpty(endTime)) {
                    startTimeStr = sdf1.format(startDate);
                    endTimeStr = sdf2.format(DateUtil.getNowWeekSunday(sdf.parse(startTimeStr)));
                } else {
                    if (!StringUtils.isEmpty(startTime)) {
                        startTimeStr = sdf1.format(DateUtil.getNowWeekMonday(sdf.parse(startTime)));
                        if (StringUtils.isEmpty(endTime)) {
                            endTimeStr = sdf2.format(DateUtil.getNowWeekSunday(sdf.parse(startTime)));
                        }
                    }
                    if (!StringUtils.isEmpty(endTime)) {
                        endTimeStr = sdf2.format(DateUtil.getNowWeekSunday(sdf.parse(endTime)));
                        if (StringUtils.isEmpty(startTime)) {
                            startTimeStr = sdf1.format(DateUtil.getNowWeekMonday(sdf.parse(endTime)));
                        }
                    }

                }
            } else {
                sdf = new SimpleDateFormat("yyyy-MM");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
                // 没选日期，默认前一个时间单位
                Date startDate = DateUtil.getLastMonthFirstDay(new Date());
                if (Strings.isNullOrEmpty(startTime) && Strings.isNullOrEmpty(endTime)) {
                    startTimeStr = sdf1.format(startDate);
                    endTimeStr = sdf2.format(DateUtil.getLastMonthLastDay(new Date()));
                } else {
                    if (!StringUtils.isEmpty(startTime)) {
                        startTimeStr = sdf1.format(DateUtil.getNowMonthFirstDay(sdf.parse(startTime)));
                        if (StringUtils.isEmpty(endTime)) {
                            endTimeStr = sdf2.format(DateUtil.getNowMonthLastDay(sdf.parse(startTime)));
                        }
                    }
                    if (!StringUtils.isEmpty(endTime)) {
                        endTimeStr = sdf2.format(DateUtil.getNowMonthLastDay(sdf.parse(endTime)));
                        if (StringUtils.isEmpty(startTime)) {
                            startTimeStr = sdf1.format(DateUtil.getNowMonthFirstDay(sdf.parse(endTime)));
                        }
                    }
                }
            }

            model.addAttribute("startDate", sdf.format(sdf.parse(startTimeStr)));
            model.addAttribute("endDate", sdf.format(sdf.parse(endTimeStr)));

        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        if (!Strings.isNullOrEmpty(startTimeStr)) {
            queryMap.put("GTE_createTime", startTimeStr);
        }

        if (!Strings.isNullOrEmpty(endTimeStr)) {
            queryMap.put("LTE_andCreateTime", endTimeStr);
        }
    }

    private void setPageSelectedFlag(
            List<DepartmentEntity> departmentEntities, List<UserEntity> userEntities, String[] department, String[] user
    ) {
        if (department != null) {
            // 页面选中效果
            for (DepartmentEntity departmentEntity : departmentEntities) {
                departmentEntity.setType("0");
                for (String deptm : Lists.newArrayList(department)) {
                    if (deptm.equals(departmentEntity.getId().toString())) {
                        departmentEntity.setType("1");
                        break;
                    } else {
                        departmentEntity.setType("0");
                    }
                }
            }
        }

        if (user != null) {
            for (UserEntity userEntitiy1 : userEntities) {
                userEntitiy1.setWeiXinId("0");
                for (String user1 : Lists.newArrayList(user)) {
                    if (user1.equals(String.valueOf(userEntitiy1.getId()))) {
                        userEntitiy1.setWeiXinId("1");
                        break;
                    } else {
                        userEntitiy1.setWeiXinId("0");
                    }
                }
            }
        }
    }

    private void setPageSelectedFlag2(
            List<DepartmentEntity> departmentEntities, List<UserEntity> userEntities, List<ProjectEntity> projectEntities,
            List<ReportChannelEntity> channelEntities, String[] department, String[] user, String[] project,
            String[] channel
    ) {
        if (department != null) {
            // 页面选中效果
            for (DepartmentEntity departmentEntity : departmentEntities) {
                departmentEntity.setType("0");
                for (String deptm : Lists.newArrayList(department)) {
                    if (deptm.equals(departmentEntity.getId().toString())) {
                        departmentEntity.setType("1");
                        break;
                    } else {
                        departmentEntity.setType("0");
                    }
                }
            }
        }

        if (user != null && userEntities != null) {
            for (UserEntity userEntitiy1 : userEntities) {
                userEntitiy1.setWeiXinId("0");
                for (String user1 : Lists.newArrayList(user)) {
                    if (user1.equals(String.valueOf(userEntitiy1.getId()))) {
                        userEntitiy1.setWeiXinId("1");
                        break;
                    } else {
                        userEntitiy1.setWeiXinId("0");
                    }
                }
            }
        }

        if (project != null) {
            for (ProjectEntity projectEntity : projectEntities) {
                projectEntity.setFlag(false);
                for (String projectStr : Lists.newArrayList(project)) {
                    if (projectStr.equals(String.valueOf(projectEntity.getId()))) {
                        projectEntity.setFlag(true);
                        break;
                    } else {
                        projectEntity.setFlag(false);
                    }
                }
            }
        }

        if (channel != null && null != channelEntities) {
            for (ReportChannelEntity channelEntity : channelEntities) {
                channelEntity.setCreater("0");
                for (String channelStr : Lists.newArrayList(channel)) {
                    if (channelStr.equals(String.valueOf(channelEntity.getId()))) {
                        channelEntity.setCreater("1");
                        break;
                    } else {
                        channelEntity.setCreater("0");
                    }
                }
            }
        }
    }

    private void setPageSelectedFlag3(
            List<DepartmentEntity> departmentEntities, List<UserEntity> userEntities, String[] department, String[] user
    ) {
        if (department != null) {
            // 页面选中效果
            for (DepartmentEntity departmentEntity : departmentEntities) {
                departmentEntity.setType("0");
                for (String deptm : Lists.newArrayList(department)) {
                    if (deptm.equals(departmentEntity.getId().toString())) {
                        departmentEntity.setType("1");
                        break;
                    } else {
                        departmentEntity.setType("0");
                    }
                }
            }
        }

        if (user != null) {
            for (UserEntity userEntitiy1 : userEntities) {
                userEntitiy1.setWeiXinId("0");
                for (String user1 : Lists.newArrayList(user)) {
                    if (user1.equals(String.valueOf(userEntitiy1.getId()))) {
                        userEntitiy1.setWeiXinId("1");
                        break;
                    } else {
                        userEntitiy1.setWeiXinId("0");
                    }
                }
            }
        }
    }

    /**
     * 驻场日报
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "localReportStatistic", method = RequestMethod.GET)
    public String localReportStatistic(Model model, HttpServletRequest request) {
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");

        ProjectListRequest projectReq = new ProjectListRequest();
        projectReq.setPaging(new Page(Integer.MAX_VALUE));
        HashMap<String, Object> map = new HashMap<>();
        map.put("EQ_cityName", dept.getName());
        map.put("EQ_showStatus", "1");
        projectReq.setSearchParams(map);
        projectReq.setOrderColumn("createTime ");
        projectReq.setOrderMode(" desc ");
        ProjectListResponse projectRsp = project.getProjectList(projectReq);
        List<ProjectEntity> projectList = projectRsp.getObjectList();
        model.addAttribute("projects", projectList);

        DepartmentEntity city = null;
        String cityId = dept.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        city = departmentResponse.getEntity();

        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String urlPath = "";
        if (userEntity.getDeptId() == 1) {
            urlPath = city.getUrlPath();
        } else {
            urlPath = userEntity.getDeptUrlPath() + "/";
        }

        CityDepConfigListRequest cdlr = new CityDepConfigListRequest();
        Map<String, Object> cdm = new HashMap<>();
        cdm.put("EQ_city", cityId);
        cdlr.setSearchParams(cdm);
        CityDepConfigListResponse cr = cityDepConfig.getCityDepConfigList(cdlr);

        DepartmentListRequest dlr = new DepartmentListRequest();
        Page dPage = new Page(Integer.MAX_VALUE);

        List<DepartmentEntity> departmentEntities = new ArrayList<>();

        if (cr.getObjectList() != null && !cr.getObjectList().isEmpty()) {
            List<CityDepConfigEntity> cdl = cr.getObjectList();
            CityDepConfigEntity cd = cdl.get(0);
            String dc = cd.getDept();

            Map<String, Object> dmap = new HashMap<>();
            dmap.put("IN_ids", Lists.newArrayList(dc.split(",")));
            dlr.setParamMap(dmap);
            dlr.setOrderColumn("name");
            dlr.setOrderMode("asc");
            dlr.setSearchParams(dmap);
            dlr.setPaging(dPage);
            departmentEntities = department.getDepartmentList(dlr).getObjectList();
        }

        model.addAttribute("departmentList", departmentEntities);

        List<UserEntity> userEntities = new ArrayList<>();
        Map<String, Object> reportChanne = new HashMap<>();
        reportChanne.put("EQ_city", dept.getDescripition());
        reportChanne.put("EQ_status", "1");
        ReportChannelListRequest listRequest = new ReportChannelListRequest();
        listRequest.setPaging(new Page(Integer.MAX_VALUE));
        listRequest.setSearchParams(reportChanne);
        listRequest.setOrderColumn("create_time ");
        listRequest.setOrderMode(" desc ");
        ReportChannelListResponse channelList = reportChannel.getReportChannelList(listRequest);
        model.addAttribute("channelList", channelList.getObjectList());

        Map<String, Object> listMap = new HashMap<>();
        String dateViewType = request.getParameter("dateViewType") == null ? "1" : request.getParameter("dateViewType");
        // 处理日期查询条件
        setQueryDateLocalReport(dateViewType, startTime, endTime, listMap, model);

        String groupStr = "";
        String[] queryProject = request.getParameterValues(
                "project") == null ? new String[]{} : request.getParameterValues("project");
        String[] queryChannels = request.getParameterValues(
                "channel") == null ? new String[]{} : request.getParameterValues("channel");
        String[] queryDepart = request.getParameterValues(
                "department") == null ? new String[]{} : request.getParameterValues("department");
        String[] queryUser = request.getParameterValues("user") == null ? new String[]{} : request.getParameterValues(
                "user");

        String groupByDate = "";
        switch (dateViewType) {
            case "1":
                groupByDate = "DATE_FORMAT(l.report_date, '%Y%m%d')";
                break;
            case "2":
                groupByDate = "DATE_FORMAT(l.report_date, '%Y%u')";
                break;
            case "3":
                groupByDate = "DATE_FORMAT(l.report_date, '%Y%m')";
                break;
            default:
                groupByDate = "DATE_FORMAT(l.report_date, '%Y%m%d')";
                break;
        }

        // 设置页面多选框选中效果
        setPageSelectedFlag2(departmentEntities, userEntities, projectList, channelList.getObjectList(), queryDepart,
                queryUser, queryProject, queryChannels);

        if (!Strings.isNullOrEmpty(groupByDate)) {
            groupStr = groupByDate;
        }

        //group by project ,default
        if (queryChannels.length > 0) {
            if (!"all".equalsIgnoreCase(queryChannels[0])) {
                groupStr += ",channel_id";
                listMap.put("EQ_channelId", Joiner.on(",").join(queryChannels));
            }
        }

        if (queryUser.length > 0) {
            groupStr += ",user_id";
            if (!"all".equalsIgnoreCase(queryUser[0])) {
                listMap.put("EQ_userId", Joiner.on(",").join(queryUser));
            }
        }

        if (queryProject.length > 0) {
            if (!"all".equalsIgnoreCase(queryProject[0])) {
                groupStr += ",project_id";
                listMap.put("EQ_projectId", Joiner.on(",").join(queryProject));
            }
        }
        List<LocalReportFormVo> voList = new ArrayList<>();
        Map<Integer, Set<Integer>> deptMap = new HashMap<>();
        if (queryDepart.length > 0) {
            if (!"all".equalsIgnoreCase(queryDepart[0])) {
                groupStr += ",stid";
                //maybe use union all replace this if need page
                for (String deptId : queryDepart) {
                    listMap.put("EQ_departId", deptId);
                    listMap.put("EQ_groupby", groupStr);
                    listMap.put("EQ_period", groupByDate);
                    LocalReportListRequest localReportListRequest = new LocalReportListRequest();
                    localReportListRequest.setSearchParams(listMap);
                    localReportListRequest.setPaging(new Page(1000));
                    request.getSession().setAttribute("localReportQueryRequest", localReportListRequest);
                    House365SearchResponse response = localReportService.statistic(localReportListRequest);
                    voList.addAll(response.getObjectList());
                }
            } else {
                listMap.put("EQ_groupby", groupStr);
                listMap.put("EQ_period", groupByDate);
                LocalReportListRequest localReportListRequest = new LocalReportListRequest();
                localReportListRequest.setSearchParams(listMap);
                localReportListRequest.setPaging(new Page(1000));
                request.getSession().setAttribute("localReportQueryRequest", localReportListRequest);
                House365SearchResponse response = localReportService.statistic(localReportListRequest);
                voList = response.getObjectList();
            }
        } else {

            listMap.put("EQ_groupby", groupStr);
            listMap.put("EQ_period", groupByDate);
            LocalReportListRequest localReportListRequest = new LocalReportListRequest();
            localReportListRequest.setSearchParams(listMap);
            localReportListRequest.setPaging(new Page(1000));
            request.getSession().setAttribute("localReportQueryRequest", localReportListRequest);
            House365SearchResponse response = localReportService.statistic(localReportListRequest);
            voList = response.getObjectList();
        }

        handleLRList(queryProject, queryChannels, queryDepart, queryUser, deptMap, voList);

        model.addAttribute("queryUser", Joiner.on(",").join(queryUser));
        //设置显示tab
        //        model.addAttribute("displayTab", displayTab);
        model.addAttribute("dateViewType", dateViewType);
        model.addAttribute("tableData", voList);
        return getAutoUrl();
    }

    //handle child dept data , sum and add to parent dept
    private void handleLRList(
            String[] queryProject, String[] queryChannels, String[] queryDepart, String[] queryUser,
            Map<Integer, Set<Integer>> deptMap, List<LocalReportFormVo> voList
    ) {
        String allShow = "全部";
        for (LocalReportFormVo vo : voList) {
            if (queryProject.length == 0 || "all".equalsIgnoreCase(queryProject[0])) {
                vo.setProjectname(allShow);
            }
            if (queryChannels.length == 0 || "all".equalsIgnoreCase(queryChannels[0])) {
                vo.setChannelName(allShow);
            }

            if (queryDepart.length == 0 || "all".equalsIgnoreCase(queryDepart[0])) {
                vo.setDepartName(allShow);
            }

            if (queryUser.length == 0) {
                vo.setName(allShow);
            }
        }

    }

    private void handleLRList2(
            String[] queryDepart, String[] queryUser, Map<Integer, Set<Integer>> deptMap, List<ReportMarketingFormVo> voList
    ) {
        String allShow = "全部";
        if (voList != null) {
            for (ReportMarketingFormVo vo : voList) {
                if (queryDepart.length == 0 || "all".equalsIgnoreCase(queryDepart[0])) {
                    vo.setDepartmentName(allShow);
                }

                if (queryUser.length == 0) {
                    vo.setUserName(allShow);
                }
            }
        }
    }


    /**
     * 直销日报
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "reportMarketingStatistic", method = RequestMethod.GET)
    public String reportMarketingStatistic(Model model, HttpServletRequest request) {
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);

        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");

        String cityId = dept.getCityID();

        CityDepConfigListRequest cdlr = new CityDepConfigListRequest();
        Map<String, Object> cdm = new HashMap<>();
        cdm.put("EQ_city", cityId);
        cdlr.setSearchParams(cdm);
        CityDepConfigListResponse cr = cityDepConfig.getCityDepConfigList(cdlr);

        DepartmentListRequest dlr = new DepartmentListRequest();
        Page dPage = new Page(Integer.MAX_VALUE);

        List<DepartmentEntity> departmentEntities = new ArrayList<>();

        if (cr.getObjectList() != null && !cr.getObjectList().isEmpty()) {
            List<CityDepConfigEntity> cdl = cr.getObjectList();
            CityDepConfigEntity cd = cdl.get(0);
            String dc = cd.getDept();

            Map<String, Object> dmap = new HashMap<>();
            dmap.put("IN_ids", Lists.newArrayList(dc.split(",")));
            dlr.setParamMap(dmap);
            dlr.setOrderColumn("name");
            dlr.setOrderMode("asc");
            dlr.setSearchParams(dmap);
            dlr.setPaging(dPage);
            departmentEntities = department.getDepartmentList(dlr).getObjectList();
        }

        model.addAttribute("departmentList", departmentEntities);

        List<UserEntity> userEntities = new ArrayList<>();

        Map<String, Object> reportChannel = new HashMap<>();
        reportChannel.put("EQ_city", dept.getDescripition());
        reportChannel.put("EQ_status", "1");

        Map<String, Object> listMap = new HashMap<>();
        String dateViewType = request.getParameter("dateViewType") == null ? "1" : request.getParameter("dateViewType");
        // 处理日期查询条件
        setQueryDate(dateViewType, startTime, endTime, listMap, model);

        String groupStr = "";
        String[] queryDepart = request.getParameterValues(
                "department") == null ? new String[]{} : request.getParameterValues("department");
        String[] queryUser = request.getParameterValues("user") == null ? new String[]{} : request.getParameterValues(
                "user");

        String groupByDate = "";
        switch (dateViewType) {
            case "1":
                groupByDate = "DATE_FORMAT(rm.report_time, '%Y%m%d')";
                break;
            case "2":
                groupByDate = "DATE_FORMAT(rm.report_time, '%Y%u')";
                break;
            case "3":
                groupByDate = "DATE_FORMAT(rm.report_time, '%Y%m')";
                break;
            default:
                groupByDate = "DATE_FORMAT(rm.report_time, '%Y%m%d')";
                break;
        }

        // 设置页面多选框选中效果
        setPageSelectedFlag3(departmentEntities, userEntities, queryDepart, queryUser);


        if (!Strings.isNullOrEmpty(groupByDate)) {
            groupStr = groupByDate;
        }

        Map<Integer, Set<Integer>> deptMap = new HashMap<>();

        if (queryUser.length > 0) {
            groupStr += ",user_id";
            if (!"all".equalsIgnoreCase(queryUser[0])) {
                listMap.put("EQ_userId", Joiner.on(",").join(queryUser));
            }
        }


        List<ReportMarketingFormVo> voList = new ArrayList<>();
        if (queryDepart.length > 0) {
            if (!"all".equalsIgnoreCase(queryDepart[0])) {
                List<String> departIds = Arrays.asList(queryDepart);
                //maybe use union all replace this if need page
                listMap.put("EQ_departIds", departIds);
                listMap.put("EQ_groupby", groupStr);
                listMap.put("EQ_period", groupByDate);
                ReportMarketingListRequest reportMarketingListRequest = new ReportMarketingListRequest();
                reportMarketingListRequest.setSearchParams(listMap);
                reportMarketingListRequest.setPaging(new Page(1000));
                request.getSession().setAttribute("reportMarketingQueryRequest", reportMarketingListRequest);
                House365SearchResponse response = reportMarketingService.statistic(reportMarketingListRequest);
                voList.addAll(response.getObjectList());

            } else {
                List<String> departIds = new ArrayList<>();
                for (DepartmentEntity departmentEntity : departmentEntities) {
                    departIds.add(String.valueOf(departmentEntity.getId()));
                }
                listMap.put("EQ_departIds", departIds);
                listMap.put("EQ_groupby", groupStr);
                listMap.put("EQ_period", groupByDate);
                ReportMarketingListRequest reportMarketingListRequest = new ReportMarketingListRequest();
                reportMarketingListRequest.setSearchParams(listMap);
                reportMarketingListRequest.setPaging(new Page(1000));
                request.getSession().setAttribute("reportMarketingQueryRequest", reportMarketingListRequest);
                House365SearchResponse response = reportMarketingService.statistic(reportMarketingListRequest);
                voList = response.getObjectList();
            }
        }

        handleLRList2(queryDepart, queryUser, deptMap, voList);

        model.addAttribute("queryUser", Joiner.on(",").join(queryUser));
        //设置显示tab
        //        model.addAttribute("displayTab", displayTab);
        model.addAttribute("dateViewType", dateViewType);
        model.addAttribute("tableData", voList);
        return getAutoUrl();
    }

    /**
     * 驻场日报导出
     *
     * @param model
     * @param request
     * @param response
     */
    @RequestMapping(value = "localReportStatisticExcel", method = RequestMethod.GET)
    public void localReportStatisticExcel(
            Model model, HttpServletRequest request, HttpServletResponse response
    ) {
        final String[] excelTitles = {"日期", "项目", "渠道", "部门", "职员", "报备", "到访", "认筹", "认购", "业绩"};
        LocalReportListRequest localReportListRequest = (LocalReportListRequest) request.getSession().getAttribute(
                "localReportQueryRequest");
        localReportListRequest.setPaging(new Page(Integer.MAX_VALUE));
        House365SearchResponse searchResponse = localReportService.statistic(localReportListRequest);

        String[] queryProject = request.getParameterValues(
                "project") == null ? new String[]{} : request.getParameterValues("project");
        String[] queryChannels = request.getParameterValues(
                "channel") == null ? new String[]{} : request.getParameterValues("channel");
        String[] queryDepart = request.getParameterValues(
                "department") == null ? new String[]{} : request.getParameterValues("department");
        String[] queryUser = request.getParameterValues("user") == null ? new String[]{} : request.getParameterValues(
                "user");

        List<List<Object>> recordList = new ArrayList<>();
        if (searchResponse.getObjectList() != null) {
            List<LocalReportFormVo> list = searchResponse.getObjectList();

            Map<String, Object> listMap = new HashMap<>();
            Map<Integer, Set<Integer>> deptMap = new HashMap<>();
            if (queryDepart.length > 0) {
                if (!"all".equalsIgnoreCase(queryDepart[0])) {
                    //get all depts and childs
                    Set<String> deptIds = new HashSet<>();
                    for (String d : queryDepart) {
                        DepartmentResponse res = department.getDepartmentById(Integer.valueOf(d));
                        if (res.getEntity() != null) {

                            Set<Integer> childIds = new HashSet<>();
                            List<DepartmentEntity> children = department.findChildrenListByPath(
                                    Lists.newArrayList(res.getEntity()));
                            for (DepartmentEntity de : children) {
                                deptIds.add(String.valueOf(de.getId()));
                                childIds.add(de.getId());
                            }
                            deptMap.put(res.getEntity().getId(), childIds);

                        }
                    }

                    listMap.put("EQ_departId", Joiner.on(",").join(deptIds));
                }
            }
            handleLRList(queryProject, queryChannels, queryDepart, queryUser, deptMap, list);

            for (LocalReportFormVo entity : list) {
                List<Object> record = new ArrayList<>();
                record.add(entity.getReportDate());
                record.add(entity.getProjectname());
                record.add(entity.getChannelName());
                record.add(entity.getDepartName());
                record.add(entity.getName());
                record.add(entity.getRecord());
                record.add(entity.getVisit());
                record.add(entity.getBuyorder());
                record.add(entity.getBuy());
                record.add(entity.getScore());
                recordList.add(record);
            }
        }

        ExcelUtil.exportExcel("驻场日报导出.xlsx", "驻场日报导出", excelTitles, recordList, response);
    }

    /**
     * 直销日报导出
     *
     * @param model
     * @param request
     * @param response
     */
    @RequestMapping(value = "reportMarketingStatisticExcel", method = RequestMethod.GET)
    public void reportMarketingStatisticExcel(
            Model model, HttpServletRequest request, HttpServletResponse response
    ) {
        final String[] excelTitles = {"日期", "部门", "姓名", "电话接触量", "电话接通量", "意向沉淀量", "到访量", "认筹量", "认购量", "业绩"};
        ReportMarketingListRequest reportMarketingListRequest = (ReportMarketingListRequest) request.getSession().getAttribute(
                "reportMarketingQueryRequest");

        String[] queryDepart = request.getParameterValues(
                "department") == null ? new String[]{} : request.getParameterValues("department");
        String[] queryUser = request.getParameterValues("user") == null ? new String[]{} : request.getParameterValues(
                "user");
        Map<Integer, Set<Integer>> deptMap = new HashMap<>();
        if (queryDepart.length > 0) {
            if (!"all".equalsIgnoreCase(queryDepart[0])) {
                //get all depts and childs
                Set<String> deptIds = new HashSet<>();

                for (String d : queryDepart) {
                    DepartmentResponse res = department.getDepartmentById(Integer.valueOf(d));
                    if (res.getEntity() != null) {

                        Set<Integer> childIds = new HashSet<>();
                        List<DepartmentEntity> children = department.findChildrenListByPath(
                                Lists.newArrayList(res.getEntity()));
                        for (DepartmentEntity de : children) {
                            deptIds.add(String.valueOf(de.getId()));
                            childIds.add(de.getId());
                        }
                        deptMap.put(res.getEntity().getId(), childIds);

                    }
                }
            }
        }

        reportMarketingListRequest.setPaging(new Page(Integer.MAX_VALUE));
        House365SearchResponse searchResponse = reportMarketingService.statistic(reportMarketingListRequest);

        handleLRList2(queryDepart, queryUser, deptMap, searchResponse.getObjectList());

        List<List<Object>> recordList = new ArrayList<>();
        if (searchResponse.getObjectList() != null) {
            List<ReportMarketingFormVo> list = searchResponse.getObjectList();
            for (ReportMarketingFormVo entity : list) {
                List<Object> record = new ArrayList<>();
                record.add(entity.getReportTime());
                record.add(entity.getDepartmentName());
                record.add(entity.getUserName());
                record.add(entity.getCallCount());
                record.add(entity.getConnectCount());
                record.add(entity.getIntentBuyCount());
                record.add(entity.getVisitedCount());
                record.add(entity.getIdentificationChipsCount());
                record.add(entity.getSubscriptionCount());
                record.add(entity.getSource());
                recordList.add(record);
            }
        }

        ExcelUtil.exportExcel("直销日报导出.xlsx", "直销日报导出", excelTitles, recordList, response);
    }

    /**
     * 项目来源分析
     */
    @RequestMapping(value = "projectSource", method = RequestMethod.GET)
    public String projectSource(Model model, HttpServletRequest request) {
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);

        ProjectListRequest projectReq = new ProjectListRequest();
        projectReq.setPaging(new Page(Integer.MAX_VALUE));
        HashMap<String, Object> map = new HashMap<>();
        map.put("EQ_cityName", dept.getName());
        projectReq.setSearchParams(map);
        ProjectListResponse projectRsp = project.getProjectList(projectReq);
        List<ProjectEntity> projectList = projectRsp.getObjectList();
        model.addAttribute("projects", projectList);

        String dateViewType = request.getParameter("dateViewType");
        String projectIds = request.getParameter("projectIds");
        String projectNames = request.getParameter("projectNames");


        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        Map<String, Object> queryMap = new HashMap<>();
        // 处理日期查询条件
        setQueryDate(dateViewType, startTime, endTime, queryMap, model);


        if (StringUtils.isEmpty(dateViewType)) {
            model.addAttribute("sourceList", JSONArray.fromObject(Arrays.asList(new String[]{})));
            model.addAttribute("projectList", JSONArray.fromObject(Arrays.asList(new String[]{})));
            model.addAttribute("viewList", JSONArray.fromObject(Arrays.asList(new String[]{})));
            return getAutoUrl();
        }
        if (projectIds.equals(",")) {
            model.addAttribute("sourceList", JSONArray.fromObject(Arrays.asList(new String[]{})));
            model.addAttribute("projectList", JSONArray.fromObject(Arrays.asList(new String[]{})));
            model.addAttribute("viewList", JSONArray.fromObject(Arrays.asList(new String[]{})));
            return getAutoUrl();
        }
        projectNames = projectNames.substring(1, projectNames.length() - 1);
        List<String> projectNameList = Arrays.asList(projectNames.split(","));
        projectIds = projectIds.substring(1, projectIds.length() - 1);
        List<Integer> projectIdList = new LinkedList<>();
        String[] split = projectIds.split(",");
        for (String str : split) {
            projectIdList.add(Integer.valueOf(str));
        }
        for (ProjectEntity entity : projectList) {
            for (Integer pid : projectIdList) {
                if (entity.getId().intValue() == pid) {
                    entity.setFlag(true);
                }
            }
        }

        ProjectSrouceParaPo paraPo = setProjectSourcePara(request, model);

        List<Map<String, Object>> tmpListResult = customerStatusLog.getProjectSource(paraPo);
        Set<String> sourceSet = new HashSet<>();
        Set<String> projectSet = new HashSet<>(projectNameList);
        for (Map<String, Object> m : tmpListResult) {
            sourceSet.add((String) (m.get("source")));
            projectSet.add((String) (m.get("projectName")));
        }

        //如果来源为空，echart只展示第一个项目，看起来不合理。 修改：如果没有来源数据，不显示项目信息
        List<BarPo> resultList = new LinkedList<>();
        if (!sourceSet.isEmpty()) {

            BarPo tmpMap;
            List<Long> tmpList;
            for (String source : sourceSet) {
                tmpMap = new BarPo();
                tmpMap.setName(source);
                tmpMap.setType("bar");
                tmpMap.setBarMaxWidth(35);

                tmpList = new LinkedList<>();
                boolean flag;
                for (String tmpProject : projectSet) {
                    flag = false;
                    for (Map<String, Object> m : tmpListResult) {
                        if (m.get("source").equals(source) && m.get("projectName").equals(tmpProject)) {
                            tmpList.add((Long) (m.get("num")));
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        tmpList.add(0L);
                    }
                }
                tmpMap.setData(tmpList);
                resultList.add(tmpMap);
            }

            // 排序
            List<BarComparePo> BarComparePoList = new LinkedList<>();
            BarComparePo tmpBarComparePo = null;
            List<Long> data = null;
            int i = 0;
            for (Iterator<String> iterator = projectSet.iterator(); iterator.hasNext(); ) {
                tmpBarComparePo = new BarComparePo();
                tmpBarComparePo.setProjectName(iterator.next());
                data = new LinkedList<>();
                for (BarPo tmpPo : resultList) {
                    data.add(tmpPo.getData().get(i));
                }
                tmpBarComparePo.setData(data);
                BarComparePoList.add(tmpBarComparePo);
                i++;
            }
            Collections.sort(BarComparePoList);
            projectSet.clear();
            for (BarPo tmpPo : resultList) {
                tmpPo.getData().clear();
            }
            int j = 0;
            for (BarComparePo po : BarComparePoList) {
                projectSet.add(po.getProjectName());
                for (BarPo tmpPo : resultList) {
                    tmpPo.getData().add(po.getData().get(j++));
                }
                j = 0;
            }
        } else {
            projectSet.clear();
        }

        model.addAttribute("projectIds", projectIdList);
        model.addAttribute("projectNames", projectNameList);
        model.addAttribute("sourceList", JSONArray.fromObject(sourceSet));
        model.addAttribute("projectList", JSONArray.fromObject(projectSet));
        model.addAttribute("viewList", JSONArray.fromObject(resultList));
        model.addAttribute("hight", projectSet.size() * 300);
        List<ProjectSrouceRePo> projectSourceTableData = getProjectSourceTableData(paraPo);
        model.addAttribute("tableData", projectSourceTableData);
        return getAutoUrl();
    }

    private ProjectSrouceParaPo setProjectSourcePara(HttpServletRequest request, Model model) {
        String dateViewType = request.getParameter("dateViewType");
        String projectIds = request.getParameter("projectIds");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String status = request.getParameter("status");

        ProjectSrouceParaPo paraPo = new ProjectSrouceParaPo();
        if (!StringUtils.isEmpty(status)) {
            paraPo.setStatus(Integer.valueOf(status));
        }

        SimpleDateFormat sdf;
        SimpleDateFormat sdfTmp;
        paraPo.setDateViewType(Integer.valueOf(dateViewType));
        Calendar calendar = Calendar.getInstance();
        calendar.setMinimalDaysInFirstWeek(7);
        try {
            if (dateViewType.equals("1")) {
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                sdfTmp = new SimpleDateFormat("yyyyMMdd");
                if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraPo.setStartTime(startTime);
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.addDays(sdf.parse(startTime), -1)));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextDay(sdf.parse(endTime))));
                }
                if (!StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    paraPo.setStartTime(startTime);
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.addDays(sdf.parse(startTime), -1)));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextDay(sdf.parse(startTime))));
                }
                if (StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraPo.setStartTime(endTime);
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.addDays(sdf.parse(endTime), -1)));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextDay(sdf.parse(endTime))));
                }
                if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    String now = sdf.format(DateUtil.addDays(new Date(), -1));
                    paraPo.setStartTime(now);
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.addDays(sdf.parse(now), -1)));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextDay(sdf.parse(now))));
                }
            } else if (dateViewType.equals("2")) {
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                sdfTmp = new SimpleDateFormat("yyyyww");
                sdfTmp.setCalendar(calendar);
                if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraPo.setStartTime(sdf.format(DateUtil.getNowWeekMonday(sdf.parse(startTime))));
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.getLastWeekMonday(sdf.parse(startTime))));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextWeekMonday(sdf.parse(endTime))));
                }
                if (!StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    paraPo.setStartTime(sdf.format(DateUtil.getNowWeekMonday(sdf.parse(startTime))));
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.getLastWeekMonday(sdf.parse(startTime))));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextWeekMonday(sdf.parse(startTime))));
                }
                if (StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraPo.setStartTime(sdf.format(DateUtil.getNowWeekMonday(sdf.parse(endTime))));
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.getLastWeekMonday(sdf.parse(endTime))));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextWeekMonday(sdf.parse(endTime))));
                }
                if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    String now = sdf.format(DateUtil.addWeeks(new Date(), -1));
                    paraPo.setStartTime(sdf.format(DateUtil.getNowWeekMonday(sdf.parse(now))));
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.getLastWeekMonday(sdf.parse(now))));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextWeekMonday(sdf.parse(now))));
                }
            } else {
                sdf = new SimpleDateFormat("yyyy-MM");
                sdfTmp = new SimpleDateFormat("yyyyMM");
                sdfTmp.setCalendar(calendar);
                if (!StringUtils.isEmpty(startTime)) {
                    paraPo.setStartTime(sdf.format(DateUtil.getNowMonthFirstDay(sdf.parse(startTime))));
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.getLastMonthLastDay(sdf.parse(startTime))));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextMonthFirstDay(sdf.parse(endTime))));
                }
                if (!StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    paraPo.setStartTime(sdf.format(DateUtil.getNowMonthFirstDay(sdf.parse(startTime))));
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.getLastMonthLastDay(sdf.parse(startTime))));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextMonthFirstDay(sdf.parse(startTime))));
                }
                if (StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraPo.setStartTime(sdf.format(DateUtil.getNowMonthFirstDay(sdf.parse(endTime))));
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.getLastMonthLastDay(sdf.parse(endTime))));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextMonthFirstDay(sdf.parse(endTime))));
                }
                if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    String now = sdf.format(DateUtil.addMonths(new Date(), -1));
                    paraPo.setStartTime(sdf.format(DateUtil.getNowMonthFirstDay(sdf.parse(now))));
                    paraPo.setStartTimeFormatStr(sdfTmp.format(DateUtil.getLastMonthLastDay(sdf.parse(now))));
                    paraPo.setEndTime(sdf.format(DateUtil.getNextMonthFirstDay(sdf.parse(now))));
                }
            }

            model.addAttribute("startDate", paraPo.getStartTime());
            model.addAttribute("endDate", sdf.format(DateUtil.getLastDay(sdf.parse(paraPo.getEndTime()))));

        } catch (ParseException e) {
            LOGGER.error(e.getMessage(), e);
        }

        projectIds = projectIds.substring(1, projectIds.length() - 1);
        List<Integer> projectIdList = new LinkedList<>();
        String[] split = projectIds.split(",");
        for (String str : split) {
            projectIdList.add(Integer.valueOf(str.trim()));
        }
        paraPo.setProjectIds(projectIdList);
        paraPo.setSameStatus("sameStatus");

        return paraPo;
    }

    private List<ProjectSrouceRePo> getProjectSourceTableData(ProjectSrouceParaPo paraPo) {
        if (null != paraPo.getStartTime()) {
            SimpleDateFormat sdf = null;
            Date tmpDate = null;
            try {
                switch (paraPo.getDateViewType()) {
                    case 1:
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                        tmpDate = DateUtil.addDays(sdf.parse(paraPo.getStartTime()), -1);
                        break;
                    case 2:
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                        tmpDate = DateUtil.addWeeks(sdf.parse(paraPo.getStartTime()), -1);
                        break;
                    case 3:
                        sdf = new SimpleDateFormat("yyyy-MM");
                        tmpDate = DateUtil.addMonths(sdf.parse(paraPo.getStartTime()), -1);
                        break;
                    default:
                        break;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (null != tmpDate && sdf != null) {
                paraPo.setStartTime(sdf.format(tmpDate));
            }
        }
        List<ProjectSrouceRePo> resultLi = projectSourceStatistics.getProjectSourceStatistics(paraPo);

        try {
            if (CollectionUtils.isNotEmpty(resultLi)) {
                NumberFormat nf = NumberFormat.getPercentInstance();
                nf.setMinimumFractionDigits(2);
                String statusMsg = null;
                if (paraPo.getStatus() != null) {
                    statusMsg = CustomerStatusEnum.getMsgByStatus(paraPo.getStatus());
                } else {
                    statusMsg = "全部";
                }

                double ratio;
                ProjectSrouceRePo lastTmp = null;
                SimpleDateFormat sdf = null;
                for (ProjectSrouceRePo projectSrouceRePo : resultLi) {
                    projectSrouceRePo.setStatusMsg(statusMsg);
                    if (null == lastTmp) {
                        lastTmp = projectSrouceRePo;
                        projectSrouceRePo.setDayBaseRatio("-");
                        continue;
                    }
                    if (lastTmp.getProjectId().intValue() == projectSrouceRePo.getProjectId().intValue() && projectSrouceRePo.getSourceName().equals(
                            lastTmp.getSourceName())) {
                        if (paraPo.getDateViewType() == 1) {
                            sdf = new SimpleDateFormat("yyyyMMdd");
                            if (lastTmp.getTime().equals(sdf.format(DateUtil.addDays(sdf.parse(projectSrouceRePo.getTime

                                    ()), -1)))) {
                                ratio = ((projectSrouceRePo.getCount() - lastTmp.getCount()) * 1.0) / lastTmp.getCount();
                                projectSrouceRePo.setDayBaseRatio(nf.format(ratio));
                            } else {
                                projectSrouceRePo.setDayBaseRatio("-");
                            }
                        } else if (paraPo.getDateViewType() == 2) {
                            sdf = new SimpleDateFormat("yyyyww");
                            if (sdf.format(DateUtil.addWeeks(sdf.parse(lastTmp.getTime

                                    ()), 1)).equals(projectSrouceRePo.getTime())) {
                                ratio = ((projectSrouceRePo.getCount() - lastTmp.getCount()) * 1.0) / lastTmp.getCount();
                                projectSrouceRePo.setDayBaseRatio(nf.format(ratio));
                            } else {
                                projectSrouceRePo.setDayBaseRatio("-");
                            }
                        } else {
                            sdf = new SimpleDateFormat("yyyyMM");
                            if (sdf.format(DateUtil.addMonths(sdf.parse(lastTmp.getTime

                                    ()), 1)).equals(projectSrouceRePo.getTime())) {
                                ratio = ((projectSrouceRePo.getCount() - lastTmp.getCount()) * 1.0) / lastTmp.getCount();
                                projectSrouceRePo.setDayBaseRatio(nf.format(ratio));
                            } else {
                                projectSrouceRePo.setDayBaseRatio("-");
                            }
                        }
                    } else {
                        projectSrouceRePo.setDayBaseRatio("-");
                    }
                    lastTmp = projectSrouceRePo;
                }
                if (paraPo.getStartTimeFormatStr() != null) {
                    ProjectSrouceRePo tmpPo = null;
                    for (Iterator iterator = resultLi.iterator(); iterator.hasNext(); ) {
                        tmpPo = (ProjectSrouceRePo) iterator.next();
                        if (paraPo.getStartTimeFormatStr().equals(tmpPo.getTime())) {
                            iterator.remove();
                        }
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return resultLi;
    }

    /**
     * 项目来源分析EXCEL
     */
    @RequestMapping(value = "/projectSourceExcel", method = RequestMethod.GET)
    public void projectSourceExcel(
            Model model, HttpServletRequest request, HttpServletResponse response
    ) {
        List<List<Object>> recordList = new ArrayList<>();
        ProjectSrouceParaPo projectSrouceParaPo = setProjectSourcePara(request, model);
        List<ProjectSrouceRePo> projectSourceTableData = getProjectSourceTableData(projectSrouceParaPo);
        List<Object> li = null;
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        for (ProjectSrouceRePo projectSrouceRePo : projectSourceTableData) {
            li = new LinkedList<>();
            li.add(dept.getName());
            li.add(projectSrouceRePo.getStatusMsg());
            li.add(projectSrouceRePo.getProjectName());
            li.add(projectSrouceRePo.getSourceName());
            li.add(projectSrouceRePo.getTime());
            li.add(projectSrouceRePo.getCount());
            li.add(projectSrouceRePo.getDayBaseRatio());
            recordList.add(li);
        }

        ExcelUtil.exportExcel("项目来源分析.xlsx", "项目来源分析", projectSourExcelTitles, recordList, response);

    }

    /**
     * 项目转化分析
     */
    @RequestMapping(value = "projectTransform", method = RequestMethod.GET)
    public String projectTransform(Model model, HttpServletRequest request) {
        String dateViewType = request.getParameter("dateViewType");
        String projectId = request.getParameter("projectId");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String projectName = request.getParameter("projectName");

        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        ProjectListRequest projectReq = new ProjectListRequest();
        projectReq.setPaging(new Page(Integer.MAX_VALUE));
        HashMap<String, Object> map = new HashMap<>();
        map.put("EQ_cityName", dept.getName());
        projectReq.setSearchParams(map);
        ProjectListResponse projectRsp = project.getProjectList(projectReq);
        List<ProjectEntity> projectList = projectRsp.getObjectList();
        model.addAttribute("projects", projectList);

        String projectIds = request.getParameter("projectIds") == null ? "" : request.getParameter("projectIds");
        String projectNames = request.getParameter("projectNames") == null ? "" : request.getParameter("projectNames");

        if (projectNames.endsWith(",")) {
            projectNames = projectNames.substring(0, projectNames.length() - 1);
        }
        if (projectIds.endsWith(",")) {
            projectIds = projectIds.substring(1, projectIds.length() - 1);
        }

        List<String> projectNameList = Arrays.asList(projectNames.split(","));
        List<Integer> projectIdList = new LinkedList<>();
        String[] split = projectIds.split(",");
        if (!Strings.isNullOrEmpty(projectIds)) {
            for (String str : split) {
                projectIdList.add(Integer.valueOf(str));
            }
        }
        for (ProjectEntity entity : projectList) {
            for (Integer pid : projectIdList) {
                if (entity.getId().intValue() == pid) {
                    entity.setFlag(true);
                }
            }
        }

        if (!Strings.isNullOrEmpty(projectIds)) {
            projectId = projectIds;
        }

        Map<String, String> paraMap = new HashMap<>();
        paraMap.put("dateViewType", dateViewType);
        paraMap.put("projectId", projectId);
        paraMap.put("startTime", startTime);
        paraMap.put("endTime", endTime);
        model.addAttribute("projectIds", projectIdList);
        model.addAttribute("projectNames", projectNameList);
        if (org.apache.commons.lang3.StringUtils.isBlank(projectName)) {
            projectName = "请输入楼盘名";
        }

        paraMap.put("projectName", projectName);

        if (dateViewType == null) {
            model.addAttribute("searchParams", paraMap);
            return getAutoUrl();
        }

        List<List<String>> projectTransResult = getProjectTransResult(dateViewType, projectId, startTime, endTime,
                model);

        model.addAttribute("searchParams", paraMap);
        model.addAttribute("countList", projectTransResult);
        return getAutoUrl();
    }

    /**
     * 项目转化分析EXCEL
     */
    @RequestMapping(value = "/projectTransformExcel", method = RequestMethod.GET)
    public void projectTransformExcel(
            Model model, HttpServletRequest request, HttpServletResponse response
    ) {

        List<List<Object>> recordList = new ArrayList<>();

        String dateViewType = request.getParameter("dateViewType");
        String projectId = request.getParameter("projectId");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");

        List<List<String>> projectTransResult = getProjectTransResult(dateViewType, projectId, startTime, endTime,
                model);
        List<Object> temp;
        for (List<String> list : projectTransResult) {
            temp = new LinkedList<>();
            temp.addAll(list);
            recordList.add(temp);
        }

        ExcelUtil.exportExcel("项目转化分析.xlsx", "项目转化分析", projectTranExcelTitles, recordList, response);

    }

    private List<List<String>> getProjectTransResult(
            String dateViewType, String projectId, String startTime, String endTime, Model model
    ) {
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("projectId", projectId);

        Map<String, Long> countMap = new HashMap<>();
        for (CustomerStatusEnum customerStatusEnum : Constant.CustomerStatusEnum.getItemList()) {
            countMap.put(customerStatusEnum.getStatus() + "", 0L);
        }

        paraMap.put("sameStatus", "sameStatus");
        SimpleDateFormat sdf;
        try {
            if (dateViewType.equals("1")) {
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraMap.put("startTime", startTime);
                    paraMap.put("endTime", sdf.format(DateUtil.getNextDay(sdf.parse(endTime))));
                }
                if (!StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    paraMap.put("startTime", startTime);
                    paraMap.put("endTime", sdf.format(DateUtil.getNextDay(sdf.parse(startTime))));
                }
                if (StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraMap.put("startTime", endTime);
                    paraMap.put("endTime", sdf.format(DateUtil.getNextDay(sdf.parse(endTime))));
                }
                if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    String now = sdf.format(DateUtil.addDays(new Date(), -1));
                    paraMap.put("startTime", now);
                    paraMap.put("endTime", sdf.format(DateUtil.getNextDay(sdf.parse(now))));
                }
            } else if (dateViewType.equals("2")) {
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraMap.put("startTime", sdf.format(DateUtil.getNowWeekMonday(sdf.parse(startTime))));
                    paraMap.put("endTime", sdf.format(DateUtil.getNextWeekMonday(sdf.parse(endTime))));
                }
                if (!StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    paraMap.put("startTime", sdf.format(DateUtil.getNowWeekMonday(sdf.parse(startTime))));
                    paraMap.put("endTime", sdf.format(DateUtil.getNextWeekMonday(sdf.parse(startTime))));
                }
                if (StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraMap.put("startTime", sdf.format(DateUtil.getNowWeekMonday(sdf.parse(endTime))));
                    paraMap.put("endTime", sdf.format(DateUtil.getNextWeekMonday(sdf.parse(endTime))));
                }
                if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    String now = sdf.format(DateUtil.addWeeks(new Date(), -1));
                    paraMap.put("startTime", sdf.format(DateUtil.getNowWeekMonday(sdf.parse(now))));
                    paraMap.put("endTime", sdf.format(DateUtil.getNextWeekMonday(sdf.parse(now))));
                }
            } else {
                sdf = new SimpleDateFormat("yyyy-MM");
                if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraMap.put("startTime", sdf.format(DateUtil.getNowMonthFirstDay(sdf.parse(startTime))));
                    paraMap.put("endTime", sdf.format(DateUtil.getNextMonthFirstDay(sdf.parse(endTime))));
                }
                if (!StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    paraMap.put("startTime", sdf.format(DateUtil.getNowMonthFirstDay(sdf.parse(startTime))));
                    paraMap.put("endTime", sdf.format(DateUtil.getNextMonthFirstDay(sdf.parse(startTime))));
                }
                if (StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
                    paraMap.put("startTime", sdf.format(DateUtil.getNowMonthFirstDay(sdf.parse(endTime))));
                    paraMap.put("endTime", sdf.format(DateUtil.getNextMonthFirstDay(sdf.parse(endTime))));
                }
                if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
                    String now = sdf.format(DateUtil.addMonths(new Date(), -1));
                    paraMap.put("startTime", sdf.format(DateUtil.getNowMonthFirstDay(sdf.parse(now))));
                    paraMap.put("endTime", sdf.format(DateUtil.getNextMonthFirstDay(sdf.parse(now))));
                }
            }

            model.addAttribute("startDate", paraMap.get("startTime"));
            model.addAttribute("endDate",
                    sdf.format(DateUtil.getLastDay(sdf.parse(String.valueOf(paraMap.get("endTime"))))));
        } catch (ParseException e) {
            LOGGER.error(e.getMessage(), e);
        }

        List<Map<String, Long>> projectTransform = customerStatusLog.getProjectTransform(paraMap);
        String status;
        Long num;
        Long numOrigin;
        for (Map<String, Long> map : projectTransform) {
            status = String.valueOf(map.get("status"));
            num = map.get("num");
            numOrigin = countMap.get(status);
            countMap.put(status, num + numOrigin);
        }

        List<List<String>> result = new LinkedList<>();
        List<String> temp;
        for (CustomerStatusEnum customerStatusEnum : Constant.CustomerStatusEnum.getItemList()) {
            temp = new LinkedList<>();
            if (customerStatusEnum == Constant.CustomerStatusEnum.RECORDED) {
                temp.add(Constant.CustomerStatusEnum.RECORDED.getMsg());
                temp.add("-");
                temp.add(divResult(countMap.get("2"), countMap.get("1")));
                temp.add(divResult(countMap.get("3"), countMap.get("1")));
                temp.add(divResult(countMap.get("4"), countMap.get("1")));
                temp.add(divResult(countMap.get("5"), countMap.get("1")));
                temp.add(divResult(countMap.get("6"), countMap.get("1")));
            } else if (customerStatusEnum == Constant.CustomerStatusEnum.VISITED) {
                temp.add(Constant.CustomerStatusEnum.VISITED.getMsg());
                temp.add("-");
                temp.add("-");
                temp.add(divResult(countMap.get("3"), countMap.get("2")));
                temp.add(divResult(countMap.get("4"), countMap.get("2")));
                temp.add(divResult(countMap.get("5"), countMap.get("2")));
                temp.add(divResult(countMap.get("6"), countMap.get("2")));
            } else if (customerStatusEnum == Constant.CustomerStatusEnum.ORDERED) {
                temp.add(Constant.CustomerStatusEnum.ORDERED.getMsg());
                temp.add("-");
                temp.add("-");
                temp.add("-");
                temp.add(divResult(countMap.get("4"), countMap.get("3")));
                temp.add(divResult(countMap.get("5"), countMap.get("3")));
                temp.add(divResult(countMap.get("6"), countMap.get("3")));
            } else if (customerStatusEnum == Constant.CustomerStatusEnum.BUY) {
                temp.add(Constant.CustomerStatusEnum.BUY.getMsg());
                temp.add("-");
                temp.add("-");
                temp.add("-");
                temp.add("-");
                temp.add(divResult(countMap.get("5"), countMap.get("4")));
                temp.add(divResult(countMap.get("6"), countMap.get("4")));
            } else if (customerStatusEnum == Constant.CustomerStatusEnum.SING) {
                temp.add(Constant.CustomerStatusEnum.SING.getMsg());
                temp.add("-");
                temp.add("-");
                temp.add("-");
                temp.add("-");
                temp.add("-");
                temp.add(divResult(countMap.get("6"), countMap.get("5")));
            } else if (customerStatusEnum == Constant.CustomerStatusEnum.CANCEL) {
                temp.add(Constant.CustomerStatusEnum.CANCEL.getMsg());
                temp.add("-");
                temp.add("-");
                temp.add("-");
                temp.add("-");
                temp.add("-");
                temp.add("-");
            }
            result.add(temp);
        }
        return result;
    }

    private String divResult(Long num1, Long num2) {
        if (num2 == 0) {
            return "-";
        }
        if (num1 == 0) {
            return "0%";
        }
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.0");
        double temp = ((num1 * 1.0) / num2) * 100;
        return df.format(temp) + "%";
    }


    /**
     * 外呼日报统计
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "callDailyStatistic", method = RequestMethod.GET)
    public String callDailyStatistic(Model model, HttpServletRequest request) {
        try {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
            if (org.apache.commons.lang3.StringUtils.isBlank(startTime) && org.apache.commons.lang3.StringUtils.isBlank(endTime)) {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DATE, -1);
                Date d = cal.getTime();
                SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
                //获取昨天日期
                String yesterday = sp.format(d);
                startTime = yesterday + " 00:00:00";
                endTime = yesterday + " 23:59:59";
            } else {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
            }

            String cityId = dept.getCityID();
            CityDepConfigListRequest cdlr = new CityDepConfigListRequest();
            Map<String, Object> cdm = new HashMap<>(10);
            cdm.put("EQ_city", cityId);
            cdlr.setSearchParams(cdm);
            CityDepConfigListResponse cr = cityDepConfig.getCityDepConfigList(cdlr);

            DepartmentListRequest dlr = new DepartmentListRequest();
            Page dPage = new Page(Integer.MAX_VALUE);
            List<DepartmentEntity> departmentEntities = new ArrayList<>();

            if (CollectionUtils.isNotEmpty(cr.getObjectList())) {
                List<CityDepConfigEntity> cityDepList = cr.getObjectList();
                model.addAttribute("cityDepList", cityDepList);
                CityDepConfigEntity cd = cityDepList.get(0);
                String dc = cd.getDept();
                Map<String, Object> deptMap = new HashMap<>(10);
                deptMap.put("IN_ids", Lists.newArrayList(dc.split(",")));
                dlr.setParamMap(deptMap);
                dlr.setOrderColumn("name");
                dlr.setOrderMode("asc");
                dlr.setSearchParams(deptMap);
                dlr.setPaging(dPage);
                departmentEntities = department.getDepartmentList(dlr).getObjectList();
            } else {
                model.addAttribute("cityDepList", Collections.emptyList());
            }
            model.addAttribute("departmentList", departmentEntities);

            List<UserEntity> userEntities = new ArrayList<>();

            List<CallDailyEntity> callDailyList = new ArrayList<>();
            String[] queryDepart = request.getParameterValues("department") == null ? new String[]{} : request.getParameterValues("department");
            String[] queryUser = request.getParameterValues("user") == null ? new String[]{} : request.getParameterValues("user");

            setNewList(callDailyList, queryDepart, queryUser, startTime, endTime, cityId, departmentEntities);
            // 设置页面多选框选中效果
            setPageSelectedFlag3(departmentEntities, userEntities, queryDepart, queryUser);

            model.addAttribute("queryUser", Joiner.on(",").join(queryUser));
            model.addAttribute("tableData", callDailyList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询外呼日报分析失败", e);
        }
        return getAutoUrl();
    }

    private int setCount(List<Map<String, Object>> list, int count) {
        for (Map<String, Object> m : list) {
            String disposition = m.get("disposition").toString();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(disposition) && "ANSWERED".equals(disposition)) {
                count++;
            }
        }
        return count;
    }

    private int setTimeCount(List<Map<String, Object>> list, int timeCount) {
        for (Map<String, Object> m : list) {
            String disposition = m.get("disposition").toString();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(disposition) && "ANSWERED".equals(disposition)) {
                int billsec = Integer.parseInt(m.get("billsec").toString());
                timeCount += billsec;
            }
        }
        return timeCount;
    }

    @RequestMapping(value = "callDailyStatisticExcel", method = RequestMethod.GET)
    public void callDailyStatisticExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            final String[] excelTitles = {"部门", "姓名", "外呼总量", "成功接通量", "累计时长（分钟）"};
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
            String cityId = dept.getCityID();

            List<CallDailyEntity> callDailyList = new ArrayList<>();
            String[] queryDepart = request.getParameterValues("department") == null ? new String[]{} : request.getParameterValues("department");
            String[] queryUser = request.getParameterValues("user") == null ? new String[]{} : request.getParameterValues("user");
            List<DepartmentEntity> departmentEntities = new ArrayList<>();

            CityDepConfigListRequest cdlr = new CityDepConfigListRequest();
            Map<String, Object> cdm = new HashMap<>(10);
            cdm.put("EQ_city", cityId);
            cdlr.setSearchParams(cdm);
            CityDepConfigListResponse cr = cityDepConfig.getCityDepConfigList(cdlr);
            DepartmentListRequest dlr = new DepartmentListRequest();
            Page dPage = new Page(Integer.MAX_VALUE);
            if (CollectionUtils.isNotEmpty(cr.getObjectList())) {
                List<CityDepConfigEntity> cityDepList = cr.getObjectList();
                CityDepConfigEntity cd = cityDepList.get(0);
                String dc = cd.getDept();
                Map<String, Object> deptMap = new HashMap<>(10);
                deptMap.put("IN_ids", Lists.newArrayList(dc.split(",")));
                dlr.setParamMap(deptMap);
                dlr.setOrderColumn("name");
                dlr.setOrderMode("asc");
                dlr.setSearchParams(deptMap);
                dlr.setPaging(dPage);
                departmentEntities = department.getDepartmentList(dlr).getObjectList();
            }
            setNewList(callDailyList, queryDepart, queryUser, startTime, endTime, cityId, departmentEntities);

            List<List<Object>> recordList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(callDailyList)) {
                for (CallDailyEntity entity : callDailyList) {
                    List<Object> record = new ArrayList<>();
                    record.add(entity.getDeptName());
                    record.add(entity.getUserName());
                    record.add(entity.getCallCount());
                    record.add(entity.getSuccessCount());
                    record.add(entity.getCallDuration());
                    recordList.add(record);
                }
            }
            Date date = new Date();
            SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
            String day = sp.format(date);
            String name = "外呼统计分析_" + day + ".xlsx";
            ExcelUtil.exportExcel(name, "外呼统计分析", excelTitles, recordList, response);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导出外呼统计分析报表失败", e);
        }
    }

    private void setList(List<CallDailyEntity> callDailyList, String[] queryDepart, String[] queryUser, String startTime, String endTime, String cityId) {
        //判断选择部门
        if (queryDepart.length > 0 && !"all".equals(queryDepart[0])) {
            for (String s : queryDepart) {
                DepartmentEntity departmentEntity = department.queryById(Integer.parseInt(s));
                String urlPath = departmentEntity.getUrlPath();
                //判断选择部门且选择人员的情况
                if (queryUser.length > 0 && !"all".equals(queryUser[0])) {
                    for (String userId : queryUser) {
                        UserEntity userEntity = user.getById(Integer.parseInt(userId));
                        String deptUrlPath = userEntity.getDeptUrlPath();
                        //判断该职员是否在其部门下
                        if (deptUrlPath.contains(urlPath)) {
                            CallDailyEntity entity = new CallDailyEntity();
                            Map<String, Object> callMap = new HashMap<>(10);
                            callMap.put("id", Integer.parseInt(userId));
                            callMap.put("startTime", startTime);
                            callMap.put("endTime", endTime);
                            callMap.put("urlPath", urlPath);
                            List<Map<String, Object>> list = statusSourceStatistics.queryByUserId(callMap);
                            int count = 0;
                            int timeCount = 0;
                            entity.setDeptName(departmentEntity.getName());
                            entity.setUserName(userEntity.getRealName());
                            if (CollectionUtils.isNotEmpty(list)) {
                                count = setCount(list, count);
                                timeCount = setTimeCount(list, timeCount);
                                entity.setCallCount(list.size());
                                entity.setSuccessCount(count);
                                entity.setCallDuration(Math.round(timeCount / 60));
                            } else {
                                entity.setCallCount(0);
                                entity.setSuccessCount(0);
                                entity.setCallDuration(0);
                            }
                            callDailyList.add(entity);
                        }
                    }
                } else {
                    CallDailyEntity entity = new CallDailyEntity();
                    //判断选择部门但是没有选择人员
                    Map<String, Object> callMap = new HashMap<>(10);
                    callMap.put("id", Integer.parseInt(s));
                    callMap.put("startTime", startTime);
                    callMap.put("endTime", endTime);
                    List<Map<String, Object>> list = statusSourceStatistics.queryByDept(callMap);
                    int count = 0;
                    int timeCount = 0;
                    entity.setDeptName(departmentEntity.getName());
                    entity.setUserName("");
                    if (CollectionUtils.isNotEmpty(list)) {
                        count = setCount(list, count);
                        timeCount = setTimeCount(list, timeCount);
                        entity.setCallCount(list.size());
                        entity.setSuccessCount(count);
                        entity.setCallDuration(Math.round(timeCount / 60));
                    } else {
                        entity.setCallCount(0);
                        entity.setSuccessCount(0);
                        entity.setCallDuration(0);
                    }
                    callDailyList.add(entity);
                }
            }
        } else {
            //选择全部部门，且同时选择人员的时候
            if (queryUser.length > 0 && !"all".equals(queryUser[0])) {
                for (String userId : queryUser) {
                    UserEntity userEntity = user.getById(Integer.parseInt(userId));
                    DepartmentEntity departmentEntity = department.queryById(userEntity.getDeptId());
                    CallDailyEntity entity = new CallDailyEntity();
                    Map<String, Object> callMap = new HashMap<>(10);
                    callMap.put("id", Integer.parseInt(userId));
                    callMap.put("startTime", startTime);
                    callMap.put("endTime", endTime);
                    List<Map<String, Object>> list = statusSourceStatistics.queryByUserId(callMap);
                    int count = 0;
                    int timeCount = 0;
                    entity.setDeptName(departmentEntity.getName());
                    entity.setUserName(userEntity.getRealName());
                    if (CollectionUtils.isNotEmpty(list)) {
                        count = setCount(list, count);
                        timeCount = setTimeCount(list, timeCount);
                        entity.setCallCount(list.size());
                        entity.setSuccessCount(count);
                        entity.setCallDuration(Math.round(timeCount / 60));
                    } else {
                        entity.setCallCount(0);
                        entity.setSuccessCount(0);
                        entity.setCallDuration(0);
                    }
                    callDailyList.add(entity);
                }
            } else {
                //选择全部部门，没有选择人员
                Map<String, Object> callMap = new HashMap<>(10);
                callMap.put("id", cityId);
                callMap.put("startTime", startTime);
                callMap.put("endTime", endTime);
                List<Map<String, Object>> callList = statusSourceStatistics.queryByDept(callMap);
                if (CollectionUtils.isNotEmpty(callList)) {
                    CallDailyEntity entity = new CallDailyEntity();
                    int count = 0;
                    int timeCount = 0;
                    count = setCount(callList, count);
                    timeCount = setTimeCount(callList, timeCount);
                    entity.setDeptName("全部");
                    entity.setUserName("");
                    entity.setCallCount(callList.size());
                    entity.setSuccessCount(count);
                    entity.setCallDuration(Math.round(timeCount / 60));
                    callDailyList.add(entity);
                }
            }
        }

    }

    private void setNewList(List<CallDailyEntity> callDailyList, String[] queryDepart, String[] queryUser, String startTime, String endTime, String cityId, List<DepartmentEntity> departList) {
        //判断选择部门
        if (queryDepart.length > 0) {
            //判断选择的为全部部门
            if ("all".equals(queryDepart[0])) {
                //判断选择人的情况
                if (queryUser.length > 0) {
                    //判断选择全部人员的情况
                    if ("all".equals(queryUser[0])) {
                        List<UserEntity> allList = new ArrayList<>();
                        for (DepartmentEntity departmentEntity : departList) {
                            Map<String, Object> userMap = new HashMap<>(10);
                            userMap.put("deptUrlPath", departmentEntity.getUrlPath());
                            List<UserEntity> userList = user.queryByConditions(userMap);
                            allList.addAll(userList);
                        }
                        allList = removeDuplicate(allList);
                        if (CollectionUtils.isNotEmpty(allList)) {
                            for (UserEntity entity1 : allList) {
                                DepartmentEntity departmentEntity = department.queryById(entity1.getDeptId());
                                CallDailyEntity dailyEntity = new CallDailyEntity();
                                Map<String, Object> callMap = new HashMap<>(10);
                                callMap.put("id", entity1.getId());
                                callMap.put("startTime", startTime);
                                callMap.put("endTime", endTime);
                                List<Map<String, Object>> dailyList = statusSourceStatistics.queryByUserId(callMap);
                                int count = 0;
                                int timeCount = 0;
                                dailyEntity.setDeptName(departmentEntity.getName());
                                dailyEntity.setUserName(entity1.getRealName());
                                if (CollectionUtils.isNotEmpty(dailyList)) {
                                    count = setCount(dailyList, count);
                                    timeCount = setTimeCount(dailyList, timeCount);
                                    dailyEntity.setCallCount(dailyList.size());
                                    dailyEntity.setSuccessCount(count);
                                    dailyEntity.setCallDuration(Math.round(timeCount / 60));
                                } else {
                                    dailyEntity.setCallCount(0);
                                    dailyEntity.setSuccessCount(0);
                                    dailyEntity.setCallDuration(0);
                                }
                                callDailyList.add(dailyEntity);
                            }
                        }
                    } else {
                        for (String userId : queryUser) {
                            UserEntity userEntity = user.getById(Integer.parseInt(userId));
                            DepartmentEntity departmentEntity = department.queryById(userEntity.getDeptId());
                            CallDailyEntity entity = new CallDailyEntity();
                            Map<String, Object> callMap = new HashMap<>(10);
                            callMap.put("id", Integer.parseInt(userId));
                            callMap.put("startTime", startTime);
                            callMap.put("endTime", endTime);
                            List<Map<String, Object>> list = statusSourceStatistics.queryByUserId(callMap);
                            int count = 0;
                            int timeCount = 0;
                            entity.setDeptName(departmentEntity.getName());
                            entity.setUserName(userEntity.getRealName());
                            if (CollectionUtils.isNotEmpty(list)) {
                                count = setCount(list, count);
                                timeCount = setTimeCount(list, timeCount);
                                entity.setCallCount(list.size());
                                entity.setSuccessCount(count);
                                entity.setCallDuration(Math.round(timeCount / 60));
                            } else {
                                entity.setCallCount(0);
                                entity.setSuccessCount(0);
                                entity.setCallDuration(0);
                            }
                            callDailyList.add(entity);
                        }
                    }
                } else {
                    //没有选择人员
                    Map<String, Object> callMap = new HashMap<>(10);
                    callMap.put("id", cityId);
                    callMap.put("startTime", startTime);
                    callMap.put("endTime", endTime);
                    List<Map<String, Object>> callList = statusSourceStatistics.queryByDept(callMap);
                    if (CollectionUtils.isNotEmpty(callList)) {
                        CallDailyEntity entity = new CallDailyEntity();
                        int count = 0;
                        int timeCount = 0;
                        count = setCount(callList, count);
                        timeCount = setTimeCount(callList, timeCount);
                        entity.setDeptName("全部");
                        entity.setUserName("全部");
                        entity.setCallCount(callList.size());
                        entity.setSuccessCount(count);
                        entity.setCallDuration(Math.round(timeCount / 60));
                        callDailyList.add(entity);
                    }
                }
            } else {
                //选择其他部门的情况
                if (queryUser.length > 0) {
                    //判断选择全部人员的情况
                    if ("all".equals(queryUser[0])) {
                        List<UserEntity> userAllList = new ArrayList<>();
                        for (String s : queryDepart) {
                            DepartmentEntity departmentEntity = department.queryById(Integer.parseInt(s));
                            String urlPath = departmentEntity.getUrlPath();
                            Map<String, Object> userMap = new HashMap<>(10);
                            userMap.put("deptUrlPath", urlPath);
                            List<UserEntity> userList = user.queryByConditions(userMap);
                            if (CollectionUtils.isNotEmpty(userList)) {
                                userAllList.addAll(userList);
                            }
                        }
                        userAllList = removeDuplicate(userAllList);
                        if (CollectionUtils.isNotEmpty(userAllList)) {
                            for (UserEntity entity1 : userAllList) {
                                DepartmentEntity departmentEntity = department.queryById(entity1.getDeptId());
                                CallDailyEntity dailyEntity = new CallDailyEntity();
                                Map<String, Object> callMap = new HashMap<>(10);
                                callMap.put("id", entity1.getId());
                                callMap.put("startTime", startTime);
                                callMap.put("endTime", endTime);
                                List<Map<String, Object>> dailyList = statusSourceStatistics.queryByUserId(callMap);
                                int count = 0;
                                int timeCount = 0;
                                dailyEntity.setDeptName(departmentEntity.getName());
                                dailyEntity.setUserName(entity1.getRealName());
                                if (CollectionUtils.isNotEmpty(dailyList)) {
                                    count = setCount(dailyList, count);
                                    timeCount = setTimeCount(dailyList, timeCount);
                                    dailyEntity.setCallCount(dailyList.size());
                                    dailyEntity.setSuccessCount(count);
                                    dailyEntity.setCallDuration(Math.round(timeCount / 60));
                                } else {
                                    dailyEntity.setCallCount(0);
                                    dailyEntity.setSuccessCount(0);
                                    dailyEntity.setCallDuration(0);
                                }
                                callDailyList.add(dailyEntity);
                            }
                        }

                    } else {
                        for (String userId : queryUser) {
                            UserEntity userEntity = user.getById(Integer.parseInt(userId));
                            DepartmentEntity departmentEntity = department.queryById(userEntity.getDeptId());

                            CallDailyEntity entity = new CallDailyEntity();
                            Map<String, Object> callMap = new HashMap<>(10);
                            callMap.put("id", Integer.parseInt(userId));
                            callMap.put("startTime", startTime);
                            callMap.put("endTime", endTime);
                            List<Map<String, Object>> list = statusSourceStatistics.queryByUserId(callMap);
                            int count = 0;
                            int timeCount = 0;
                            entity.setDeptName(departmentEntity.getName());
                            entity.setUserName(userEntity.getRealName());
                            if (CollectionUtils.isNotEmpty(list)) {
                                count = setCount(list, count);
                                timeCount = setTimeCount(list, timeCount);
                                entity.setCallCount(list.size());
                                entity.setSuccessCount(count);
                                entity.setCallDuration(Math.round(timeCount / 60));
                            } else {
                                entity.setCallCount(0);
                                entity.setSuccessCount(0);
                                entity.setCallDuration(0);
                            }
                            callDailyList.add(entity);

                        }
                    }
                } else {
                    for (String s : queryDepart) {
                        DepartmentEntity departmentEntity = department.queryById(Integer.parseInt(s));
                        CallDailyEntity entity = new CallDailyEntity();
                        //判断选择部门但是没有选择人员
                        Map<String, Object> callMap = new HashMap<>(10);
                        callMap.put("id", Integer.parseInt(s));
                        callMap.put("startTime", startTime);
                        callMap.put("endTime", endTime);
                        List<Map<String, Object>> list = statusSourceStatistics.queryByDept(callMap);
                        int count = 0;
                        int timeCount = 0;
                        entity.setDeptName(departmentEntity.getName());
                        entity.setUserName("全部");
                        if (CollectionUtils.isNotEmpty(list)) {
                            count = setCount(list, count);
                            timeCount = setTimeCount(list, timeCount);
                            entity.setCallCount(list.size());
                            entity.setSuccessCount(count);
                            entity.setCallDuration(Math.round(timeCount / 60));
                        } else {
                            entity.setCallCount(0);
                            entity.setSuccessCount(0);
                            entity.setCallDuration(0);
                        }
                        callDailyList.add(entity);
                    }
                }
            }
        }

    }


    private static List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }

    /**
     * 销售转化报表统计
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/salesConversionReport")
    public String salesConversionReport(Model model, HttpServletRequest request) {
        try {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
            if (org.apache.commons.lang3.StringUtils.isBlank(startTime) && org.apache.commons.lang3.StringUtils.isBlank(endTime)) {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DATE, -1);
                Date d = cal.getTime();
                SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
                //获取昨天日期
                String yesterday = sp.format(d);
                startTime = yesterday + " 00:00:00";
                endTime = yesterday + " 23:59:59";
            } else {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
            }

            String cityId = dept.getCityID();
            CityDepConfigListRequest cdlr = new CityDepConfigListRequest();
            Map<String, Object> cdm = new HashMap<>(10);
            cdm.put("EQ_city", cityId);
            cdlr.setSearchParams(cdm);
            CityDepConfigListResponse cr = cityDepConfig.getCityDepConfigList(cdlr);

            DepartmentListRequest dlr = new DepartmentListRequest();
            Page dPage = new Page(Integer.MAX_VALUE);
            List<DepartmentEntity> departmentEntities = new ArrayList<>();

            if (cr.getObjectList() != null && CollectionUtils.isNotEmpty(cr.getObjectList())) {
                List<CityDepConfigEntity> cityDepList = cr.getObjectList();
                model.addAttribute("cityDepList", cityDepList);
                CityDepConfigEntity cd = cityDepList.get(0);
                String dc = cd.getDept();
                Map<String, Object> deptMap = new HashMap<>(10);
                deptMap.put("IN_ids", Lists.newArrayList(dc.split(",")));
                dlr.setParamMap(deptMap);
                dlr.setOrderColumn("name");
                dlr.setOrderMode("asc");
                dlr.setSearchParams(deptMap);
                dlr.setPaging(dPage);
                departmentEntities = department.getDepartmentList(dlr).getObjectList();
            } else {
                model.addAttribute("cityDepList", Collections.emptyList());
            }
            model.addAttribute("departmentList", departmentEntities);

            List<UserEntity> userEntities = new ArrayList<>();

            List<Map<String, String>> salesList = new ArrayList<>();
            String[] queryDepart = request.getParameterValues("department") == null ? new String[]{} : request.getParameterValues("department");
            String[] queryUser = request.getParameterValues("user") == null ? new String[]{} : request.getParameterValues("user");

            setSalesList(salesList, queryDepart, queryUser, startTime, endTime, departmentEntities);
            // 设置页面多选框选中效果
            setPageSelectedFlag3(departmentEntities, userEntities, queryDepart, queryUser);

            model.addAttribute("queryUser", Joiner.on(",").join(queryUser));
            model.addAttribute("tableData", salesList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询销售转化报表失败", e);
        }
        return getAutoUrl();
    }

    @RequestMapping(value = "/salesConversionReportExcel")
    public void salesConversionReportExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            final String[] excelTitles = {"部门", "安家顾问", "私客总量", "已跟进量", "AB类", "约看", "到访", "到访转化率", "认筹", "认筹转化率", "认购", "认购转化率", "签约", "签约转化率", "退房"};
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";

            String cityId = dept.getCityID();
            CityDepConfigListRequest cdlr = new CityDepConfigListRequest();
            Map<String, Object> cdm = new HashMap<>(10);
            cdm.put("EQ_city", cityId);
            cdlr.setSearchParams(cdm);
            CityDepConfigListResponse cr = cityDepConfig.getCityDepConfigList(cdlr);

            DepartmentListRequest dlr = new DepartmentListRequest();
            Page dPage = new Page(Integer.MAX_VALUE);
            List<DepartmentEntity> departmentEntities = new ArrayList<>();

            if (cr.getObjectList() != null && CollectionUtils.isNotEmpty(cr.getObjectList())) {
                List<CityDepConfigEntity> cityDepList = cr.getObjectList();
                CityDepConfigEntity cd = cityDepList.get(0);
                String dc = cd.getDept();
                Map<String, Object> deptMap = new HashMap<>(10);
                deptMap.put("IN_ids", Lists.newArrayList(dc.split(",")));
                dlr.setParamMap(deptMap);
                dlr.setOrderColumn("name");
                dlr.setOrderMode("asc");
                dlr.setSearchParams(deptMap);
                dlr.setPaging(dPage);
                departmentEntities = department.getDepartmentList(dlr).getObjectList();
            }

            List<Map<String, String>> salesList = new ArrayList<>();
            String[] queryDepart = request.getParameterValues("department") == null ? new String[]{} : request.getParameterValues("department");
            String[] queryUser = request.getParameterValues("user") == null ? new String[]{} : request.getParameterValues("user");

            setSalesList(salesList, queryDepart, queryUser, startTime, endTime, departmentEntities);
            List<List<Object>> recordList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(salesList)) {
                for (Map<String, String> map : salesList) {
                    List<Object> record = new ArrayList<>();
                    record.add(map.get("deptName"));
                    record.add(map.get("managerName"));
                    record.add(map.get("count"));
                    record.add(map.get("callBackCount"));
                    record.add(map.get("abCount"));

                    record.add(map.get("seeCount"));
                    record.add(map.get("daoCount"));
                    record.add(map.get("daoRate"));
                    record.add(map.get("renCount"));
                    record.add(map.get("renRate"));

                    record.add(map.get("buyCount"));
                    record.add(map.get("buyRate"));
                    record.add(map.get("signCount"));
                    record.add(map.get("signRate"));
                    record.add(map.get("cancelCount"));
                    recordList.add(record);
                }
            }
            Date date = new Date();
            SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
            String day = sp.format(date);
            String name = "销售转化分析_" + day + ".xlsx";
            ExcelUtil.exportExcel(name, "销售转化分析_", excelTitles, recordList, response);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导出销售转化报表失败", e);
        }
    }

    private void setSalesList(List<Map<String, String>> salesList, String[] queryDepart, String[] queryUser, String startTime, String endTime, List<DepartmentEntity> departList) {
        //判断选择部门
        if (queryDepart.length > 0) {
            //判断选择的为全部部门
            if ("all".equals(queryDepart[0])) {
                //判断选择人的情况
                if (queryUser.length > 0) {
                    //判断选择全部人员的情况
                    if ("all".equals(queryUser[0])) {
                        List<UserEntity> allList = new ArrayList<>();
                        for (DepartmentEntity departmentEntity : departList) {
                            Map<String, Object> userMap = new HashMap<>(10);
                            userMap.put("deptUrlPath", departmentEntity.getUrlPath());
                            List<UserEntity> userList = user.queryByConditions(userMap);
                            allList.addAll(userList);
                        }
                        allList = removeDuplicate(allList);
                        if (CollectionUtils.isNotEmpty(allList)) {
                            for (UserEntity userEntity : allList) {
                                String userId = String.valueOf(userEntity.getId());
                                putListData(userId, salesList, startTime, endTime);
                            }
                        }
                    } else {
                        for (String userId : queryUser) {
                            putListData(userId, salesList, startTime, endTime);
                        }
                    }
                } else {
                    //没有选择人员
                    List<Integer> allList = new ArrayList<>();
                    for (DepartmentEntity departmentEntity : departList) {
                        Map<String, Object> userMap = new HashMap<>(10);
                        userMap.put("deptUrlPath", departmentEntity.getUrlPath());
                        List<UserEntity> userList = user.queryByConditions(userMap);
                        if (CollectionUtils.isNotEmpty(userList)) {
                            for (UserEntity entity : userList) {
                                allList.add(entity.getId());
                            }
                        }
                    }
                    allList = removeDuplicate(allList);
                    if (CollectionUtils.isNotEmpty(allList)) {
                        putNewListData(allList, salesList, startTime, endTime, "全部");
                    }
                }
            } else {
                //选择其他部门的情况
                if (queryUser.length > 0) {
                    //判断选择全部人员的情况
                    if ("all".equals(queryUser[0])) {
                        List<UserEntity> userAllList = new ArrayList<>();
                        for (String s : queryDepart) {
                            DepartmentEntity departmentEntity = department.queryById(Integer.parseInt(s));
                            String urlPath = departmentEntity.getUrlPath();
                            Map<String, Object> userMap = new HashMap<>(10);
                            userMap.put("deptUrlPath", urlPath);
                            List<UserEntity> userList = user.queryByConditions(userMap);
                            if (CollectionUtils.isNotEmpty(userList)) {
                                userAllList.addAll(userList);
                            }
                        }
                        userAllList = removeDuplicate(userAllList);
                        if (CollectionUtils.isNotEmpty(userAllList)) {
                            for (UserEntity userEntity : userAllList) {
                                String userId = String.valueOf(userEntity.getId());
                                putListData(userId, salesList, startTime, endTime);
                            }
                        }

                    } else {
                        for (String userId : queryUser) {
                            putListData(userId, salesList, startTime, endTime);
                        }
                    }
                } else {
                    List<Integer> allList = new ArrayList<>();
                    for (String s : queryDepart) {
                        DepartmentEntity departmentEntity = department.queryById(Integer.parseInt(s));
                        String urlPath = departmentEntity.getUrlPath();
                        Map<String, Object> userMap = new HashMap<>(10);
                        userMap.put("deptUrlPath", urlPath);
                        List<UserEntity> userList = user.queryByConditions(userMap);
                        if (CollectionUtils.isNotEmpty(userList)) {
                            for (UserEntity entity : userList) {
                                allList.add(entity.getId());
                            }
                        }
                        allList = removeDuplicate(allList);
                        if (CollectionUtils.isNotEmpty(allList)) {
                            putNewListData(allList, salesList, startTime, endTime, departmentEntity.getName());
                        }
                    }

                }
            }
        }

    }

    private static ArrayList<Map<String, Object>> removeDuplicateList(List<Map<String, Object>> list) {
        Set<Map<String, Object>> set = new TreeSet<>(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return o1.get("phone").toString().compareTo(o2.get("phone").toString());
            }
        });
        set.addAll(list);
        return new ArrayList<>(set);
    }

    private void putListData(String userId, List<Map<String, String>> salesList, String startTime, String endTime) {
        UserEntity userEntity = user.getById(Integer.parseInt(userId));
        DepartmentEntity departmentEntity = department.queryById(userEntity.getDeptId());
        Map<String, String> putMap = new HashMap<>(10);

        Map<String, Object> map = new HashMap<>(10);
        map.put("managerId", userEntity.getId());
        map.put("startTime", startTime);
        map.put("endTime", endTime);

        //获取安家顾问部门
        putMap.put("deptName", departmentEntity.getName());
        //获取安家顾问姓名
        putMap.put("managerName", userEntity.getRealName());

        setCount(map, putMap);
        setCallBackCount(map, putMap);
        setAbCount(map, putMap);

        Map<String, Object> searchMap = new HashMap<>(10);
        searchMap.put("managerId", userEntity.getId());
        searchMap.put("startTime", startTime);
        searchMap.put("endTime", endTime);
        searchMap.put("status", 1);

        int seeCount = setSeeCount(searchMap, putMap);
        int daoCount = setDaoCount(searchMap, putMap, seeCount);
        setRenCount(searchMap, putMap, daoCount);
        setBuyCount(searchMap, putMap, daoCount);
        setSignCount(searchMap, putMap, daoCount);
        setCancelCount(searchMap, putMap);

        salesList.add(putMap);
    }

    private void putNewListData(List<Integer> list, List<Map<String, String>> salesList, String startTime, String endTime, String deptName) {

        Map<String, String> putMap = new HashMap<>(10);

        Map<String, Object> map = new HashMap<>(10);
        map.put("idList", list);
        map.put("startTime", startTime);
        map.put("endTime", endTime);

        //获取安家顾问部门
        putMap.put("deptName", deptName);
        //获取安家顾问姓名
        putMap.put("managerName", "全部");

        setCount(map, putMap);
        setCallBackCount(map, putMap);
        setAbCount(map, putMap);

        Map<String, Object> searchMap = new HashMap<>(10);
        searchMap.put("idList", list);
        searchMap.put("startTime", startTime);
        searchMap.put("endTime", endTime);
        searchMap.put("status", 1);

        int seeCount = setSeeCount(searchMap, putMap);
        int daoCount = setDaoCount(searchMap, putMap, seeCount);
        setRenCount(searchMap, putMap, daoCount);
        setBuyCount(searchMap, putMap, daoCount);
        setSignCount(searchMap, putMap, daoCount);
        setCancelCount(searchMap, putMap);

        salesList.add(putMap);
    }

    private void setCount(Map<String, Object> map, Map<String, String> putMap) {
        List<Map<String, Object>> list = anInterface.queryByManagerId(map);
        if (CollectionUtils.isNotEmpty(list)) {
            list = removeDuplicateList(list);
            //获取客户总量
            putMap.put("count", String.valueOf(list.size()));
        } else {
            putMap.put("count", "0");
        }
    }

    private void setCallBackCount(Map<String, Object> map, Map<String, String> putMap) {
        int callBackCount = anInterface.queryCustomerLogCount(map);
        putMap.put("callBackCount", String.valueOf(callBackCount));

//        List<Map<String, Object>> callBackList = anInterface.queryCustomerLog(map);
//        if (CollectionUtils.isNotEmpty(callBackList)) {
//            callBackList = removeDuplicateList(callBackList);
//            //获取回访数量
//            putMap.put("callBackCount", String.valueOf(callBackList.size()));
//        } else {
//            putMap.put("callBackCount", "0");
//        }
    }

    private void setAbCount(Map<String, Object> map, Map<String, String> putMap) {
        map.put("type", "A");
        List<Map<String, Object>> aList = anInterface.queryByManagerId(map);
        if (CollectionUtils.isNotEmpty(aList)) {
            aList = removeDuplicateList(aList);
            //获取ab类总数
            putMap.put("abCount", String.valueOf(aList.size()));
        } else {
            putMap.put("abCount", "0");
        }
    }

    private int setSeeCount(Map<String, Object> searchMap, Map<String, String> putMap) {
        int count = anInterface.queryCustomerByStatusCount(searchMap);
        putMap.put("seeCount", String.valueOf(count));
        return count;
//        List<Map<String, Object>> seeList = anInterface.queryCustomerByStatus(searchMap);
//        if (CollectionUtils.isNotEmpty(seeList)) {
//            seeList = removeDuplicateList(seeList);
//            //获取约看类总数
//            putMap.put("seeCount", String.valueOf(seeList.size()));
//        } else {
//            putMap.put("seeCount", "0");
//        }
//        return seeList.size();
    }

    private int setDaoCount(Map<String, Object> searchMap, Map<String, String> putMap, int seeCount) {
        searchMap.put("status", 2);
        int daoCount = anInterface.queryCustomerByStatusCount(searchMap);
        putMap.put("daoCount", String.valueOf(daoCount));
        if (seeCount != 0) {
            double d = (double) daoCount / seeCount;
            DecimalFormat df = new DecimalFormat("0.00%");
            String result = df.format(d);
            putMap.put("daoRate", result);
        } else {
            putMap.put("daoRate", "");
        }
        return daoCount;

//        searchMap.put("status", 2);
//        List<Map<String, Object>> daoList = anInterface.queryCustomerByStatus(searchMap);
//        if (CollectionUtils.isNotEmpty(daoList)) {
//            daoList = removeDuplicateList(daoList);
//            int daoCount = daoList.size();
//            //获取到访类总数
//            putMap.put("daoCount", String.valueOf(daoCount));
//            if (seeCount != 0) {
//                double d = (double) daoCount / seeCount;
//                DecimalFormat df = new DecimalFormat("0.00%");
//                String result = df.format(d);
//                putMap.put("daoRate", result);
//            } else {
//                putMap.put("daoRate", "");
//            }
//        } else {
//            putMap.put("daoCount", "0");
//        }
//        return daoList.size();
    }

    private void setRenCount(Map<String, Object> searchMap, Map<String, String> putMap, int daoCount) {
        searchMap.put("status", 3);
        int renCount = anInterface.queryCustomerByStatusCount(searchMap);
        putMap.put("renCount", String.valueOf(renCount));
        if (daoCount != 0) {
            double d = (double) renCount / daoCount;
            DecimalFormat df = new DecimalFormat("0.00%");
            String result = df.format(d);
            putMap.put("renRate", result);
        } else {
            putMap.put("renRate", "");
        }

//        searchMap.put("status", 3);
//        List<Map<String, Object>> renList = anInterface.queryCustomerByStatus(searchMap);
//        if (CollectionUtils.isNotEmpty(renList)) {
//            renList = removeDuplicateList(renList);
//            int renCount = renList.size();
//            //获取认筹类总数
//            putMap.put("renCount", String.valueOf(renCount));
//            if (daoCount != 0) {
//                double d = (double) renCount / daoCount;
//                DecimalFormat df = new DecimalFormat("0.00%");
//                String result = df.format(d);
//                putMap.put("renRate", result);
//            } else {
//                putMap.put("renRate", "");
//            }
//        } else {
//            putMap.put("renCount", "0");
//        }
    }

    private void setBuyCount(Map<String, Object> searchMap, Map<String, String> putMap, int daoCount) {
        searchMap.put("status", 4);
        int buyCount = anInterface.queryCustomerByStatusCount(searchMap);
        putMap.put("buyCount", String.valueOf(buyCount));
        if (daoCount != 0) {
            double d = (double) buyCount / daoCount;
            DecimalFormat df = new DecimalFormat("0.00%");
            String result = df.format(d);
            putMap.put("buyRate", result);
        } else {
            putMap.put("buyRate", "");
        }

//        searchMap.put("status", 4);
//        List<Map<String, Object>> buyList = anInterface.queryCustomerByStatus(searchMap);
//        if (CollectionUtils.isNotEmpty(buyList)) {
//            buyList = removeDuplicateList(buyList);
//            int buyCount = buyList.size();
//            //获取认购类总数
//            putMap.put("buyCount", String.valueOf(buyCount));
//            if (daoCount != 0) {
//                double d = (double) buyCount / daoCount;
//                DecimalFormat df = new DecimalFormat("0.00%");
//                String result = df.format(d);
//                putMap.put("buyRate", result);
//            } else {
//                putMap.put("buyRate", "");
//            }
//        } else {
//            putMap.put("buyCount", "0");
//        }
    }

    private void setSignCount(Map<String, Object> searchMap, Map<String, String> putMap, int daoCount) {
        searchMap.put("status", 5);
        int signCount = anInterface.queryCustomerByStatusCount(searchMap);
        putMap.put("signCount", String.valueOf(signCount));
        if (daoCount != 0) {
            double d = (double) signCount / daoCount;
            DecimalFormat df = new DecimalFormat("0.00%");
            String result = df.format(d);
            putMap.put("signRate", result);
        } else {
            putMap.put("signRate", "");
        }

//        searchMap.put("status", 5);
//        List<Map<String, Object>> signList = anInterface.queryCustomerByStatus(searchMap);
//        if (CollectionUtils.isNotEmpty(signList)) {
//            signList = removeDuplicateList(signList);
//            int signCount = signList.size();
//            //获取签约类总数
//            putMap.put("signCount", String.valueOf(signCount));
//            if (daoCount != 0) {
//                double d = (double) signCount / daoCount;
//                DecimalFormat df = new DecimalFormat("0.00%");
//                String result = df.format(d);
//                putMap.put("signRate", result);
//            } else {
//                putMap.put("signRate", "");
//            }
//        } else {
//            putMap.put("signCount", "0");
//        }
    }

    private void setCancelCount(Map<String, Object> searchMap, Map<String, String> putMap) {
        searchMap.put("status", 6);
        int cancelCount = anInterface.queryCustomerByStatusCount(searchMap);
        putMap.put("cancelCount", String.valueOf(cancelCount));

//        searchMap.put("status", 6);
//        List<Map<String, Object>> cancelList = anInterface.queryCustomerByStatus(searchMap);
//        if (CollectionUtils.isNotEmpty(cancelList)) {
//            cancelList = removeDuplicateList(cancelList);
//            //获取退房类总数
//            putMap.put("cancelCount", String.valueOf(cancelList.size()));
//        } else {
//            putMap.put("cancelCount", "0");
//        }
    }

    /**
     * 成交状态报表统计
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/transactionStatusReport")
    public String transactionStatusReport(Integer number, Model model, HttpServletRequest request) {
        try {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            String city = dept.getDescripition();
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(startTime) && org.apache.commons.lang3.StringUtils.isNotBlank(endTime)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
            }
            Page page = new Page(20);
            if (null != number) {
                page.setCurrentPage(number);
            }
            CustomerProjectListRequest listRequest = new CustomerProjectListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            MapListResponse response = customerProject.list(listRequest, city, startTime, endTime);
            model.addAttribute("page", response.getPaging());
            model.addAttribute("dataList", response.getObjectList());
        } catch (Exception e) {
            logger.error("查询成交状态报表失败", e);
        }
        return getAutoUrl();
    }

    /**
     * 云迹客户报表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/cloudCusReport")
    public String cloudCusReport(Model model, HttpServletRequest request) {
        try {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            String city = dept.getDescripition();
            searchParams.put("city", city);
            searchParams.put("userId", userEntity.getId());
            List<CloudCountEntity> list = activityInterface.reportList(searchParams);
            model.addAttribute("dataList", list);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询云迹报表失败", e);
        }
        return getAutoUrl();
    }
}
