/**
 * Description: 客户信息控制器
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-19 下午 16:32:23
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-19   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.house365.beans.common.HGSConstant;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CustomerProjectStatusDetailVo;
import com.house365.beans.vo.CustomerProjectStatusProgressVo;
import com.house365.beans.vo.CustomerProjectVo;
import com.house365.beans.vo.CustomerVo;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.cached.RedisUtilsInterface;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.*;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.*;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.*;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户信息控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-19
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController {

    private static final String SEPARATOR = ",";
    private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private IAttachmentInterface attachmentInterface;
    /**
     * 自动注入客户信息WS实现
     */
    @Autowired
    private ICustomer customer;
    @Autowired
    private ICustomerProject customerProject;
    @Autowired
    private IProject project;
    @Autowired
    private IDepartment department;
    @Autowired
    private IUser user;
    @Autowired
    private ICustomerCallbackLog customerCallbackLog;
    @Autowired
    private ICustomerStatusLog customerStatusLog;

    @Autowired
    private ICustomerSource customerSource;
    @Autowired
    private IMarketCustomer marketCustomer;

    @Autowired
    private IDictionary dictionary;

    @Autowired
    private RedisUtilsInterface redisUtils;

    @Autowired
    private ICityCallInterface callInterface;
    @Autowired
    private ICustomerLogInterface logInterface;

    @Autowired
    private ICustomerCallbackTemplate customerCallbackTemplate;
    @Autowired
    private MergeCustomerUtil mergeCustomerUtil;
    @Autowired
    private IClearData dataService;
    @Autowired
    private ICloudCustomerInterface cloudCustomerInterface;


    /**
     * 去新增客户信息（原数据公海中新增使用，已遗弃）
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model) {
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增客户信息（原数据公海中新增使用，已遗弃）
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCustomer(@Valid CustomerVo vo, BindingResult result, Model model) {
        CustomerEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                CustomerSourceEntity cse = customerSource.getCustomerSourceById(entity.getActSourceId()).getEntity();
                entity.setActSource(cse == null ? "" : cse.getSourceName());
                entity.setCrmSync("0");
                CustomerRequest request = new CustomerRequest();
                request.setEntity(entity);
                CustomerResponse response = customer.addCustomer(request);
                Integer id = response.getEntity().getId();
                return "redirect:/customer/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 去查看客户信息
     *
     * @param id 客户信息页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        CustomerResponse response = customer.getCustomerById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改客户信息
     *
     * @param id 客户信息页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        CustomerResponse response = customer.getCustomerById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改客户信息
     *
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateCustomer(@Valid CustomerVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
                                 Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        CustomerEntity entity = vo.getEntity();
        String phone = request.getParameter("phone");
        model.addAttribute("entity", entity);

        // 表单验证无误,进行提交
        try {
            String action = request.getParameter("action");

            CustomerEntity db = customer.getCustomerById(entity.getId()).getEntity();
            db.setName(entity.getName());
            if (!Strings.isNullOrEmpty(entity.getBakPhone1())) {
                db.setBakPhone1(entity.getBakPhone1());
            }
            if (!Strings.isNullOrEmpty(entity.getBakPhone2())) {
                db.setBakPhone2(entity.getBakPhone2());
            }
            if (!Strings.isNullOrEmpty(entity.getBakPhone3())) {
                db.setBakPhone3(entity.getBakPhone3());
            }
            if (!Strings.isNullOrEmpty(entity.getBuyIntention())) {
                db.setBuyIntention(entity.getBuyIntention());
            }
            if (null != entity.getSex()) {
                db.setSex(entity.getSex());
            }
            db.setTraceStatus(entity.getTraceStatus() != null ? entity.getTraceStatus() : 1);
            //备注字段用作保存最近1条回访记录
            db.setRemark(entity.getRemark());
            db.setBuyIntention(entity.getBuyIntention());
            db.setUpdater(userEntity.getName());
            db.setUpdateTime(new Date());
            CustomerRequest customerRequest = new CustomerRequest();
            customerRequest.setEntity(db);
            customer.updateCustomerNew(customerRequest, userEntity.getId(), userEntity.getRealName());

            // E invalid
            if (HGSConstant.BUYINTENTIONENUM.E.getCode().equalsIgnoreCase(db.getBuyIntention())) {
                //删除合并客户
                List<CustomerEntity> customerList = customer.getDetailCustomers(phone, entity.getManagerId());
                customer.deleteSingleCustomer(entity);
                //合并前客户回公海
                for (CustomerEntity customerentity : customerList) {
                    customer.removeCustomer(customerentity.getId(), userEntity.getId());
                }
//                customer.removeCustomer(id, userEntity.getId());
//                return "redirect:/customer/myCustomer";
                return "redirect:/customermanagement/myCustomerNew";
            }

            //只读
            if ("view".equalsIgnoreCase(action)) {
                return "redirect:/customer/viewCustomerInfo?customerId=" + entity.getId();
            }
            redirectAttributes.addAttribute("message", "更新成功");
            return "redirect:/customer/customerInfo?action=edit&customerId=" + entity.getId();
        } catch (Exception ex) {
            addErrorMessage(model, ex.getMessage());
            model.addAttribute("action", "edit");
            return getAutoUrl("form");
        }
    }

    /**
     * 查询公海客户信息
     *
     * @param request 请求对象
     * @return 结果视图
     */
//    @RequestMapping(value = "", method = RequestMethod.GET)
//    public String list(Integer number, String type, Model model, HttpServletRequest request) {
//        // 获取查询条件
//        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
//        Page page = new Page(100);
//        if (null != number) {
//            page.setCurrentPage(number);
//        }
//
//        //共多少条数据，今日新增多少条
//        //当前部门 所在城市ID
//        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
//                SessionConstants.SESSION_CURRNET_DEPT_KEY);
//        String cityId = departmentEntity.getCityID();
//
//        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
//        String cityCode = departmentResponse.getEntity().getDescripition();
//        House365RestResponse<Map<String, Object>> seaSummary = customer.getSeaSummary(cityCode);
//        model.addAttribute("summary", seaSummary.getData().getEntity());
//
//        if (searchParams.containsKey("GTE_createTimeStart")) {
//            searchParams.put("GTE_createTimeStart", searchParams.get("GTE_createTimeStart") + " 00:00:00");
//        }
//        if (searchParams.containsKey("LTE_createTimeEnd")) {
//            searchParams.put("LTE_createTimeEnd", searchParams.get("LTE_createTimeEnd") + " 23:59:59");
//        }
//
//        // 购房意向
//        if (searchParams.containsKey("EQ_buyIntention")) {
//            if ("".equalsIgnoreCase(searchParams.get("EQ_buyIntention").toString())) {//待定
//                searchParams.remove("EQ_buyIntention");
//                searchParams.put("EQ_buyIntentionIsNull", "1");
//            }
//            if ("all".equalsIgnoreCase(String.valueOf(searchParams.get("EQ_buyIntention")))) {//全部
//                searchParams.remove("EQ_buyIntention");
//            }
//        }
//        searchParams.put("EQ_cityCode", cityCode);
//        searchParams.put("ISNULL_managerId", "");
//        searchParams.put("EQ_isDelete", "0");
//        List buyIntentionQuery = new ArrayList();
//        if ("1".equals(type)) {
//            // CRM导入
//            searchParams.put("EQ_createSource", "CRM导入");
//            //非待定非全部，不需要过滤
//            searchParams.put("NOTEQ_eIntention", "5");
//            searchParams.put("EQ_isRecycled", "0");
//
//        } else if ("2".equals(type)) {
//            // 系统回收
//            searchParams.put("EQ_isRecycled", "1");
//            //非待定非全部，不需要过滤
//            searchParams.put("NOTEQ_eIntention", "5");
//        } else if ("3".equals(type)) {
//            // 无效客户
//            buyIntentionQuery.add(HGSConstant.BUYINTENTIONENUM.E.getCode());
//        }
//        searchParams.put("IN_type", buyIntentionQuery);
//
//
//        // 掉公海时间
//        if (searchParams.containsKey("GTE_oceanDateStart") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
//                ("GTE_oceanDateStart")))) {
//            searchParams.put("GTE_oceanDateStart", searchParams.get("GTE_oceanDateStart") + " 00:00:00");
//        }
//        if (searchParams.containsKey("LTE_oceanDateEnd") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
//                ("LTE_oceanDateEnd")))) {
//            searchParams.put("LTE_oceanDateEnd", searchParams.get("LTE_oceanDateEnd") + " 23:59:59");
//        }
//
//        CustomerListRequest listRequest = new CustomerListRequest();
//        listRequest.setOrderColumn("ocean_date");
//        listRequest.setOrderMode("desc");
//        listRequest.setPaging(page);
//        listRequest.setSearchParams(searchParams);
//        CustomerListResponse response = customer.getCustomerList(listRequest);
//
//        //约看项目信息
//        for (CustomerEntity customerEntity : response.getObjectList()) {
//            List<String> projectNames = new ArrayList<>();
//            ProjectListResponse projectListResponse = project.queryCustomerProject(customerEntity.getId());
//            for (ProjectEntity projectEntity : projectListResponse.getObjectList()) {
//                projectNames.add(projectEntity.getProjectName());
//            }
//            customerEntity.setProjectNames(projectNames);
//            if (!Strings.isNullOrEmpty(customerEntity.getPhone())) {
//                String[] phones = customerEntity.getPhone().split(",");
//                Set<String> phoneSet = new HashSet<>();
//                for (String phone : phones) {
//                    if (!Strings.isNullOrEmpty(phone)) {
//                        if (phone.length() > 4) {
//                            phoneSet.add(phone.substring(0, 3) + "****" + phone.substring(7, phone.length()));
//                        }
//                    }
//                }
//                customerEntity.setPhone(Joiner.on(",").join(phoneSet));
//            }
//        }
//
//        // 处理前台显示客户类型
//        handleDisplayCustomerType(response.getObjectList());
//
//        model.addAttribute("page", response.getPaging());
//        model.addAttribute("type", type);
//        model.addAttribute("customers", response.getObjectList());
//        //未曾使用
//        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
//        return getAutoUrl();
//    }

    /**
     * 查询公海客户信息
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, String type, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(100);
        if (null != number) {
            page.setCurrentPage(number);
        }

        //共多少条数据，今日新增多少条
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();

        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        House365RestResponse<Map<String, Object>> seaSummary = customer.getSeaSummary(cityCode);
        model.addAttribute("summary", seaSummary.getData().getEntity());

        // 购房意向
        if (searchParams.containsKey("buyIntention")) {
            //待定
            if ("dai".equalsIgnoreCase(searchParams.get("buyIntention").toString())) {
                searchParams.put("buyIntentionIsNull", "1");
            }
        }
        searchParams.put("city", cityCode);

        // 掉公海时间
        if (searchParams.containsKey("GTE_oceanDateStart") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get("GTE_oceanDateStart")))) {
            searchParams.put("oceanDateStart", searchParams.get("GTE_oceanDateStart") + " 00:00:00");
        }
        if (searchParams.containsKey("LTE_oceanDateEnd") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get("LTE_oceanDateEnd")))) {
            searchParams.put("oceanDateEnd", searchParams.get("LTE_oceanDateEnd") + " 23:59:59");
        }

        MapListRequest listRequest = new MapListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        MapListResponse response = customer.seaList(listRequest,type);

        //约看项目信息
        if(CollectionUtils.isNotEmpty(response.getObjectList())) {
            for (Map<String, Object> m : response.getObjectList()) {
                int customerId = Integer.parseInt(m.get("id").toString());
                String customerPhone = m.get("phone").toString();
                List<String> projectNames = new ArrayList<>();
                ProjectListResponse projectListResponse = project.queryCustomerProject(customerId);
                for (ProjectEntity projectEntity : projectListResponse.getObjectList()) {
                    projectNames.add(projectEntity.getProjectName());
                }
                m.put("projectNames", projectNames);
                if (org.apache.commons.lang3.StringUtils.isNotBlank(customerPhone)) {
                    String[] phones = customerPhone.split(",");
                    Set<String> phoneSet = new HashSet<>();
                    for (String phone : phones) {
                        if (!Strings.isNullOrEmpty(phone)) {
                            if (phone.length() > 4) {
                                phoneSet.add(phone.substring(0, 3) + "****" + phone.substring(7, phone.length()));
                            }
                        }
                    }
                    m.put("phone", Joiner.on(",").join(phoneSet));
                }

                String createSource = "";
                if (null != m.get("createSource")) {
                    createSource = m.get("createSource").toString();
                }
                // 处理前台显示客户类型
                if (org.apache.commons.lang3.StringUtils.isNotBlank(createSource)) {
                    // createSource='CRM导入'的话不需要做特殊处理
                    if ("CRM拉取".equals(createSource)) {
                        m.put("createSource", "营销活动");
                    } else if ("SYSTEM".equals(createSource) || "WECHAT".equals(createSource)) {
                        m.put("createSource", "手动添加");
                    } else if ("HOTLINE".equals(createSource)) {
                        m.put("createSource", "400来电");
                    } else if ("PT".equals(createSource)) {
                        m.put("createSource", "平台导入");
                    }
                }
            }
        }

        model.addAttribute("page", response.getPaging());
        model.addAttribute("type", type);
        model.addAttribute("customers", response.getObjectList());
        //未曾使用
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 处理前台显示客户类型
     *
     * @param customerList
     */
    private void handleDisplayCustomerType(List<CustomerEntity> customerList) {
        if (CollectionUtils.isNotEmpty(customerList)) {
            for (CustomerEntity customer : customerList) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(customer.getCreateSource())) {
                    // createSource='CRM导入'的话不需要做特殊处理
                    if ("CRM拉取".equals(customer.getCreateSource())) {
                        customer.setCreateSource("营销活动");
                    } else if ("SYSTEM".equals(customer.getCreateSource()) || "WECHAT".equals(customer.getCreateSource())) {
                        customer.setCreateSource("手动添加");
                    } else if ("HOTLINE".equals(customer.getCreateSource())) {
                        customer.setCreateSource("400来电");
                    } else if ("PT".equals(customer.getCreateSource())) {
                        customer.setCreateSource("平台导入");
                    }
                }
            }
        }
    }

    /**
     * 处理前台显示客户类型
     *
     * @param customer
     */
    private void handleDisplayCustomerType(CustomerEntity customer) {

        // createSource='CRM导入'的话不需要做特殊处理
        if (customer != null) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(customer.getCreateSource())) {
                if ("CRM拉取".equals(customer.getCreateSource())) {
                    customer.setCreateSource("营销活动");
                } else if ("SYSTEM".equals(customer.getCreateSource()) || "WECHAT".equals(customer.getCreateSource())) {
                    customer.setCreateSource("手动添加");
                } else if ("HOTLINE".equals(customer.getCreateSource())) {
                    customer.setCreateSource("400来电");
                } else if ("PT".equals(customer.getCreateSource())) {
                    customer.setCreateSource("平台导入");
                }
            }
        }
    }

    /**
     * 派工
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "assignManager", method = RequestMethod.GET)
    public String assignManager(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String customerCount = request.getParameter("customerCount") == null ? "0" : request.getParameter(
                "customerCount");
        //1 multy select user, 0 select single user
        String multyassign = request.getParameter("multyassign") == null ? "0" : request.getParameter("multyassign");

        //当前城市下所有员工
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();

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

        String urlPath = "";
        //是总部员工，选择当前城市和下属所有部门员工 ， 非管理员，选登录用户下属所有部门员工
        if (userEntity.getDeptId() == 1) {
            urlPath = city.getUrlPath();
        } else {
            urlPath = userEntity.getDeptUrlPath() + "/";
        }
        //非随意派工人员
        searchParams.put("LIKE_deptUrlPath", urlPath);
        searchParams.put("EQ_isFreeMan", "0");

        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);
        List<UserEntity> userList = response.getObjectList();

        //可随意派工人员
        getFreeman(userEntity, page, userList);

        if (!userList.contains(userEntity)) {
            userList.add(0, userEntity);
        }

        model.addAttribute("users", userList);
        model.addAttribute("customerCount", customerCount);
        model.addAttribute("multyassign", multyassign);
        return getAutoUrl("assignManager");
    }

    private void getFreeman(UserEntity userEntity, Page page, List<UserEntity> userList) {
        //获取城市下，不限制转移的用户。
        Map<String, Object> freemanQuery = new HashMap<>();
        String str = userEntity.getDeptUrlPath();
        //总部算南京
        if ("/1".equalsIgnoreCase(userEntity.getDeptUrlPath())) {
            str = "/1/2/";
        }

        if (!str.endsWith("/")) {
            str += "/";
        }
        str = str.substring(0, str.indexOf("/", 4));
        freemanQuery.put("REGEXP_deptUrlPath", "^" + str + "$|^" + str + "/");
        freemanQuery.put("EQ_isFreeMan", "1");
        UserListRequest freemanListRequest = new UserListRequest();
        freemanListRequest.setPaging(page);
        freemanListRequest.setOrderColumn("name");
        freemanListRequest.setOrderMode("asc");
        freemanListRequest.setSearchParams(freemanQuery);
        UserListResponse freemanResponse = user.getUserList(freemanListRequest);
        List<UserEntity> freemanList = freemanResponse.getObjectList();

        userList.addAll(0, freemanList);
    }

    private void getFreemanNew(UserEntity userEntity, List<UserEntity> userList) {
        //获取城市下，不限制转移的用户。
        String str = userEntity.getDeptUrlPath();
        //总部算南京
        if ("/1".equalsIgnoreCase(userEntity.getDeptUrlPath())) {
            str = "/1/2/";
        }
        if (!str.endsWith("/")) {
            str += "/";
        }
        str = str.substring(0, str.indexOf("/", 4));
        Map<String, Object> searchMap = new HashMap<>(10);
        searchMap.put("isFreeMan", 1);
        searchMap.put("deptUrlPathNew", "^" + str + "$|^" + str + "/");
        searchMap.put("order", 1);
        List<UserEntity> freemanList = user.queryByConditions(searchMap);

        userList.addAll(0, freemanList);
    }

    /**
     * 客户转移
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "transManager", method = RequestMethod.GET)
    public String transManager(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String customerCount = request.getParameter("customerCount") == null ? "0" : request.getParameter(
                "customerCount");

        //重写查询用户列表提升性能
        Map<String, Object> searchMap = new HashMap<>(10);
        searchMap.put("isFreeMan", 0);
        searchMap.put("deptUrlPath", userEntity.getDeptUrlPath());
        searchMap.put("order", 1);
        List<UserEntity> userList = user.queryByConditions(searchMap);

        //获取城市下，不限制转移的用户。
        getFreemanNew(userEntity, userList);

        model.addAttribute("users", userList);
        model.addAttribute("customerCount", customerCount);
        return getAutoUrl("transManager");
    }

    /**
     * 派工
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "assign", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse assign(HttpServletRequest request) {
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        String type = request.getParameter("type") == null ? "" : request.getParameter("type");
        String assignFrom = request.getParameter("assignFrom") == null ? "" : request.getParameter("assignFrom");

        String userIds = request.getParameter("userIds");
        String customerIds = request.getParameter("customerIds") == null ? "" : request.getParameter("customerIds");
        String[] customerIdArray = customerIds.split(",");
        String[] userIdArray = userIds.split(",");

        try {
            if ("all".equalsIgnoreCase(type)) {//派工所有
                //营销活动派工（marketCustomer 客户列表中派工）
                Map<String, Object> searchParams = new HashMap<>(10);
                String actId = request.getParameter("actid");
                String customerType = request.getParameter("customerType");
                searchParams.put("EQ_activeId", actId);
                String phone = redisUtils.getValByKeyNew("marketCustomer_bind_phone" + userEntity.getId());
                String signupSourceName = redisUtils.getValByKeyNew("marketCustomer_bind_signupSourceName" + userEntity.getId());
                String actSource = redisUtils.getValByKeyNew("marketCustomer_bind_actSource" + userEntity.getId());
                String managerName = redisUtils.getValByKeyNew("marketCustomer_bind_managerName" + userEntity.getId());
                if (org.apache.commons.lang3.StringUtils.isNotBlank(phone) && "null".equals(phone)) {
                    phone = "";
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(signupSourceName) && "null".equals(signupSourceName)) {
                    signupSourceName = "";
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(actSource) && "null".equals(actSource)) {
                    actSource = "";
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(managerName) && "null".equals(managerName)) {
                    managerName = "";
                }
                searchParams.put("LIKE_phone", phone);
                searchParams.put("LIKE_signupSourceName", signupSourceName);
                searchParams.put("LIKE_actSource", actSource);
                searchParams.put("LIKE_managerName", managerName);
                if ("notassignandovertime".equalsIgnoreCase(customerType)) {
                    MarketCustomerListResponse notassignandovertimeResponse = getNotassignandovertimeList(searchParams);
                    List<Integer> customers = new ArrayList<>();
                    for (MarketCustomerEntity customer : notassignandovertimeResponse.getObjectList()) {
                        customers.add(customer.getId());
                    }
                    customer.bindUser(Joiner.on(",").join(customers), userIds, userEntity.getId(), userEntity.getRealName(), 4);
                    restResponse.setMsg(customers.size() + "组数据已经全部派工完成");
                } else if (Strings.isNullOrEmpty(customerType)) {
                    MarketCustomerListResponse notassignResponse = getnotassignList(searchParams);
                    List<Integer> customers = new ArrayList<>();
                    for (MarketCustomerEntity customer : notassignResponse.getObjectList()) {
                        customers.add(customer.getId());
                    }
                    customer.bindUser(Joiner.on(",").join(customers), userIds, userEntity.getId(), userEntity.getRealName(), 4);
                    restResponse.setMsg(customers.size() + "组数据已经全部派工完成");
                } else if ("assigned".equalsIgnoreCase(customerType)) {
                    MarketCustomerListResponse assignResponse = getAssignedList(searchParams);
                    List<Integer> customers = new ArrayList<>();
                    for (MarketCustomerEntity customer : assignResponse.getObjectList()) {
                        customers.add(customer.getId());
                    }
                    customer.bindUser(Joiner.on(",").join(customers), userIds, userEntity.getId(), userEntity.getRealName(), 4);
                    restResponse.setMsg(customers.size() + "组数据已经全部派工完成");
                }
            } else if ("market".equalsIgnoreCase(type)) {
                //convert to customer table （营销活动派工）
                customer.bindUser(customerIds, userIds, userEntity.getId(), userEntity.getRealName(), 4);
                restResponse.setMsg(customerIdArray.length + "组数据已经全部派工完成");
            } else if ("handover".equalsIgnoreCase(type)) {
                // 主管 客户转移按钮
                customer.bindUser(customerIdArray, userIdArray, userEntity.getId(), true, type, assignFrom);
                restResponse.setMsg(customerIdArray.length + "组数据已经全部派工完成");
            } else if ("daihuifang".equalsIgnoreCase(type)) {
                // 待回访列表派工（属于营销活动派工）
                customer.bindUser(customerIdArray, userIdArray, userEntity.getId(), false, type, assignFrom);
                restResponse.setMsg(customerIdArray.length + "组数据已经全部派工完成");
            } else if ("cloud".equalsIgnoreCase(type)) {
                //convert to customer table （云迹活动派工）
                customer.bindCloudUser(customerIds, userIds, userEntity.getId(), userEntity.getRealName(), 9);
                restResponse.setMsg(customerIdArray.length + "组数据已经全部派工完成");
            } else if ("cloudAll".equals(type)) {
                //云迹活动派工所有（查询该活动所有待派客户）
                String actId = request.getParameter("actid");
                Map<String, Object> map = new HashMap<>(5);
                map.put("activeId", actId);
                map.put("type", 1);
                List<CloudCustomerEntity> list = cloudCustomerInterface.queryByConditions(map);
                StringBuilder ids = new StringBuilder();
                if (CollectionUtils.isNotEmpty(list)) {
                    for (int i = 0; i < list.size(); i++) {
                        if (i == list.size() - 1) {
                            ids.append(list.get(i).getId());
                        } else {
                            ids.append(list.get(i).getId()).append(",");
                        }
                    }
                }
                customer.bindCloudUser(ids.toString(), userIds, userEntity.getId(), userEntity.getRealName(), 9);
                restResponse.setMsg(list.size() + "组数据已经全部派工完成");
            } else {
                // 公海派工（在客户公海列表中）
                customer.bindUser(customerIdArray, userIdArray, userEntity.getId(), false, type, assignFrom);
                restResponse.setMsg(customerIdArray.length + "组数据已经全部派工完成");
            }
        } catch (Exception e) {
            restResponse.setResult("0");
            restResponse.setMsg(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return restResponse;
    }

    /**
     * 判断约看客户权限
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/judgeSee")
    @ResponseBody
    public HResult judgeSee(HttpServletRequest request) {
        HResult result = new HResult();
        try {
            String customerId = request.getParameter("customerIds");
            //查询是否有回访记录，如果没有则返回需先添加回访
            boolean flag = false;
            if (org.apache.commons.lang3.StringUtils.isNotBlank(customerId)) {
                String[] customerIds = customerId.split(",");
                if (customerIds.length > 0) {
                    for (int i = 0; i < customerIds.length; i++) {
                        Map<String, Object> map = new HashMap<>(10);
                        map.put("customerId", customerId);
                        List<CustomerCallbackLogEntity> list = customerCallbackLog.queryByConditions(map);
                        if (CollectionUtils.isEmpty(list)) {
                            flag = true;
                            break;
                        }
                    }
                }
            } else {
                result.setStatus(-1);
                result.setErrorMessage("请至少选择一个客户");
            }
            if (flag) {
                result.setStatus(-1);
                result.setErrorMessage("请先添加客户回访，才能约看客户");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("判断约看客户权限失败");
            logger.error("判断约看客户权限失败", e);
        }
        return result;
    }

    /**
     * 项目约看
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "assignProject", method = RequestMethod.GET)
    public String assignProject(Model model, HttpServletRequest request) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String customerId = request.getParameter("customerId");

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

        Map<String, Object> searchParams = new HashMap<>(10);
        Page page = new Page(Integer.MAX_VALUE);
        ProjectListRequest listRequest = new ProjectListRequest();
        listRequest.setPaging(page);
        searchParams.put("EQ_showStatus", "1");
        searchParams.put("EQ_city", city.getDescripition());

        if (!Strings.isNullOrEmpty(customerId) && (customerId.indexOf(",") < 0 || customerId.split(",").length == 1)) {
            if (customerId.contains(",")) {
                customerId = customerId.split(",")[0];
            }
            //single customer
            searchParams.put("EQ_filterExsit", customerId);
        }

        listRequest.setSearchParams(searchParams);
        ProjectListResponse response = project.getProjectList(listRequest);

        if (StringUtils.isNotBlank(customerId)) {
            Map<String, Object> cpMap = new HashMap<>(10);
            cpMap.put("EQ_customerId", "customerId");
            CustomerProjectListRequest customerProjectListRequest = new CustomerProjectListRequest();
            customerProjectListRequest.setSearchParams(cpMap);
            CustomerProjectListResponse customerProjectListResponse = customerProject.getCustomerProjectList(
                    customerProjectListRequest);

            model.addAttribute("addList", customerProjectListResponse.getObjectList());
        }

        model.addAttribute("departments", response.getObjectList());
        return getAutoUrl("assignProject");
    }

    /**
     * 项目客户转移
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "turnProject", method = RequestMethod.GET)
    public String turnProject(Model model, HttpServletRequest request) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String customerId = request.getParameter("customerId");
        String oldProjectId = request.getParameter("oldProjectId");

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

        Map<String, Object> searchParams = new HashMap<>(10);
        Page page = new Page(Integer.MAX_VALUE);
        ProjectListRequest listRequest = new ProjectListRequest();
        listRequest.setPaging(page);
        searchParams.put("EQ_showStatus", "1");
        searchParams.put("EQ_city", city.getDescripition());

//        if (!Strings.isNullOrEmpty(customerId) && (customerId.indexOf(",") < 0 || customerId.split(",").length == 1)) {
//            if (customerId.contains(",")) {
//                customerId = customerId.split(",")[0];
//            }
//            //single customer
//            searchParams.put("EQ_filterExsit", customerId);
//        }

        listRequest.setSearchParams(searchParams);
        ProjectListResponse response = project.getProjectList(listRequest);

        if (StringUtils.isNotBlank(customerId)) {
            Map<String, Object> cpMap = new HashMap<>(10);
            cpMap.put("EQ_customerId", customerId);
            CustomerProjectListRequest customerProjectListRequest = new CustomerProjectListRequest();
            customerProjectListRequest.setSearchParams(cpMap);
            CustomerProjectListResponse customerProjectListResponse = customerProject.getCustomerProjectList(
                    customerProjectListRequest);

            model.addAttribute("addList", customerProjectListResponse.getObjectList());
        }
        if (response != null && response.getObjectList() != null) {
            for (int i = 0; i < response.getObjectList().size(); i++) {
                if (oldProjectId.equals(String.valueOf(response.getObjectList().get(i).getId()))) {
                    response.getObjectList().remove(response.getObjectList().get(i));
                }
            }
        }
        model.addAttribute("departments", response.getObjectList());
        return getAutoUrl("turnProject");
    }

    @RequestMapping(value = "bindProject", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse bindProject(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String projectIds = request.getParameter("projectIds");
        String customerIds = request.getParameter("customerIds");
        try {
            if (!Strings.isNullOrEmpty(projectIds) && !Strings.isNullOrEmpty(customerIds)) {
                customer.bindProject(projectIds, customerIds, userEntity.getName());
            }
        } catch (Exception e) {
            restResponse.setResult("0");
            restResponse.setMsg(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return restResponse;
    }

    @RequestMapping(value = "bindTurnProject", method = RequestMethod.GET)
    @ResponseBody
    public String bindTurnProject(HttpServletRequest request, HttpServletResponse response) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();

        restResponse.setResult("1");
        String projectId = request.getParameter("projectId");
        String customerId = request.getParameter("customerId");
        String oldProjectId = request.getParameter("oldProjectId");
//        String resultMsg ="success";
        try {
            request.setCharacterEncoding("UTF-8");
            // 设置响应的编码格式
            response.setContentType("application/json; charset=utf-8");
            if (!Strings.isNullOrEmpty(projectId) && !Strings.isNullOrEmpty(customerId)) {
                //校验同号码客户
                String msg = customer.bindTurnProject(projectId, customerId, userEntity.getId(), userEntity.getName(), oldProjectId);
                if (!"1".equals(msg)) {
                    return msg;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "1";
    }

    /**
     * 客户详情
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "customerInfo", method = RequestMethod.GET)
    public String customerInfo(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();

        String customerId = request.getParameter("customerId");
        String waitFlag = request.getParameter("waitFlag");
        String managerId = request.getParameter("managerId");
        String action = request.getParameter("action");
        CustomerEntity customerEntity = customer.queryById(Integer.valueOf(customerId));
        if (customerEntity == null) {
            CustomerResponse customerResponse = customer.getCustomerById(Integer.valueOf(customerId));
            if (customerResponse != null && customerResponse.getEntity() != null) {
                customerEntity = customer.getCustomerMerge(customerResponse.getEntity().getPhone(), customerResponse.getEntity().getManagerId());
            }
        }
        //根据新的客户id获取旧表中的id
        Map<String, Object> idMap = new HashMap<>(10);
        idMap.put("phone", customerEntity.getPhone());
        idMap.put("managerId", customerEntity.getManagerId());
        idMap.put("isPrivate", 1);
        List<CustomerEntity> oldList = customer.queryByConditions(idMap);
        model.addAttribute("showPlatCreater", "0");
        List<Integer> customerIdList = new ArrayList<>();
        customerIdList.add(Integer.valueOf(customerId));
        if (CollectionUtils.isNotEmpty(oldList)) {
            for (CustomerEntity e : oldList) {
                customerIdList.add(e.getId());
                if ("8".equals(String.valueOf(e.getCustomerSourceType())) && StringUtils.isNotEmpty(e.getCreater())) {
                    UserEntity tue = user.getById(Integer.valueOf(e.getCreater()));
                    customerEntity.setShowPlatCreater("1");
                    customerEntity.setCreater(tue.getRealName());
                    model.addAttribute("showPlatCreater", "1");
                }
            }
        }

        //获取客户标签
        List<LabelEntity> labelDetailList = user.queryCustomerLabel(null, customerEntity.getId());
        //客户详情展示客户标签
        List<Object> labs = new ArrayList<>();
        if ("1".equals(waitFlag)) {//待回访跳转详情：合并该客户已标记标签
            CustomerResponse resp = customer.getCustomerById(Integer.valueOf(customerId));
            CustomerEntity ce = resp.getEntity();
            if (ce.getPhone() != null && ce.getManagerId() != null) {
                CustomerEntity mergeeEntity = customer.getCustomerMerge(ce.getPhone(), ce.getManagerId());
                if (mergeeEntity != null) {
                    List<LabelEntity> labelDetailList2 = user.queryCustomerLabel(null, mergeeEntity.getId());//当前用户给待回访客户添加的标签
                    if (CollectionUtils.isNotEmpty(labelDetailList2)) {
                        for (LabelEntity oldLabEntity : labelDetailList2) {
                            labs.add(oldLabEntity);
                        }
                    }
                }
            }
        }

        if (CollectionUtils.isNotEmpty(labelDetailList)) {
            model.addAttribute("managerId", customerEntity.getManagerId());
            for (LabelEntity oldLabEntity : labelDetailList) {
                labs.add(oldLabEntity);
            }
        }
        model.addAttribute("labs", labs);

        if (org.apache.commons.lang3.StringUtils.isNotBlank(customerEntity.getCreateSource())) {
            UserUtil.showCreateSource(customerEntity);
        }
        //查询约看项目
        Map<String, Object> cpMap = new HashMap<>(10);
        cpMap.put("idList", customerIdList);
        List<CustomerProjectEntity> cpList = customerProject.queryList(cpMap);
        if (CollectionUtils.isNotEmpty(cpList)) {
            for (CustomerProjectEntity cp : cpList) {
                if (userEntity.getPreLoginTime() != null && cp.getLastChangeStatusTime() != null) {
                    if (userEntity.getPreLoginTime().before(cp.getLastChangeStatusTime())) {
                        cp.setRemark("New!");
                    } else {
                        cp.setRemark("");
                    }
                } else {
                    cp.setRemark("");
                }
            }
        }

        //查询回访记录
        List<CustomerCallbackLogEntity> backLogList = customerCallbackLog.queryByConditions(cpMap);

        // 客户详情展示退回公海时间
        boolean displayBackToSeaDate = false;
        Calendar backToSeaCal = Calendar.getInstance();
        String backToSeaDate = "";
        userEntity.setCity(cityCode);
        //判断是否有城市外呼配置
        if (org.apache.commons.lang3.StringUtils.isNotBlank(cityCode)) {
            List<CityCallConfig> list = callInterface.queryByCity(cityCode);
            if (CollectionUtils.isNotEmpty(list)) {
                model.addAttribute("hasPhone", 1);
            }
        }

        int visitCount = 0;
        displayBackToSeaDate = DictUtil.getBackToSeaTime(customerEntity, userEntity, cpList, backToSeaCal, visitCount, backLogList, displayBackToSeaDate);
        if (displayBackToSeaDate) {
            backToSeaDate = new SimpleDateFormat("yyyy-MM-dd").format(backToSeaCal.getTime());
        }

        // 获取回访内容模板
        CustomerCallbackTemplateListRequest callbackTemplateReq = new CustomerCallbackTemplateListRequest();
        callbackTemplateReq.setPaging(new Page(100));
        Map<String, Object> callbackTemplateParams = new HashMap<>(10);
        callbackTemplateParams.put("EQ_cityKey", cityCode);
        callbackTemplateReq.setSearchParams(callbackTemplateParams);
        CustomerCallbackTemplateListResponse callbackTemplateResponse =
                customerCallbackTemplate.getCustomerCallbackTemplateList(callbackTemplateReq);
        List<CustomerCallbackTemplateEntity> callbackTemplateList = callbackTemplateResponse.getObjectList();

        // 回访内容模板
        model.addAttribute("callbackTemplateList", callbackTemplateList);
        //标签库中当前用户创建的标签
        List<LabelEntity> userLabelList = user.queryUserLabel(userEntity.getId());
        //用户客户标签
        boolean labelFlag = true;
        if (userLabelList != null && userLabelList.size() > 0) {
            model.addAttribute("haslabel", "1");
            model.addAttribute("hasOwnlabel", "1");
            //当前用户给当前客户添加的标签
            List<LabelEntity> hasLabelList1 = user.queryUserCustomerLabel(null, customerEntity.getId());
            //待回访跳转详情：合并该客户已标记标签
            if ("1".equals(waitFlag)) {
                CustomerResponse resp = customer.getCustomerById(Integer.valueOf(customerId));
                CustomerEntity ce = resp.getEntity();
                if (ce.getPhone() != null && ce.getManagerId() != null) {
                    CustomerEntity mergeEntity = customer.getCustomerMerge(ce.getPhone(), ce.getManagerId());
                    if (mergeEntity != null) {
                        //当前用户给待回访客户添加的标签
                        List<LabelEntity> hasLabelList2 = user.queryUserCustomerLabel(null, mergeEntity.getId());
                        hasLabelList1.addAll(hasLabelList2);
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(hasLabelList1)) {
                List<String> lids = new ArrayList<>();
                for (LabelEntity hasLabel : hasLabelList1) {
                    lids.add(hasLabel.getLabelId());
                }
                for (LabelEntity alllabel : userLabelList) {
                    for (LabelEntity hasLabel : hasLabelList1) {
                        if (alllabel.getLabelId().equals(hasLabel.getLabelId())) {
                            alllabel.setSelected("1");
                        }
                    }
                }
                model.addAttribute("lids", lids);
            } else {
                labelFlag = false;
            }
        } else {
            labelFlag = false;
            model.addAttribute("hasOwnlabel", "0");
        }

        /**
         * 用户无权查看完整手机号
         */
        if(userEntity.getShowMobile() == null || userEntity.getShowMobile() != 1) {
            customerEntity.setPhone(MobileUtil.hidePhone(customerEntity.getPhone()));
        }

        model.addAttribute("userLabelList", userLabelList);
        model.addAttribute("labelFlag", labelFlag);
        model.addAttribute("action", action);
        model.addAttribute("callLogs", backLogList);
        model.addAttribute("customerProjects", cpList);
        model.addAttribute("entity", customerEntity);
        model.addAttribute("displayBackToSeaDate", displayBackToSeaDate);
        model.addAttribute("backToSeaDate", backToSeaDate);

        //查询客户日志
        Map<String, Object> map = new HashMap<>(10);
        map.put("phone", customerEntity.getPhone());
        map.put("managerId", customerEntity.getManagerId());
        map.put("idList", customerIdList);
        List<CustomerLogEntity> list = logInterface.queryByConditions(map);
        List<String> logShowList = new ArrayList<>(15);

        UserUtil.addOperateLog(logShowList, list);
        //客户日志列表
        model.addAttribute("logList", logShowList);
        //客户情况来源
        UserUtil.showCreateSource(oldList);

        for (CustomerEntity tempCe : oldList) {
            if ("8".equals(String.valueOf(tempCe.getCustomerSourceType()))) {
                UserEntity tue = user.getById(Integer.valueOf(tempCe.getCreater()));
                tempCe.setCreater(tue.getRealName());
            }
        }
        model.addAttribute("oldList", oldList);
        model.addAttribute("customerId", customerId);
        if (waitFlag != null && !"".equals(waitFlag)) {
            model.addAttribute("waitFlag", waitFlag);
        }
        model.addAttribute("managerId", managerId);
        return getAutoUrl("customerInfo");
    }

    /**
     * 删除客户信息
     *
     * @param id 客户信息页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "deleteHotLineCustomer/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public House365RestResponse deleteHotLineCustomer(@PathVariable Integer id, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        if (null != id && userEntity != null) {
            try {
                CustomerResponse customerResponse = customer.getCustomerById(id);
                CustomerEntity customerEntity = customerResponse.getEntity();
                if (customerEntity != null) {
                    //98:未跟踪
                    if (customerEntity.getStatus() == 98) {
                        //未跟踪400客户原先删除进入私客改为直接删除,1：删除
                        customerEntity.setIsDelete(1);
                    }
                    customerEntity.setStatus(Constant.HotLineStatusEnum.DELETE.getMsg());
                    customerEntity.setUpdateTime(new Date());
                    customerEntity.setUpdater(userEntity.getRealName());

                    CustomerRequest customerRequest = new CustomerRequest();
                    customerRequest.setEntity(customerEntity);
                    customer.updateCustomer(customerRequest, userEntity.getId(), userEntity.getRealName());
                }
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id, HttpServletRequest request) {
        String userId = request.getSession().getAttribute(SessionConstants.THREAD_USERID_KEY).toString();
        String userName = request.getSession().getAttribute(SessionConstants.THREAD_USERNAME_KEY).toString();
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    customer.setDeleteFlag(Integer.valueOf(ids[i]), Integer.parseInt(userId), userName);
                }
            } else {
                customer.setDeleteFlag(Integer.valueOf(id), Integer.parseInt(userId), userName);
            }
        }
    }

    /**
     * 删除客户信息
     *
     * @param id 客户信息页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "remove/{id}", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse remove(@PathVariable Integer id, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        if (null != id && userEntity != null) {
            try {
                customer.removeCustomer(id, userEntity.getId());
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    /**
     * 创建回访纪录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "addCall", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse addCall(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String customerId = request.getParameter("customerId");
        String addType = request.getParameter("addType");
        String addFrom = request.getParameter("addFrom");
        String phone = request.getParameter("phone");
        String managerId = request.getParameter("managerId");
        Date newdate = new Date();

        if (null != customerId && userEntity != null) {
            try {
                String content = request.getParameter("content");
                String buyIntention = request.getParameter("buyIntention");
                String labelIds = request.getParameter("labelIds");
                List<String> labIds = new ArrayList<>();
                String[] lids;
                if (labelIds != null && labelIds.contains(",")) {
                    lids = labelIds.split(",");
                    //标签ids
                    for (String lid : lids) {
                        labIds.add(lid);
                    }
                } else {
                    if (labelIds != null && !"".equals(labelIds)) {
                        lids = new String[1];
                        lids[0] = labelIds;
                        //标签ids
                        for (String lid : lids) {
                            labIds.add(lid);
                        }
                    }

                }

                LabelEntity labelentity = new LabelEntity();
                Map<String, Object> callMap = new HashMap<>(10);
                callMap.put("managerId", managerId);
                callMap.put("phone", phone);
                //先去查询该客户合并id
                CustomerEntity mergeEntity = customer.getMergeCustomerId(callMap);
                //400客户未跟踪添加标记需将标记打在合并后私客上
//                if ("400".equals(addFrom) || "waitCall".equals(addType)) {
//                    if (mergeEntity != null) {
//                        labelentity.setCustomerId(mergeEntity.getId());
//                    } else {
//                        labelentity.setCustomerId(Integer.valueOf(customerId));
//                    }
//                } else {
//                    labelentity.setCustomerId(Integer.valueOf(customerId));
//                }
                //统一处理客户id，防止不是私客列表进入的详情
                if (mergeEntity != null) {
                    labelentity.setCustomerId(mergeEntity.getId());
                } else {
                    labelentity.setCustomerId(Integer.valueOf(customerId));
                }
                //删除旧标签
                labelentity.setManagerId(userEntity.getId());
                user.updateUserCustomerLabel(labelentity);

                //该客户重新绑定该用户下的标签
                List<LabelEntity> paramList = new ArrayList<>();
                CustomerResponse customerResponse = customer.getCustomerById(Integer.valueOf(customerId));
                CustomerEntity customerEntity = customerResponse.getEntity();

                for (String lid : labIds) {
                    LabelEntity le = new LabelEntity();
                    le.setManagerId(userEntity.getId());
                    if ("400".equals(addFrom) || "waitCall".equals(addType)) {
                        le.setCustomerId(labelentity.getCustomerId());
                    } else {
                        le.setCustomerId(Integer.valueOf(customerId));
                    }
                    //查询现有标签,避免添加重复标签
                    le.setLabelId(lid);
                    List<LabelEntity> ids = user.getCustomerLabelIds(le);

                    boolean exists = false;
                    for (LabelEntity tem : ids) {
                        if (tem.getLabelId().equals(String.valueOf(lid))) {
                            exists = true;
                        }
                    }
                    if (!exists) {
                        paramList.add(le);
                    }
                }
                if (paramList.size() > 0) {
                    user.saveCustomersLabels(paramList);
                    paramList.clear();
                }
                labIds.clear();

                int logId = 0;
                customerEntity.setLastCallTime(newdate);
                if (null != customerEntity.getIsWaitCall() && 1 == customerEntity.getIsWaitCall()) {
                    CustomerCallbackLogResponse response = addCallBackWithSource(userEntity, customerId, content, 1, newdate);
                    if (response != null) {
                        logId = response.getEntity().getId();
                    }
                } else {
                    CustomerCallbackLogResponse response = addCallBack(userEntity, customerId, content, newdate);
                    if (response != null) {
                        logId = response.getEntity().getId();
                    }
                }
                customerEntity.setIsWaitCall(0);
                customerEntity.setUpdateTime(newdate);
                customerEntity.setUpdater(userEntity.getRealName());
                customerEntity.setBuyIntention("99".equalsIgnoreCase(buyIntention) ? "" : buyIntention);
                //更新回访记录的时候，同时更新会员备注
                customerEntity.setRemark(content);
                //会员状态 已跟踪 0 跟踪状态为98时，才可以转为已跟踪
                if (Constant.CustomerSourceEnum.HOTLINE.getMsg().equals(customerEntity.getCreateSource())) {
                    if (customerEntity.getStatus().intValue() == Constant.HotLineStatusEnum.INIT.getMsg().intValue()) {
                        //重置客户绑定置业顾问时间
                        customerEntity.setBindTime(newdate);
                        customerEntity.setStatus(Constant.HotLineStatusEnum.NORECORD.getMsg());
                    }
                }
                CustomerRequest customerRequest = new CustomerRequest();
                customerRequest.setEntity(customerEntity);

                //更新客户信息
                customer.updateCustomerNew(customerRequest, userEntity.getId(), userEntity.getRealName());
                //更新合并客户表
                //400跟踪或者待回访客户
                if ("400".equals(addFrom) || "waitCall".equals(addType)) {
                    CustomerEntity oldEntity = customer.getCustomerMerge(customerEntity.getPhone(), customerEntity.getManagerId());
                    if (oldEntity == null) {
                        handleCustomerMerge(customerEntity);
                        customer.saveCustomerMerge(customerEntity);
                        //公海客户查询
                        List<CustomerEntity> seaCustomers = customer.getSeaCustomerByPhone(customerEntity, userEntity);
                        //去公海原顾问名下此客户同步更新
                        if (seaCustomers != null && seaCustomers.size() > 0) {
                            customer.updateSeaCustomerByPhone(customerEntity, userEntity);
                        }
                    } else {
                        if (Constant.CustomerSourceEnum.HOTLINE.getMsg().equals(oldEntity.getCreateSource())) {
                            if (oldEntity.getStatus().intValue() == Constant.HotLineStatusEnum.INIT.getMsg().intValue()) {
                                oldEntity.setStatus(Constant.HotLineStatusEnum.NORECORD.getMsg());
                            }
                        }
                        mergeCustomerUtil.checkMergeCustomer(customerEntity, oldEntity, userEntity.getId(), userEntity.getRealName());
                        handleCustomerMerge(oldEntity);
                        // 意向等级、跟踪状态更新
                        //重置客户绑定置业顾问时间
                        oldEntity.setCreateTime(customerEntity.getCreateTime());
                        oldEntity.setUpdateTime(newdate);
                        oldEntity.setUpdater(String.valueOf(userEntity.getId()));
                        oldEntity.setIsActive(0);
                        oldEntity.setIsHandover(0);
                        customer.updateCustomerMerge(oldEntity);
                    }
                } else {//私客
                    if (!"5".equals(buyIntention)) {//不回公海/私客添加回访
                        // 意向等级、跟踪状态更新
                        customerEntity.setIsHandover(0);
                        customer.updateCustomerMerge4AddCall(customerEntity);
                    }
                }
                //通知CRM
                customer.crmAddCallBack(Integer.valueOf(customerId));
                //更新回访次数
                marketCustomer.addCallbackCount(customerEntity.getId());
                //无效客户回公海
                if (HGSConstant.BUYINTENTIONENUM.E.getCode().equalsIgnoreCase(buyIntention)) {
                    List<CustomerEntity> customerList = customer.getDetailCustomers(customerEntity.getPhone(), customerEntity.getManagerId());
                    //删除合并客户
                    Map<String, Object> idMap = new HashMap<>(10);
                    List<Integer> idList = new ArrayList<>();
                    if (customerList != null) {
                        for (CustomerEntity ce : customerList) {
                            idList.add(ce.getId());
                        }
                    }
                    idMap.put("ids", idList);
                    customer.deleteCustomerMergeById(idMap);
                    //合并前客户回公海
                    if (CollectionUtils.isNotEmpty(customerList)) {
                        for (CustomerEntity customerentity : customerList) {
                            customer.removeCustomer(customerentity.getId(), userEntity.getId());
                        }
                    }
                }
                //放弃客户做操作
                String isGiveUp = request.getParameter("isGiveUp");
                if (org.apache.commons.lang3.StringUtils.isNotBlank(isGiveUp) && "1".equals(isGiveUp)) {
                    customer.abandonCustomer(String.valueOf(customerEntity.getId()), userEntity.getId(), userEntity.getRealName(), logId);
                }
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    /**
     * 客户转移-处理合并客户最近回访时间
     *
     * @param currentCustomer
     * @param oldCustomerEntity
     * @return
     */
    public CustomerEntity handleCustomerMerge(CustomerEntity currentCustomer, CustomerEntity oldCustomerEntity) {
        //先去查询该客户的所有id
        List<CustomerEntity> customerIdList = customer.getCustomerIds(currentCustomer.getId(), currentCustomer.getCityCode());
        //再获取所有id的回访记录
        List<Integer> ids = new ArrayList<>();
        for (CustomerEntity entity : customerIdList) {
            ids.add(entity.getId());
        }
        Map<String, Object> idsMap = new HashMap<>(10);
        idsMap.put("ids", ids);
        if (ids.size() > 0) {
            List<CustomerCallbackLogEntity> callbacklist = customer.getCallBackList(idsMap);
            Date oldCallTime = oldCustomerEntity.getLastCallTime();
            if (callbacklist != null && callbacklist.size() > 0 && oldCallTime.before(callbacklist.get(0).getCreateTime())) {
                oldCustomerEntity.setLastCallTime(callbacklist.get(0).getCreateTime());
            }
        }
        return oldCustomerEntity;
    }

    /**
     * 非客户转移-处理合并最新回访时间
     *
     * @param currentCustomer
     * @return
     */
    public CustomerEntity handleCustomerMerge(CustomerEntity currentCustomer) {
        //先去查询该客户的所有id
        List<CustomerEntity> customerIdList = customer.getCustomerIds(currentCustomer.getId(), currentCustomer.getCityCode());
        //再获取所有id的回访记录
        List<Integer> ids = new ArrayList<>();
        for (CustomerEntity entity : customerIdList) {
            ids.add(entity.getId());
        }
        Map<String, Object> idsMap = new HashMap<>(10);
        idsMap.put("ids", ids);
        if (ids.size() > 0) {
            List<CustomerCallbackLogEntity> callbacklist = customer.getCallBackList(idsMap);
            if (callbacklist != null && callbacklist.size() > 0) {
                currentCustomer.setLastCallTime(callbacklist.get(0).getCreateTime());
            }
        } else {
            currentCustomer.setLastCallTime(null);
        }
        return currentCustomer;
    }

    /**
     * 批量转移客户到公海
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "batchRemove", method = RequestMethod.POST)
    @ResponseBody
    public House365RestResponse batchRemove(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String customerIds = request.getParameter("customerIds");
        if (StringUtils.isNotBlank(customerIds) && userEntity != null) {
            try {
                customer.batchRemoveCustomer(customerIds, userEntity.getId(), userEntity.getRealName());
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    private CustomerCallbackLogResponse addCallBackWithSource(UserEntity userEntity, String customerId, String content, Integer source, Date newdate) {
        CustomerCallbackLogEntity customerCallbackLogEntity = new CustomerCallbackLogEntity();
        customerCallbackLogEntity.setCustomerId(Integer.valueOf(customerId));
        customerCallbackLogEntity.setContent(content);
        customerCallbackLogEntity.setCreater(userEntity.getName());
        customerCallbackLogEntity.setCreateTime(newdate);
        customerCallbackLogEntity.setManagerId(userEntity.getId());
        customerCallbackLogEntity.setManagerName(userEntity.getRealName());
        customerCallbackLogEntity.setSource(source);
        CustomerCallbackLogRequest callRequest = new CustomerCallbackLogRequest();
        callRequest.setEntity(customerCallbackLogEntity);
        CustomerCallbackLogResponse response = customerCallbackLog.addCustomerCallbackLog(callRequest);
        return response;
    }

    private CustomerCallbackLogResponse addCallBack(UserEntity userEntity, String customerId, String content, Date newdate) {
        CustomerCallbackLogEntity customerCallbackLogEntity = new CustomerCallbackLogEntity();
        customerCallbackLogEntity.setCustomerId(Integer.valueOf(customerId));
        customerCallbackLogEntity.setContent(content);
        customerCallbackLogEntity.setCreater(userEntity.getName());
        customerCallbackLogEntity.setCreateTime(newdate);
        customerCallbackLogEntity.setManagerId(userEntity.getId());
        customerCallbackLogEntity.setManagerName(userEntity.getRealName());

        CustomerCallbackLogRequest callRequest = new CustomerCallbackLogRequest();
        callRequest.setEntity(customerCallbackLogEntity);
        CustomerCallbackLogResponse response = customerCallbackLog.addCustomerCallbackLog(callRequest);
        return response;
    }

    @RequestMapping(value = "customerProjectInfo/{cpId}", method = RequestMethod.GET)
    public String customerProjectInfo(Model model, @PathVariable Integer cpId) {
        CustomerProjectResponse cpr = customerProject.getCustomerProjectById(cpId);
        CustomerProjectEntity cp = cpr.getEntity();

        CustomerResponse cr = customer.getCustomerById(cp.getCustomerId());
        CustomerEntity ce = cr.getEntity();

        ProjectResponse projectResponse = project.getProjectById(cp.getProjectId());
        ProjectEntity pe = projectResponse.getEntity();

        Map<String, Object> logMap = new HashMap<>(10);
        logMap.put("EQ_customerId", ce.getId());
        logMap.put("EQ_projectId", pe.getId());
        Page page = new Page(Integer.MAX_VALUE);
        page.setCurrentPage(0);
        CustomerStatusLogListRequest csr = new CustomerStatusLogListRequest();
        csr.setPaging(page);
        csr.setSearchParams(logMap);
        CustomerStatusLogListResponse csl = customerStatusLog.getCustomerStatusLogList(csr);


        List<BaseAttachment> baseAttachments = new ArrayList<>();
        int nextBizType = 0;

        Map<String, Object> searchParams = new HashMap<>();
        AttachmentListRequest attachmentListRequest = new AttachmentListRequest();
        Page page1 = new Page();
        page1.setCurrentPage(1);
        page1.setPageSize(Integer.MAX_VALUE);
        searchParams.put("EQ_resourceId", cp.getId());
        searchParams.put("EQ_resourceType", "hgs_customer_project");
        attachmentListRequest.setOrderColumn("bizType");
        attachmentListRequest.setOrderMode("desc");
        attachmentListRequest.setPaging(page1);
        attachmentListRequest.setSearchParams(searchParams);
        AttachmentListResponse attachmentListResponse = attachmentInterface.getAttachments(attachmentListRequest);
        if (attachmentListResponse != null && attachmentListResponse.getObjectList() != null) {
            baseAttachments = attachmentListResponse.getObjectList();
            if (!baseAttachments.isEmpty()) {
                BaseAttachment attachment = baseAttachments.get(0);
                nextBizType = attachment.getBizType() + 1;
            }
        }

        model.addAttribute("entity", cp);
        model.addAttribute("customer", ce);
        model.addAttribute("project", pe);
        model.addAttribute("logs", csl.getObjectList());
        model.addAttribute("nextBizType", nextBizType);
        model.addAttribute("baseAttachments", baseAttachments);

        return getAutoUrl("projectInfo");
    }

    @RequestMapping(value = "cpUpdate", method = RequestMethod.POST)
    public String cpUpdate(Model model, HttpServletRequest request, CustomerVo vo, CustomerProjectVo cpv) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        CustomerResponse cr = customer.getCustomerById(vo.getCustomer().getId());
        CustomerEntity ce = cr.getEntity();

        CustomerProjectResponse cpr = customerProject.getCustomerProjectById(cpv.getEntity().getId());
        CustomerProjectEntity cp = cpr.getEntity();

        String action = request.getParameter("action");

        ce.setName(vo.getCustomer().getName());
        ce.setUpdater(userEntity.getName());
        ce.setUpdateTime(new Date());

        cp.setConsultantName(cpv.getEntity().getConsultantName());
        cp.setConsultantPhone(cpv.getEntity().getConsultantPhone());
        cp.setRecordedStatus(cpv.getEntity().getRecordedStatus());
        cp.setLoanStatus(cpv.getEntity().getLoanStatus());

        cp.setRequireArea(cpv.getEntity().getRequireArea());
        cp.setRequireHouse(cpv.getEntity().getRequireHouse());
        cp.setRequireHouseType(cpv.getEntity().getRequireHouseType());
        cp.setRequirePrice(cpv.getEntity().getRequirePrice());
        cp.setRemark(cpv.getEntity().getRemark());
        cp.setUpdater(userEntity.getName());
        cp.setUpdateTime(new Date());

        CustomerRequest cre = new CustomerRequest();
        cre.setEntity(ce);

        CustomerProjectRequest cpre = new CustomerProjectRequest();
        cpre.setEntity(cp);

        customer.updateCustomerNew(cre, userEntity.getId(), userEntity.getRealName());
        customerProject.updateCustomerProject(cpre);

        if (!Strings.isNullOrEmpty(action) && "edit".equalsIgnoreCase(action)) {
            return "redirect:/customer/updateProjectInfo/" + cpv.getEntity().getId();
        }
        return "redirect:/customer/customerProjectInfo/" + cp.getId();
    }

    @RequestMapping(value = "newCustomer", method = RequestMethod.GET)
    public String newCustomer(Model model, HttpServletRequest request) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();

        Map<String, Object> csMap = new HashMap<>(10);
        csMap.put("EQ_city", city.getDescripition());
        csMap.put("EQ_status", "1");
        CustomerVo vo = new CustomerVo();
        CustomerEntity ce = new CustomerEntity();
        ce.setCustomerType(1);
        ce.setSex(2);
        vo.setEntity(ce);
        //平台人员
        csMap.clear();
        csMap.put("deptUrlPath", city.getUrlPath());
        //20：平台人员身份
        csMap.put("identityType", "20");
        List<UserEntity> platManagers = user.queryManagers(csMap);

        List<Integer> typeList = Arrays.asList(1, 0);
        Map<String, Object> map = new HashMap<>(10);
        map.put("city", city.getDescripition());
        map.put("status", 1);
        map.put("typeList", typeList);
        List<CustomerSourceEntity> list = customerSource.queryByConditions(map);
        model.addAttribute("sources", list);
        model.addAttribute("platManagers", platManagers);
        model.addAttribute("sources", list);
        model.addAttribute("entity", vo.getEntity());
        return getAutoUrl("newCustomer");
    }

    /**
     * 客户新增 （客户列表添加客户按钮触发）
     *
     * @param model
     * @param request
     * @param vo
     * @return
     */
    @RequestMapping(value = "addNewCustomer", method = RequestMethod.POST)
    public String addNewCustomer(Model model, HttpServletRequest request, CustomerVo vo) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String actSourceType = request.getParameter("actSourceType");
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();
        CustomerEntity customerEntity = vo.getEntity();
        //平台人员
        Integer platManagerId = customerEntity.getManagerId();
        Date newdate = new Date();
        CustomerRequest cr = new CustomerRequest();
        customerEntity.setCreateTime(newdate);
        if (!Strings.isNullOrEmpty(customerEntity.getRemark())) {
            customerEntity.setLastCallTime(newdate);
        }
        if ("1".equals(actSourceType)) {
            customerEntity.setCreater(String.valueOf(platManagerId));
            customerEntity.setCreateSource("PT");
            customerEntity.setCustomerSourceType(8);
        } else {
            customerEntity.setCreater(userEntity.getRealName());
            customerEntity.setCreateSource("SYSTEM");
            customerEntity.setCustomerSourceType(HGSConstant.CustomerSourceType.NORMAL.getType());
        }
        customerEntity.setUpdateTime(newdate);
        customerEntity.setManagerId(userEntity.getId());
        customerEntity.setIsRecycled(0);
        customerEntity.setManagerName(userEntity.getRealName());
        customerEntity.setCityName(city.getName());
        customerEntity.setCityCode(city.getDescripition());
        customerEntity.setCrmSync("0");
        customerEntity.setIsDelete(0);
        customerEntity.setUpdater(userEntity.getName());
        //修改客户表默认值null改为11
        customerEntity.setStatus(Constant.statu);
        customerEntity.setBindTime(newdate);

        CustomerSourceEntity cse = customerSource.getCustomerSourceById(customerEntity.getActSourceId()).getEntity();
        customerEntity.setActSource(cse == null ? "" : cse.getSourceName());
        cr.setEntity(customerEntity);
        CustomerResponse cret = customer.addCustomerNew(cr, userEntity.getId(), userEntity.getRealName());
        CustomerEntity addOldCustomerEntity = cret.getEntity();
        //合并之后的表:更新or新增
        CustomerEntity oldEntity = customer.getCustomerMerge(customerEntity.getPhone(), userEntity.getId());
        if (oldEntity == null) {
            //新旧表Id唯一
            customerEntity.setId(addOldCustomerEntity.getId());
            customer.saveCustomerMerge(customerEntity);
            //公海客户查询
            List<CustomerEntity> seaCustomers = customer.getSeaCustomerByPhone(customerEntity, userEntity);
            //去公海原顾问名下此客户同步更新
            if (CollectionUtils.isNotEmpty(seaCustomers)) {
                customer.updateSeaCustomerByPhone(customerEntity, userEntity);
                for (CustomerEntity c : seaCustomers) {
                    //如果是云迹类型，更新云迹客户managerId
                    if (c.getCustomerSourceType() == 7) {
                        cloudCustomerInterface.updateById(c.getId(), userEntity);
                    }
                }
            }
        } else {
            mergeCustomerUtil.checkMergeCustomer(customerEntity, oldEntity, userEntity.getId(), userEntity.getRealName());
            // 意向等级、跟踪状态更新
            oldEntity.setUpdateTime(newdate);
            oldEntity.setCreateTime(newdate);
            oldEntity.setBindTime(newdate);
            if (!Strings.isNullOrEmpty(customerEntity.getRemark())) {
                oldEntity.setLastCallTime(newdate);
            }
            oldEntity.setUpdater(String.valueOf(userEntity.getId()));
            customerEntity.setId(oldEntity.getId());
            customer.updateCustomerMerge(oldEntity);
        }
        if (!Strings.isNullOrEmpty(customerEntity.getRemark())) {
            addCallBack(userEntity, String.valueOf(customerEntity.getId()), customerEntity.getRemark(), newdate);
        }

        model.addAttribute("vo", vo);
        return "redirect:/customer/customerInfo?action=edit&customerId=" + customerEntity.getId();
    }


    /**
     * 我的400来电客户
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "hotlineList", method = RequestMethod.GET)
    public String hotlineList(Integer number, Model model, HttpServletRequest request) {

        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        String status = String.valueOf(searchParams.get("EQ_status"));
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }

        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();

        //共多少条数据，今日新增多少条
        House365RestResponse<Map<String, Object>> seaSummary = customer.getHotLineSummary(userEntity.getId(),
                departmentEntity.getDescripition());
        model.addAttribute("summary", seaSummary.getData().getEntity());

        //自己和子部门数据
        searchParams.put("EQ_userId", userEntity.getId());
        searchParams.put("EQ_cityCode", cityCode);
        if (StringUtils.isEmpty(status)) {
            searchParams.put("NOTEQ_status", Constant.HotLineStatusEnum.DELETE.getMsg());
        }
        searchParams.put("EQ_createSource", "HOTLINE");
        CustomerListRequest listRequest = new CustomerListRequest();

        // 设定排序
        Object ocObj = request.getParameter("orderColumn");
        Object omObj = request.getParameter("orderMode");
        if (ocObj != null && !"".equals(ocObj.toString().trim()) && omObj != null && !"".equals(
                omObj.toString().trim())) {
            listRequest.setOrderColumn(ocObj.toString());
            listRequest.setOrderMode(omObj.toString());
        } else {
            listRequest.setOrderColumn("create_time");
            listRequest.setOrderMode("desc");
        }

        //用户标签 标签库中当前用户创建的标签
        List<LabelEntity> userLabelList = user.queryUserLabel(userEntity.getId());
        if (userLabelList != null && userLabelList.size() > 0) {
            model.addAttribute("hasOwnlabel", "1");
            model.addAttribute("userLabelList", userLabelList);
        } else {
            model.addAttribute("hasOwnlabel", "0");
        }

        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);

        CustomerListResponse response = customer.getCustomerList(listRequest);
        if (response != null && response.getObjectList() != null) {
            for (CustomerEntity customerEntity : response.getObjectList()) {

                Map<String, Object> callMap = new HashMap<>(10);
                callMap.put("managerId", customerEntity.getManagerId());
                callMap.put("phone", customerEntity.getPhone());
                //先去查询该客户合并id
                CustomerEntity mergerEntity = customer.getMergeCustomerId(callMap);
                if (mergerEntity != null) {
                    //该客户获得的所有标签
                    List<LabelEntity> oldList = user.queryCustomerLabel(null, mergerEntity.getId());
                    //标签当前用户所添加标签选中
                    String markedLabelId = "";
                    if (CollectionUtils.isNotEmpty(userLabelList)) {
                        for (LabelEntity userCreateLabel : userLabelList) {
                            for (LabelEntity oldLabEntity : oldList) {
                                if (userCreateLabel.getLabelId().equals(oldLabEntity.getLabelId())) {
                                    markedLabelId += userCreateLabel.getLabelId() + ",";
                                }
                            }
                        }
                    }
                    if (markedLabelId.contains(",")) {
                        markedLabelId = markedLabelId.substring(0, markedLabelId.length() - 1);
                    }
                    customerEntity.setMarkedLabelId(markedLabelId);
                }
            }
        }

        List<CustomerEntity> customers = response.getObjectList();
        /**
         * 用户无权查看完整手机号
         */
        if(userEntity.getShowMobile() == null || userEntity.getShowMobile() != 1) {
            customers = customers.stream().map(i-> {
                i.setPhone(MobileUtil.hidePhone(i.getPhone()));
                return i;
            }).collect(Collectors.toList());
        }

        model.addAttribute("page", response.getPaging());
        model.addAttribute("customers", customers);

        //未曾使用
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));

        // 获取回访内容模板
        CustomerCallbackTemplateListRequest callbackTemplateReq = new CustomerCallbackTemplateListRequest();
        callbackTemplateReq.setPaging(new Page(100));
        Map<String, Object> callbackTemplateParams = new HashMap<>(5);
        callbackTemplateParams.put("EQ_cityKey", cityCode);
        callbackTemplateReq.setSearchParams(callbackTemplateParams);
        CustomerCallbackTemplateListResponse callbackTemplateResponse =
                customerCallbackTemplate.getCustomerCallbackTemplateList(callbackTemplateReq);
        List<CustomerCallbackTemplateEntity> callbackTemplateList = callbackTemplateResponse.getObjectList();
        // 回访内容模板
        model.addAttribute("callbackTemplateList", callbackTemplateList);
        return getAutoUrl();

    }


    /**
     * 查询客户信息
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "myCustomer", method = RequestMethod.GET)
    public String myCustomer(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }

        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();

        //共多少条数据，今日新增多少条
        House365RestResponse<Map<String, Object>> seaSummary = customer.getSummary(String.valueOf(userEntity.getId()));
        model.addAttribute("summary", seaSummary.getData().getEntity());

        if ("案场报备状态".equalsIgnoreCase(String.valueOf(searchParams.get("EQ_recordedStatus")))) {
            searchParams.remove("EQ_recordedStatus");
        } else if (Strings.isNullOrEmpty(String.valueOf(searchParams.get("EQ_recordedStatus")))) {
            searchParams.remove("EQ_recordedStatus");
            //待定纪录
            searchParams.put("EQ_recordedStatusNull", "1");
        }

        if ("购房意向".equalsIgnoreCase(String.valueOf(searchParams.get("EQ_buyIntention")))) {
            searchParams.remove("EQ_buyIntention");
        } else if (Strings.isNullOrEmpty(String.valueOf(searchParams.get("EQ_buyIntention")))) {
            searchParams.remove("EQ_buyIntention");
            searchParams.put("EQ_buyIntentionIsNull", "1");
        }

        if (searchParams.containsKey("LIKE_name")) {
            searchParams.put("LIKE_likephone", searchParams.get("LIKE_name"));
            searchParams.remove("LIKE_name");
        }
        if (searchParams.containsKey("GTE_createTimeStart") && !Strings.isNullOrEmpty(
                String.valueOf(searchParams.get("GTE_createTimeStart")))) {
            searchParams.put("GTE_createTimeStart", searchParams.get("GTE_createTimeStart") + " 00:00:00");
        }
        if (searchParams.containsKey("LTE_createTimeEnd") && !Strings.isNullOrEmpty(
                String.valueOf(searchParams.get("LTE_createTimeEnd")))) {
            searchParams.put("LTE_createTimeEnd", searchParams.get("LTE_createTimeEnd") + " 23:59:59");
        }

        List<Integer> customerIds = new ArrayList<>();
        //统计信息过滤条件
        String summaryType = request.getParameter("summaryType");
        //是否根据customerid过滤，是的话没有customerids会设置为-1
        boolean filterFlag = false;
        if (!Strings.isNullOrEmpty(summaryType)) {
            filterFlag = true;
            House365RestResponse res = customer.getSummaryIds(summaryType, String.valueOf(userEntity.getId()));
            customerIds = (List<Integer>) res.getData().getEntity();
            model.addAttribute("summaryType", summaryType);
        }

        //满足客户项目过滤条件的
        if (customerIds != null && !customerIds.isEmpty()) {
            searchParams.put("IN_ids", Lists.newArrayList(customerIds));
        } else {
            if (filterFlag) {
                searchParams.put("IN_ids", Lists.newArrayList(-1));
            }
        }

        //自己和子部门数据
        searchParams.put("EQ_userId", userEntity.getId());
        searchParams.put("EQ_cityCode", cityCode);
        searchParams.put("EQ_hotline", "0");

        CustomerListRequest listRequest = new CustomerListRequest();


        // 设定排序
        Object ocObj = request.getParameter("orderColumn");
        Object omObj = request.getParameter("orderMode");
        if (ocObj != null && !"".equals(ocObj.toString().trim()) && omObj != null && !"".equals(
                omObj.toString().trim())) {
            listRequest.setOrderColumn(ocObj.toString());
            listRequest.setOrderMode(omObj.toString());
        } else {
            listRequest.setOrderColumn("create_time");
            listRequest.setOrderMode("desc");
        }

        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CustomerListResponse response = customer.getCustomerList(listRequest);

        //组装客户项目信息
        if (response.getObjectList() != null && !response.getObjectList().isEmpty()) {
            setProjectInfo(userEntity, response);
        }

        model.addAttribute("page", response.getPaging());
        model.addAttribute("customers", response.getObjectList());
        //未曾使用
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 根据客户信息获取客户项目列表
     *
     * @param userEntity
     * @param response
     */
    private void setProjectInfo(UserEntity userEntity, CustomerListResponse response) {
        List<Integer> customerIdList = new ArrayList<>();

        for (CustomerEntity customerEntity : response.getObjectList()) {
            customerIdList.add(customerEntity.getId());
        }

        List<CustomerProjectEntity> customerProjectEntities = new ArrayList<>();

        if (!customerIdList.isEmpty()) {
            Map<String, Object> cpMap = new HashMap<>();
            CustomerProjectListRequest customerProjectListRequest = new CustomerProjectListRequest();
            cpMap.put("EQ_customerIds", customerIdList);
            customerProjectListRequest.setSearchParams(cpMap);
            Page cp = new Page(Integer.MAX_VALUE);
            customerProjectListRequest.setPaging(cp);
            customerProjectListRequest.setOrderColumn(null);
            customerProjectListRequest.setOrderMode(null);

            CustomerProjectListResponse customerProjectListResponse = customerProject.getCustomerProjectList(
                    customerProjectListRequest);
            customerProjectEntities = customerProjectListResponse.getObjectList();
        }

        //客户项目信息
        for (CustomerEntity customerEntity : response.getObjectList()) {
            List<CustomerProjectEntity> cps = new ArrayList<>();
            customerEntity.setBakPhone3("");
            for (CustomerProjectEntity cpe : customerProjectEntities) {
                if (customerEntity.getId().equals(cpe.getCustomerId())) {
                    //增加NEW标识
                    if (userEntity.getPreLoginTime() != null && cpe.getLastChangeStatusTime() != null) {
                        if (userEntity.getPreLoginTime().before(cpe.getLastChangeStatusTime())) {
                            cpe.setRemark("new");
                            customerEntity.setBakPhone3("new");
                        } else {
                            cpe.setRemark("");
                        }
                    } else {
                        cpe.setRemark("");
                    }
                    cps.add(cpe);
                }
            }
            customerEntity.setCps(cps);
        }
    }

    /**
     * 查询约看客户信息
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "myRecordedCustomer", method = RequestMethod.GET)
    public String myRecordedCustomer(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }

        String projectId = request.getParameter("projectId");
        if (org.apache.commons.lang3.StringUtils.isBlank(projectId)) {
            return getAutoUrl();
        }

        //共多少条数据，今日新增多少条，包括重客数据(4.1版本不限制公海数据)
        Map<String, Object> map = new HashMap<>(10);
        map.put("projectId", projectId);
//        map.put("manager", "1");
        List<CustomerProjectEntity> list = customerProject.queryList(map);
        int totalCount = list.size();
        model.addAttribute("totalCount", totalCount);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Map<String, Object> newMap = new HashMap<>(10);
        newMap.put("createTime", calendar.getTime());
        newMap.put("projectId", projectId);
        newMap.put("manager", "1");
        List<CustomerProjectEntity> newList = customerProject.queryList(newMap);
        int newCount = newList.size();
        model.addAttribute("newCount", newCount);

        if ("案场报备状态".equalsIgnoreCase(String.valueOf(searchParams.get("EQ_recordedStatus")))) {
            searchParams.remove("EQ_recordedStatus");
        }

        //过滤项目信息，列表展示非重客数据
        Map<String, Object> cpMap = new HashMap<>(10);
        if (searchParams.containsKey("LIKE_houseName") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get("LIKE_houseName")))) {
            cpMap.put("LIKE_houseName", searchParams.get("LIKE_houseName"));
        }
        if (searchParams.containsKey("EQ_recordedStatus") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get("EQ_recordedStatus")))) {
            cpMap.put("EQ_recordedStatus", searchParams.get("EQ_recordedStatus"));
        }
        if (searchParams.containsKey("EQ_projectStatus") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get("EQ_projectStatus")))) {
            cpMap.put("EQ_status", searchParams.get("EQ_projectStatus"));
        }
        if (searchParams.containsKey("EQ_loanStatus") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get("EQ_loanStatus")))) {
            cpMap.put("EQ_loanStatus", searchParams.get("EQ_loanStatus"));
        }
        if (!Strings.isNullOrEmpty(projectId)) {
            cpMap.put("EQ_projectId", projectId);
        }
        List<Integer> customerIds = new ArrayList<>();
        List<CustomerProjectEntity> customerProjectEntities;
        //1.查询当前项目下客户报备信息
        Page cplp = new Page(Integer.MAX_VALUE);

        CustomerProjectListRequest customerProjectListRequest = new CustomerProjectListRequest();
        customerProjectListRequest.setOrderColumn("create_time");
        customerProjectListRequest.setOrderMode("desc");
        customerProjectListRequest.setSearchParams(cpMap);
        customerProjectListRequest.setPaging(cplp);
        CustomerProjectListResponse customerProjectListResponse = customerProject.getCustomerProjectList(customerProjectListRequest);
        customerProjectEntities = customerProjectListResponse.getObjectList();
        for (CustomerProjectEntity customerProjectEntity : customerProjectEntities) {
            customerIds.add(customerProjectEntity.getCustomerId());
        }

        //过滤客户信息
        if (searchParams.containsKey("LIKE_name")) {
            searchParams.put("LIKE_likephone", searchParams.get("LIKE_name"));
            searchParams.remove("LIKE_name");
        }
        if (searchParams.containsKey("GTE_createTimeStart") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get("GTE_createTimeStart")))) {
            searchParams.put("GTE_createTimeStart", searchParams.get("GTE_createTimeStart") + " 00:00:00");
        }
        if (searchParams.containsKey("LTE_createTimeEnd") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get("LTE_createTimeEnd")))) {
            searchParams.put("LTE_createTimeEnd", searchParams.get("LTE_createTimeEnd") + " 23:59:59");
        }

        CustomerListResponse response = new CustomerListResponse();
        //3.组装客户与客户项目信息
        if (CollectionUtils.isNotEmpty(customerIds)) {
            //私客回公海也可以查询
//            searchParams.put("ISNOTNULL_managerId", "");
            searchParams.put("IN_ids", Lists.newArrayList(customerIds));

            CustomerListRequest listRequest = new CustomerListRequest();
            listRequest.setOrderColumn("field");

            StringBuilder orderModeBuilder = new StringBuilder();
            for (Integer customerId : customerIds) {
                orderModeBuilder.append(String.valueOf(customerId));
                orderModeBuilder.append(SEPARATOR);
            }
            String orderMode = orderModeBuilder.toString();
            orderMode = orderMode.substring(0, orderMode.length() - SEPARATOR.length());
            listRequest.setOrderMode("(id," + orderMode + ")");

            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            response = customer.getCustomerList(listRequest);

            if (CollectionUtils.isNotEmpty(response.getObjectList())) {
                //约看项目信息
                for (CustomerEntity customerEntity : response.getObjectList()) {
                    List<CustomerProjectEntity> cps = new ArrayList<>();

                    for (CustomerProjectEntity cpe : customerProjectEntities) {
                        if (customerEntity.getId().equals(cpe.getCustomerId())) {
                            cps.add(cpe);
                        }
                    }
                    customerEntity.setCps(cps);
                }
                for (int i = 0; i < response.getObjectList().size(); i++) {
                    int isRepeat = response.getObjectList().get(i).getCps().get(0).getIsRepeat();
                    response.getObjectList().get(i).setIsRepeat(isRepeat);

                    String customerPhone = response.getObjectList().get(i).getCps().get(0).getCustomerPhone();
                    int id = response.getObjectList().get(i).getCps().get(0).getId();
                    //判断为重客时，查询主客id
                    if (isRepeat == 1) {
                        Map<String, Object> map1 = new HashMap<>(10);
                        map1.put("projectId", projectId);
                        map1.put("isRepeat", 0);
                        map1.put("customerPhone", customerPhone);
                        map1.put("id", id);
                        List<CustomerProjectEntity> projectList = customerProject.queryList(map1);
                        if (CollectionUtils.isNotEmpty(projectList)) {
                            response.getObjectList().get(i).setMajorId(projectList.get(0).getCustomerId());
                        }
                    }
                }
            }
        }
        ProjectResponse pro = project.getProjectById(Integer.valueOf(projectId));
        if (pro.getEntity() != null) {
            model.addAttribute("projectName", pro.getEntity().getProjectName());
        }

        //4.将查到的不重复项目报备客户总数放入当前分页中
//        response.getPaging().setRecords(totalCount);

        // 处理前台显示客户类型
        handleDisplayCustomerType(response.getObjectList());
        List<CustomerEntity> customers = response.getObjectList();
        /**
         * 用户无权查看完整手机号
         */
        if(userEntity.getShowMobile() == null || userEntity.getShowMobile() != 1) {
            customers = customers.stream().map(i-> {
                i.setPhone(MobileUtil.hidePhone(i.getPhone()));
                return i;
            }).collect(Collectors.toList());
        }

        model.addAttribute("projectId", projectId);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("customers", customers);
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 我的驻场项目 - 客户详情
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "viewCustomerInfo", method = RequestMethod.GET)
    public String viewCustomerInfo(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        String projectId = request.getParameter("projectId");
        String customerId = request.getParameter("customerId");
        String action = request.getParameter("action");
        CustomerResponse customerResponse = customer.getCustomerById(Integer.valueOf(customerId));

        Map<String, Object> cpMap = new HashMap<>(10);
        cpMap.put("EQ_customerId", customerId);
        CustomerProjectListRequest customerProjectListRequest = new CustomerProjectListRequest();
        customerProjectListRequest.setSearchParams(cpMap);
        CustomerProjectListResponse cpl = customerProject.getCustomerProjectList(customerProjectListRequest);
        for (CustomerProjectEntity cpe : cpl.getObjectList()) {
            if (userEntity.getPreLoginTime() != null && cpe.getLastChangeStatusTime() != null) {
                if (userEntity.getPreLoginTime().before(cpe.getLastChangeStatusTime())) {
                    cpe.setRemark("New!");
                } else {
                    cpe.setRemark("");
                }
            } else {
                cpe.setRemark("");
            }
        }


        Page page = new Page(5);
        page.setCurrentPage(0);
        Map<String, Object> callMap = new HashMap<>(10);
        callMap.put("EQ_customerId", customerId);
        CustomerCallbackLogListRequest cclr = new CustomerCallbackLogListRequest();
        cclr.setSearchParams(callMap);
        cclr.setPaging(page);
        CustomerCallbackLogListResponse cc = customerCallbackLog.getCustomerCallbackLogList(cclr);

        model.addAttribute("projectId", projectId);
        model.addAttribute("action", action);
        model.addAttribute("callLogs", cc.getObjectList());
        model.addAttribute("customerProjects", cpl.getObjectList());
        model.addAttribute("entity", customerResponse.getEntity());
        return getAutoUrl("viewCustomerInfo");
    }

    /**
     * 我的驻场项目 - 客户项目详情 读写
     *
     * @param model
     * @param cpId
     * @return
     */
    @RequestMapping(value = "updateProjectInfo/{cpId}", method = RequestMethod.GET)
    public String updateProjectInfo(Model model, @PathVariable Integer cpId,HttpServletRequest request) {

        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        CustomerProjectResponse cpr = customerProject.getCustomerProjectById(cpId);
        CustomerProjectEntity cp = cpr.getEntity();

        CustomerResponse cr = customer.getCustomerById(cp.getCustomerId());
        CustomerEntity ce = cr.getEntity();

        ProjectResponse projectResponse = project.getProjectById(cp.getProjectId());
        ProjectEntity pe = projectResponse.getEntity();

        Map<String, Object> logMap = new HashMap<>(10);
        logMap.put("EQ_customerId", ce.getId());
        logMap.put("EQ_projectId", pe.getId());
        Page page = new Page(Integer.MAX_VALUE);
        page.setCurrentPage(0);
        CustomerStatusLogListRequest csr = new CustomerStatusLogListRequest();
        csr.setPaging(page);
        csr.setSearchParams(logMap);
        CustomerStatusLogListResponse csl = customerStatusLog.getCustomerStatusLogList(csr);
        List<BaseAttachment> baseAttachments = new ArrayList<>();
        int nextBizType = 0;
        //客户项目转移日志
        Map<String, Object> map = new HashMap<>(10);
        List<Integer> customerIdList = new ArrayList<>();
        customerIdList.add(ce.getId());
        map.put("phone", ce.getPhone());
        map.put("managerId", ce.getManagerId());
        map.put("idList", customerIdList);
        map.put("type", 10);//10:项目转移记录
        List<CustomerLogEntity> turnProList = logInterface.queryByConditions(map);


        Map<String, Object> searchParams = new HashMap<>(10);
        AttachmentListRequest attachmentListRequest = new AttachmentListRequest();
        Page page1 = new Page();
        page1.setCurrentPage(1);
        page1.setPageSize(Integer.MAX_VALUE);
        searchParams.put("EQ_resourceId", cp.getId());
        searchParams.put("EQ_resourceType", "hgs_customer_project");
        attachmentListRequest.setOrderColumn("bizType");
        attachmentListRequest.setOrderMode("desc");
        attachmentListRequest.setPaging(page1);
        attachmentListRequest.setSearchParams(searchParams);
        AttachmentListResponse attachmentListResponse = attachmentInterface.getAttachments(attachmentListRequest);
        if (attachmentListResponse != null && CollectionUtils.isNotEmpty(attachmentListResponse.getObjectList())) {
            baseAttachments = attachmentListResponse.getObjectList();
            BaseAttachment attachment = baseAttachments.get(0);
            nextBizType = attachment.getBizType() + 1;
        }

        // 获取跟进阶段数据
        List<CustomerStatusLogEntity> listStatusLog = csl.getObjectList();
        // 最大激活状态ID
        int maxActiveStatusId = -1;
        // 进度条明细
        Map<String, CustomerProjectStatusDetailVo> progressDetail = new HashMap<>(10);


        for (CustomerStatusLogEntity statusLog : listStatusLog) {
            // 过滤掉无效记录
            if (statusLog.getIsDelete() == 0) {
                // 当前记录的to_status_id
                Integer thisStatusId = statusLog.getToStatusId();
                // 找出最大激活状态ID
                if (thisStatusId > maxActiveStatusId) {
                    maxActiveStatusId = thisStatusId;
                }
                // 相同状态ID的记录只取create_time最大的
                if (!progressDetail.containsKey(String.valueOf(thisStatusId)) || progressDetail.get(String.valueOf(thisStatusId))
                        .getCreateTime()
                        .before(statusLog.getCreateTime())) {

                    Date showDate = statusLog.getOccurTime() == null ? statusLog.getCreateTime() : statusLog
                            .getOccurTime();
                    progressDetail.put(String.valueOf(thisStatusId), new CustomerProjectStatusDetailVo(statusLog.getCreater(),
                            showDate));
                }
            }
        }
        if (turnProList != null && turnProList.size() > 0) {
            if (listStatusLog != null && listStatusLog.size() > 0) {
                for (CustomerLogEntity cle : turnProList) {
                    CustomerStatusLogEntity csle = new CustomerStatusLogEntity();
                    csle.setCreateTime(cle.getCreateTime());
                    csle.setOldValue(cle.getOldValue());
                    csle.setNewValue(cle.getNewValue());
                    csle.setCreater(cle.getCreateUserName());
                    for (int j = 0; j < listStatusLog.size(); j++) {
                        if (cle.getCreateTime().after(listStatusLog.get(j).getCreateTime())) {
                            listStatusLog.add(j, csle);
                            break;
                        } else {
                            if (j == listStatusLog.size() - 1) {
                                listStatusLog.add(csle);
                                break;
                            } else {
                                continue;
                            }
                        }
                    }
                }
            } else {
                List<CustomerStatusLogEntity> newLogList = new ArrayList<>();
                for (CustomerLogEntity cle : turnProList) {
                    CustomerStatusLogEntity csle = new CustomerStatusLogEntity();
                    csle.setCreateTime(cle.getCreateTime());
                    csle.setOldValue(cle.getOldValue());
                    csle.setNewValue(cle.getNewValue());
                    csle.setCreater(cle.getCreateUserName());
                    newLogList.add(csle);
                }
                csl.setObjectList(newLogList);
            }

        }
        // 根据customer_status_log的creater到user查realName
        for (Map.Entry<String, CustomerProjectStatusDetailVo> entry : progressDetail.entrySet()) {

            CustomerProjectStatusDetailVo detail = entry.getValue();
            String realName = detail.getCreater();
            Map<String, Object> userSearchParams = new HashMap<>();
            userSearchParams.put("EQ_name", detail.getCreater());
            UserListRequest req = new UserListRequest();
            req.setSearchParams(userSearchParams);
            UserListResponse res = user.getUserList(req);
            if (res.getObjectList() != null && res.getObjectList().size() > 0) {
                realName = res.getObjectList().get(0).getRealName();
            }
            detail.setStatusHandler(realName);
        }
        CustomerProjectStatusProgressVo statusProgress = new CustomerProjectStatusProgressVo(maxActiveStatusId,
                progressDetail);

        // 处理前台显示客户类型
        handleDisplayCustomerType(ce);

        if(userEntity.getShowMobile() == null || userEntity.getShowMobile() != 1) {
            ce.setPhone(MobileUtil.hidePhone(ce.getPhone()));
        }
        model.addAttribute("entity", cp);
        model.addAttribute("customer", ce);
        model.addAttribute("project", pe);
        model.addAttribute("logs", csl.getObjectList());
        model.addAttribute("nextBizType", nextBizType);
        model.addAttribute("baseAttachments", baseAttachments);
        model.addAttribute("statusProgress", statusProgress);

        return getAutoUrl("updateProjectInfo");
    }

    /**
     * 添加客户状态
     *
     * @param model
     * @param cpId
     * @return
     */
    @RequestMapping(value = "assignStatus/{cpId}", method = RequestMethod.GET)
    public String assignStatus(Model model, @PathVariable Integer cpId) {
        CustomerProjectResponse cpr = customerProject.getCustomerProjectById(cpId);
        CustomerProjectEntity cp = cpr.getEntity();
        model.addAttribute("cp", cp);
        model.addAttribute("ct", cp.getStatus());
        model.addAttribute("status", Constant.CustomerStatusEnum.getItemList());
        return getAutoUrl("assignStatus");
    }

    @RequestMapping(value = "changeStatus", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse changeStatus(HttpServletRequest request) throws Exception {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String projectId = request.getParameter("projectId");
        String status = request.getParameter("status");
        String occurTime = request.getParameter("occurTime");
        if (!Strings.isNullOrEmpty(projectId) && !Strings.isNullOrEmpty(status) && userEntity != null && !Strings.isNullOrEmpty(occurTime)) {
            try {
                String remark = request.getParameter("remark");
                CustomerProjectResponse response = customerProject.changeStatus(Integer.valueOf(projectId), userEntity.getName(), Integer.valueOf(status), remark, occurTime);
                if (response != null && !("10000").equals(response.getResultCode())) {
                    restResponse.setResult("0");
                    restResponse.setMsg(response.getResultMessage());
                }
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    /**
     * 获取CRM用户视图地址
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getCRMURL", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse getCRM(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        UserEntity currUser = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String curid = String.valueOf(currUser.getId());
        String curname = currUser.getRealName();
        restResponse.setResult("1");
        String customerId = request.getParameter("customerId");
        if (!Strings.isNullOrEmpty(customerId) && userEntity != null) {
            try {
                House365RestObject<String> hro = new House365RestObject();
                String url = customer.getCRMCustomerURL(Integer.valueOf(customerId), curid, curname, userEntity.getShowMobile());
                hro.setEntity(url);
                restResponse.setData(hro);
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }


    /**
     * 查询客户信息
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "myCustomerNew", method = RequestMethod.GET)
    public String myCustomerNew(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }

        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();

        //共多少条数据，今日新增多少条
        House365RestResponse<Map<String, Object>> seaSummary = customer.getSummary(String.valueOf(userEntity.getId()));
        model.addAttribute("summary", seaSummary.getData().getEntity());

        if ("案场报备状态".equalsIgnoreCase(String.valueOf(searchParams.get("EQ_recordedStatus")))) {
            searchParams.remove("EQ_recordedStatus");
        } else if (Strings.isNullOrEmpty(String.valueOf(searchParams.get("EQ_recordedStatus")))) {
            searchParams.remove("EQ_recordedStatus");
            //待定纪录
            searchParams.put("EQ_recordedStatusNull", "1");
        }

        if ("购房意向".equalsIgnoreCase(String.valueOf(searchParams.get("EQ_buyIntention")))) {
            searchParams.remove("EQ_buyIntention");
        } else if (Strings.isNullOrEmpty(String.valueOf(searchParams.get("EQ_buyIntention")))) {
            searchParams.remove("EQ_buyIntention");
            searchParams.put("EQ_buyIntentionIsNull", "1");
        }

        if (searchParams.containsKey("LIKE_name")) {
            searchParams.put("LIKE_likephone", searchParams.get("LIKE_name"));
            searchParams.remove("LIKE_name");
        }
        if (searchParams.containsKey("GTE_createTimeStart") && !Strings.isNullOrEmpty(
                String.valueOf(searchParams.get("GTE_createTimeStart")))) {
            searchParams.put("GTE_createTimeStart", searchParams.get("GTE_createTimeStart") + " 00:00:00");
        }
        if (searchParams.containsKey("LTE_createTimeEnd") && !Strings.isNullOrEmpty(
                String.valueOf(searchParams.get("LTE_createTimeEnd")))) {
            searchParams.put("LTE_createTimeEnd", searchParams.get("LTE_createTimeEnd") + " 23:59:59");
        }

        List<Integer> customerIds = new ArrayList<>();
        //统计信息过滤条件
        String summaryType = request.getParameter("summaryType");
        //是否根据customerid过滤，是的话没有customerids会设置为-1
        boolean filterFlag = false;
        if (!Strings.isNullOrEmpty(summaryType)) {
            filterFlag = true;
            House365RestResponse res = customer.getSummaryIds(summaryType, String.valueOf(userEntity.getId()));
            customerIds = (List<Integer>) res.getData().getEntity();
            model.addAttribute("summaryType", summaryType);
        }

        //满足客户项目过滤条件的
        if (customerIds != null && !customerIds.isEmpty()) {
            searchParams.put("IN_ids", Lists.newArrayList(customerIds));
        } else {
            if (filterFlag) {
                searchParams.put("IN_ids", Lists.newArrayList(-1));
            }
        }

        //自己和子部门数据
        searchParams.put("EQ_userId", userEntity.getId());
        searchParams.put("EQ_cityCode", cityCode);
        searchParams.put("EQ_hotline", "0");

        CustomerListRequest listRequest = new CustomerListRequest();


        // 设定排序
        Object ocObj = request.getParameter("orderColumn");
        Object omObj = request.getParameter("orderMode");
        if (ocObj != null && !"".equals(ocObj.toString().trim()) && omObj != null && !"".equals(
                omObj.toString().trim())) {
            listRequest.setOrderColumn(ocObj.toString());
            listRequest.setOrderMode(omObj.toString());
        } else {
            listRequest.setOrderColumn("create_time");
            listRequest.setOrderMode("desc");
        }

        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CustomerListResponse response = customer.getCustomerList(listRequest);

        //组装客户项目信息
        if (response.getObjectList() != null && !response.getObjectList().isEmpty()) {
            setProjectInfo(userEntity, response);
        }

        model.addAttribute("page", response.getPaging());
        model.addAttribute("customers", response.getObjectList());
        //未曾使用
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 获取我的用户列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getMyCustomers", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse getMyCustomers(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String customerId = request.getParameter("customerId");
        String curid = String.valueOf(userEntity.getId());
        String curname = userEntity.getRealName();
        if (!Strings.isNullOrEmpty(customerId) && userEntity != null) {
            try {
                House365RestObject<String> hro = new House365RestObject();
                String url = customer.getCRMCustomerURL(Integer.valueOf(customerId), curid, curname, userEntity.getShowMobile());
                hro.setEntity(url);
                restResponse.setData(hro);
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    @RequestMapping(value = "checkCustomerPhone", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object checkCustomerPhone(HttpServletRequest request, String customerPhone, String sourceType, Integer platMangerId) throws ServiceRunException {
        JSONObject checkResult = new JSONObject();
        if (!Strings.isNullOrEmpty(customerPhone)) {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

            House365RestResponse response = customer.checkCustomerPhone(userEntity.getId(), customerPhone, sourceType, platMangerId);
            try {
                Map<String, Object> result = response.getData().getParaMap();
                if ("0".equals(result.get("result"))) {
                    return JSONObject.fromObject(result).toString();
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            checkResult.put("result", "1");
            checkResult.put("msg", "该手机号可以注册！");
        }
        return checkResult;
    }


    @RequestMapping(value = "checkCustomerPhoneByCustomerIds", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object checkCustomerPhoneByCustomerIds(HttpServletRequest request, String customerIds, String userIds) throws ServiceRunException {
        JSONObject checkResult = new JSONObject();
        if (!Strings.isNullOrEmpty(customerIds)) {
            String[] userIdArray = userIds.split(",");
            House365RestResponse response = customer.checkCustomerPhoneByCustomerIds(userIds,
                    customerIds);
            try {
                Map<String, Object> result = response.getData().getParaMap();
                if ("0".equals(result.get("result"))) {
                    return JSONObject.fromObject(result).toString();
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            checkResult.put("result", "1");
            checkResult.put("msg", "该手机号可以注册！");
        }
        return checkResult;
    }

    /**
     * 选择项目
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "assignBuilding", method = RequestMethod.GET)
    public String assignBuilding(
            Model model, HttpServletRequest request, Integer maxCount, String departmentNames, String departmentIds
    ) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityCode = departmentEntity.getDescripition();

        model.addAttribute("city", cityCode);
        model.addAttribute("maxCount", maxCount);
        model.addAttribute("departmentNames", departmentNames);
        model.addAttribute("departmentIds", departmentIds);
        return getAutoUrl();
    }

    /**
     * 选择项目
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "assignBuildingNew", method = RequestMethod.GET)
    public String assignBuildingNew(
            Model model, HttpServletRequest request, Integer maxCount, String departmentNames, String departmentIds
    ) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityCode = departmentEntity.getDescripition();

        model.addAttribute("city", cityCode);
        model.addAttribute("maxCount", maxCount);
        model.addAttribute("departmentNames", departmentNames);
        model.addAttribute("departmentIds", departmentIds);
        return getAutoUrl();
    }

    @RequestMapping(value = "abandonCustomer", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse abandonCustomer(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String customerId = request.getParameter("customerId");
        if (!Strings.isNullOrEmpty(customerId) && userEntity != null) {
            try {
                logger.info("abandonCustomer [{}]", customerId);
                customer.abandonCustomer(customerId, userEntity.getId(), userEntity.getRealName(), null);
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    /**
     * 400来电客户-放弃
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "abandonHotlineCustomer", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse abandonHotlineCustomer(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String customerId = request.getParameter("customerId");
        if (!Strings.isNullOrEmpty(customerId) && userEntity != null) {
            try {
                logger.info("abandonCustomer [{}]", customerId);
                customer.abandonHotlineCustomer(customerId, userEntity.getId(), userEntity.getRealName(), null);
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    private MarketCustomerListResponse getnotassignList(Map<String, Object> searchParams) {
        Page page = new Page(Integer.MAX_VALUE);
        searchParams.put("EQ_notassign", "1");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getMarketCustomerList(listRequest);
    }

    private MarketCustomerListResponse getNotassignandovertimeList(Map<String, Object> searchParams) {
        Page page = new Page(Integer.MAX_VALUE);
        searchParams.put("EQ_notassignandovertime", "1");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getMarketCustomerList(listRequest);
    }

    private MarketCustomerListResponse getAssignedList(Map<String, Object> searchParams) {
        Page page = new Page(Integer.MAX_VALUE);
        searchParams.put("EQ_assigned", "1");
        searchParams.put("NOTEQ_status", "3");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getMarketCustomerList(listRequest);
    }

    /**
     * 设置主客
     *
     * @param id 主键id
     * @return
     */
    @RequestMapping(value = "/setMajorCustomer/{id}")
    @ResponseBody
    public HResult setMajorCustomer(@PathVariable int id, HttpServletRequest request) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            customerProject.setMajorCustomer(id, userEntity.getName());
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("设置主客失败");
            e.printStackTrace();
            logger.error("设置主客失败", e);
        }
        return result;
    }

    /**
     * 判断是否私客
     *
     * @param id 主键id
     * @return
     */
    @RequestMapping(value = "/judgePrivate/{id}")
    @ResponseBody
    public HResult judgePrivate(@PathVariable int id) {
        HResult result = new HResult();
        try {
            CustomerEntity customerEntity = customer.queryById(id);
            if (customerEntity == null) {
                CustomerResponse customerResponse = customer.getCustomerById(id);
                if (customerResponse != null && customerResponse.getEntity() != null) {
                    customerEntity = customer.getCustomerMerge(customerResponse.getEntity().getPhone(), customerResponse.getEntity().getManagerId());
                }
            }
            if (customerEntity == null) {
                result.setStatus(-1);
                result.setErrorMessage("该客户已不属于私客，无法查看");
            }
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("判断私客失败");
            e.printStackTrace();
            logger.error("判断私客失败", e);
        }
        return result;
    }

    /**
     * 判断是否公海客户
     *
     * @param cpId 客户状态id
     * @return
     */
    @RequestMapping(value = "/judgeSea/{cpId}")
    @ResponseBody
    public HResult judgeSea(@PathVariable int cpId) {
        HResult result = new HResult();
        try {
            CustomerProjectResponse response = customerProject.getCustomerProjectById(cpId);
            if (response != null) {
                CustomerProjectEntity entity = response.getEntity();
                CustomerResponse customerResponse = customer.getCustomerById(entity.getCustomerId());
                if (customerResponse != null && customerResponse.getEntity().getManagerId() == null) {
                    result.setStatus(-1);
                    result.setErrorMessage("该客户已回公海，无法维护");
                }
            }
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("判断是否公海客户失败");
            logger.error("判断是否公海客户失败", e);
        }
        return result;
    }


    @RequestMapping(value = "/clearData")
    @ResponseBody
    public HResult clearData() {
        HResult result = new HResult();
        try {
            long startTime = System.currentTimeMillis();
            List<CustomerStatusLogEntity> list = dataService.queryByCustomer();
            dataService.clearData(list);
            long endTime = System.currentTimeMillis();
            System.out.println("程序运行时间： " + (endTime - startTime) + "ms");
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("清洗数据失败");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 公海客户详情
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "seaCustomerInfo", method = RequestMethod.GET)
    public String seaCustomerInfo(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();

        String customerId = request.getParameter("customerId");
        String action = request.getParameter("action");
        CustomerResponse customerResponse = customer.getCustomerById(Integer.valueOf(customerId));
        CustomerEntity customerEntity = customerResponse.getEntity();

        //获取客户标签
        List<LabelEntity> labelDetailList = user.queryCustomerLabel(null, customerEntity.getId());
        //客户详情展示客户标签
        List<Object> labs = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(labelDetailList)) {
            for (LabelEntity oldLabEntity : labelDetailList) {
                labs.add(oldLabEntity);
            }
        }
        model.addAttribute("labs", labs);

        if (org.apache.commons.lang3.StringUtils.isNotBlank(customerEntity.getCreateSource())) {
            if ("CRM拉取".equals(customerEntity.getCreateSource())) {
                customerEntity.setCreateSource("营销活动");
            } else if ("SYSTEM".equals(customerEntity.getCreateSource()) || "WECHAT".equals(customerEntity.getCreateSource())) {
                customerEntity.setCreateSource("手动添加");
            } else if ("HOTLINE".equals(customerEntity.getCreateSource())) {
                customerEntity.setCreateSource("400来电");
            } else if ("PT".equals(customerEntity.getCreateSource())) {
                customerEntity.setCreateSource("平台导入");
            }
        }

        //查询约看项目
        Map<String, Object> cpMap = new HashMap<>(10);
        cpMap.put("customerIdNew", customerEntity.getId());
        List<CustomerProjectEntity> cpList = customerProject.queryList(cpMap);
        if (CollectionUtils.isNotEmpty(cpList)) {
            for (CustomerProjectEntity cp : cpList) {
                if (userEntity.getPreLoginTime() != null && cp.getLastChangeStatusTime() != null) {
                    if (userEntity.getPreLoginTime().before(cp.getLastChangeStatusTime())) {
                        cp.setRemark("New!");
                    } else {
                        cp.setRemark("");
                    }
                } else {
                    cp.setRemark("");
                }
            }
        }

        //查询回访记录
        cpMap.put("customerId", customerEntity.getId());
        List<CustomerCallbackLogEntity> backLogList = customerCallbackLog.queryByConditions(cpMap);

        userEntity.setCity(cityCode);
        if(userEntity.getShowMobile() == null || userEntity.getShowMobile() != 1) {
            customerEntity.setPhone(MobileUtil.hidePhone(customerEntity.getPhone()));
        }
        model.addAttribute("action", action);
        model.addAttribute("callLogs", backLogList);
        model.addAttribute("customerProjects", cpList);
        model.addAttribute("entity", customerEntity);

        //查询客户日志
        Map<String, Object> map = new HashMap<>(10);
        map.put("relateId", customerEntity.getId());
        List<CustomerLogEntity> list = logInterface.queryByConditions(map);
        List<String> logShowList = new ArrayList<>(15);
        if (CollectionUtils.isNotEmpty(list)) {
            for (CustomerLogEntity p : list) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //获取String类型的时间
                String showTime = sdf.format(p.getCreateTime());
                if (p.getType() == 1) {
                    String showWord = showTime + "  " + p.getCreateUserName() + " [新增客户]";
                    logShowList.add(showWord);
                } else if (p.getType() == 2) {
                    StringBuilder builder = new StringBuilder();
                    builder.append(showTime).append("   ").append(p.getCreateUserName()).append("  [编辑客户]  ");
                    builder.append("将  '").append(p.getModifyName()).append("'  由  '").append(p.getOldValue())
                            .append("'  修改为  '").append(p.getNewValue()).append("' , ");
                    logShowList.add(builder.toString().substring(0, builder.toString().lastIndexOf(",")));
                } else if (p.getType() == 3) {
                    String showWord = showTime + "  " + p.getCreateUserName() + " [删除客户]";
                    logShowList.add(showWord);
                } else if (p.getType() == 4) {
                    //营销活动派工
                    String showWord = showTime + "  " + p.getCreateUserName() + " [营销活动-派工客户]" + "给  ";
                    if (StringUtils.isNotBlank(p.getNewValue())) {
                        UserEntity showUser = user.getById(Integer.valueOf(p.getNewValue()));
                        if (null != showUser) {
                            showWord = showWord + showUser.getRealName();
                        }
                    }
                    logShowList.add(showWord);
                } else if (p.getType() == 5) {
                    //公海派工
                    String showWord = showTime + "  " + p.getCreateUserName() + " [公海-派工客户]" + "给  ";
                    if (StringUtils.isNotBlank(p.getNewValue())) {
                        UserEntity showUser = user.getById(Integer.valueOf(p.getNewValue()));
                        if (null != showUser) {
                            showWord = showWord + showUser.getRealName();
                        }
                    }
                    logShowList.add(showWord);
                } else if (p.getType() == 6) {
                    //移入派工
                    String showWord = showTime + "  " + p.getCreateUserName() + " [移入公海]";
                    logShowList.add(showWord);
                } else if (p.getType() == 7) {
                    //转移客户
                    String showWord = showTime + "  " + p.getCreateUserName() + " [转移客户]" + "给  ";
                    if (StringUtils.isNotBlank(p.getNewValue())) {
                        UserEntity showUser = user.getById(Integer.valueOf(p.getNewValue()));
                        if (null != showUser) {
                            showWord = showWord + showUser.getRealName();
                        }
                    }
                    logShowList.add(showWord);
                } else if (p.getType() == 8) {
                    //无变动
                    String showWord = showTime + "  " + p.getCreateUserName() + " [无变动]";
                    logShowList.add(showWord);
                } else if (p.getType() == 9) {
                    //云迹活动派工
                    String showWord = showTime + "  " + p.getCreateUserName() + " [云迹活动-派工客户]" + " 给 ";
                    UserEntity showUser = user.getById(Integer.valueOf(p.getNewValue()));
                    if (null != showUser) {
                        showWord = showWord + showUser.getRealName();
                    }
                    logShowList.add(showWord);
                }else if(p.getType() == 11){
                    //平台客户管理转移创建人
                    String showWord = showTime + "  " + p.getCreateUserName() + " [转移线索]" + "给 ";
                    UserEntity showUser = user.getById(Integer.valueOf(p.getNewValue()));
                    if (null != showUser) {
                        showWord = showWord + showUser.getRealName();
                    }
                    logShowList.add(showWord);
                }

            }
        }
        List<CustomerEntity> oldList = new ArrayList<>();
        oldList.add(customerEntity);
        model.addAttribute("oldList", oldList);
        //客户日志列表
        model.addAttribute("logList", logShowList);
        model.addAttribute("customerId", customerId);
        return getAutoUrl("seaCustomerInfo");
    }

    /**
     * 获取批量转移客户人员列表
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "transferCreator", method = RequestMethod.GET)
    public String transferCreator(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String customerCount = request.getParameter("customerCount") == null ? "0" : request.getParameter(
                "customerCount");
        String deptUrlPath = userEntity.getDeptUrlPath();
        //重写查询用户列表提升性能
        Map<String, Object> searchMap = new HashMap<>(10);
        searchMap.put("order", 1);
        List<UserEntity> userList = user.queryByConditions(searchMap);
        //当前操作人所在用户分组的所有用户以及所在用户分组的所有子用户
        List<UserEntity> transferUsers = new ArrayList<>();
        for (UserEntity userTmp:userList) {
            if(userTmp.getDeptUrlPath().startsWith(deptUrlPath))
                transferUsers.add(userTmp);
        }
        model.addAttribute("users", deptUrlPath.split( "/" ).length == 2 ? userList : transferUsers);
        model.addAttribute("customerCount", customerCount);
        return getAutoUrl("transferCreator");
    }

    /**
     * 批量转移平台客户创建人
     * @param request
     * @return
     */
    @RequestMapping(value = "batchTransferCreator", method = RequestMethod.GET)
    @ResponseBody
    public  House365RestResponse batchTransferCreator(HttpServletRequest request){
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String userIds = request.getParameter("userIds");
        String customerIds = request.getParameter("customerIds") == null ? "" : request.getParameter("customerIds");
        String[] customerIdArray = customerIds.split(",");
        String[] userIdArray = userIds.split(",");
        try {
            customer.batchTransferCreator(customerIdArray,userIdArray,userEntity,11);
            restResponse.setMsg(customerIdArray.length + "组数据已经转移创建人完成");
        } catch (Exception e) {
            restResponse.setResult("0");
            restResponse.setMsg(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return restResponse;
    }

}
