package com.house365.ws.interfaces.rest;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.house365.beans.common.HGSConstant;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.beans.vo.CustomerInfoVO;
import com.house365.beans.vo.CustomerListVO;
import com.house365.beans.vo.WechatCustomerListVO;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.SpringContextUtil;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.*;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.dao.mapper.CustomerMergeMapper;
import com.house365.ws.interfaces.server.*;
import com.house365.ws.service.interfaces.*;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static com.house365.beans.common.MessageTypeEnum.NEWCUSTOMER;
import static com.house365.ws.util.Constant.PAGENO;

/**
 * <p>Title: 客户-微信企业号接口</p>
 * <p>Description: </p>
 * <p>Date: 2017/2/4</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("wechatCustomer")
public class CustomerWechat implements ICustomerWechat {

    /**
     * 跟踪状态：有效
     */
    static final int TRACE_STATUS_INVALID = 1;
    private static final Logger LOGGER = LoggerFactory.getLogger("sysLog");
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private ICustomerService<CustomerEntity> customerService;
    @Autowired
    private IUserService<UserEntity> userService;
    @Autowired
    private IDepartmentService<DepartmentEntity> departmentService;
    @Autowired
    private ICustomerSourceService<CustomerSourceEntity> customerSourceService;
    @Autowired
    private ICustomer customer;
    @Autowired
    private IProject project;
    @Autowired
    private IDepartment department;
    @Autowired
    private IUser iuser;
    @Autowired
    private ICustomerProject customerProject;
    @Autowired
    private ICustomerCallbackLog customerCallbackLog;
    @Autowired
    private ICustomerUser customerUser;
    @Autowired
    private INotice notice;
    @Autowired
    private IAttachmentService<BaseAttachment> attachmentService;
    @Autowired
    private IWeChatPermissionService<WeChatPermissionEntity> weChatPermissionService;
    @Autowired
    private IPermissionService<PermissionEntity> permissionService;
    @Autowired
    private IUserRole userRole;
    @Autowired
    private IRushCustomerService rushCustomerService;
    @Autowired
    private RedisUtilsInterface redisUtils;
    @Autowired
    private IHgsCacheUtil hgsCacheUtil;
    @Autowired
    private IEvaluateUserCustomerLogService evaluateUserCustomerLogService;
    @Autowired
    private IReportMarketingService<ReportMarketingEntity> reportMarketingService;
    @Autowired
    private ICustomerCallbackTemplate customerCallbackTemplate;
    @Autowired
    private OperateLogUtils logUtils;
    @Autowired
    private CustomerMergeMapper mergeMapper;
    @Autowired
    private MergeCustomerUtil mergeCustomerUtil;

    /**
     * 保存客户编辑标签
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object saveCustomerLabel(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        House365RestObject object = new House365RestObject();
        //置业顾问手机
//        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerId = getMapValueByKey(Constant.CUSTOMER_ID, map, "");
        String labelIds = getMapValueByKey("labelId", map, "");
        CustomerEntity customerentity = customer.queryById(Integer.valueOf(customerId));
        LabelEntity labelentity = new LabelEntity();
        labelentity.setCustomerId(Integer.valueOf(customerId));
        iuser.delCustomerLabel(labelentity);
        // 业务层统一处理
        try {
            if (labelIds != null && !"".equals(labelIds)) {
                String[] lids;
                if (labelIds.contains(",")) {
                    lids = labelIds.split(",");
                } else {
                    lids = new String[1];
                    lids[0] = labelIds;
                }
                List<String> labIds = new ArrayList<String>();
                List<LabelEntity> paramList = new ArrayList<LabelEntity>();
                //标签ids
                for (String lid : lids) {
                    labIds.add(lid);
                }
                for (String lid : labIds) {
                    LabelEntity le = new LabelEntity();
                    le.setManagerId(customerentity.getManagerId());
                    le.setCustomerId(Integer.valueOf(customerId));
                    le.setLabelId(lid);
                    paramList.add(le);
                }
                if (paramList.size() > 0) {
                    iuser.saveCustomersLabels(paramList);
                }
            }
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(object);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getMyCustomers==result===:{}", result);
        return result;
    }


    /**
     * 获取安家顾问标签
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object getLabelByPhone(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParamsOLD);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetLabelByPhone(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getMyCustomers==result===:{}", result);
        return result;
    }

    private House365RestObject doGetLabelByPhone(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");

        LOGGER.info("==doGetHotLineCustomer>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            String cityId = DepartmentEntity.getCityID(user.getDeptUrlPath());
            DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
            String cityCode = departmentResponse.getEntity().getDescripition();
            //获取客户标签
            Map<String, Object> labelMap = new HashMap<String, Object>();
            labelMap.put("createId", user.getId());
            labelMap.put("cityCode", cityCode);
            List<LabelEntity> labelColorList = iuser.getColorLabel4MyCustomer(labelMap);
            object.setList(labelColorList);
        }
        return object;
    }

    /**
     * 客户详情编辑页获取指定客户标签
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object getCustomerLabel(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParamsOLD);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetCustomerLabel(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getMyCustomers==result===:{}", result);
        return result;
    }

    private House365RestObject doGetCustomerLabel(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        Integer customerId = Integer.valueOf(getMapValueByKey(Constant.CUSTOMER_ID, map, ""));
        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");

        LOGGER.info("==doGetHotLineCustomer>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            //获取客户标签
            Map<String, Object> labelMap = new HashMap<String, Object>();
            labelMap.put("createId", user.getId());
            List<LabelEntity> labelColorList = iuser.queryCustomerLabel(null, customerId);//客户已得标签
            //安家顾问管理标签
            List<LabelEntity> colorLabelList = iuser.getLabelColor(labelMap);
            //处理所有标签训中
            if (colorLabelList != null && colorLabelList.size() > 0) {
                for (LabelEntity le : labelColorList) {
                    for (LabelEntity emp : colorLabelList) {
                        if (emp.getLabelId().equals(le.getLabelId())) {
                            emp.setSelected("1");
                        }
                    }
                }
            }
            Map<String, Object> colorLabelMap = new HashMap<>();
            colorLabelMap.put("colorLabel", colorLabelList);//安家顾问管理标签
            colorLabelMap.put("labelColorList", labelColorList);//客户已得标签
            object.setEntity(colorLabelMap);
        }
        return object;
    }

    @Override
    public Object getMyCustomers(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetMyCustomer(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getMyCustomers==result===:{}", result);
        return result;
    }

    /**
     * 获取400客户列表
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object getHotLineCustomers(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        UserEntity entity = getUserEntity(phone);
        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetHotLineCustomer(map);
            System.out.println(("getShowMobile=" + entity.getShowMobile() + ",data.size=" + data.getList().size()));
            if(entity.getShowMobile() != 1) {
                if(entity.getShowMobile() != 1) {
                    if(data.getList() != null) {
                        for (int i = 0; i < data.getList().size(); i++) {
                            data.getList().get(i).setPhone(MobileUtil.hidePhone(data.getList().get(i).getPhone()));
                        }
                    }
                }
            }
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getHotLineCustomers==result===:{}", result);
        return result;
    }

    /**
     * 获取客户公海数据
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object getCustomerInOcean(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetCustomerInOcean(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getCustomerInOcean==result===:{}", result);
        return result;
    }

    /**
     * 获取客户公海数据概要
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object getCustomerOceanSummary(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetCustomerOceanSummary(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getCustomerOceanSummary==result===:{}", result);
        return result;
    }

    /**
     * 移动端公海派工
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object bindManager(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Boolean> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            House365RestObject<Boolean> data = doAssignCustomer(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===bindManager==result===:{}", result);
        return result;
    }

    /**
     * 获取约看项目列表
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object getAssignProjects(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<ProjectEntity> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            House365RestObject<ProjectEntity> data = doGetAssignProjects(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getAssignProjects==result===:{}", result);
        return result;
    }

    /**
     * 约看
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object bindToProjects(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Boolean> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            House365RestObject<Boolean> data = doBindToProjects(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===bindToProjects==result===:{}", result);
        return result;
    }

    //获取用户信息
    @Override
    public Object getUserInfo(Parameter parameter) {

        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<UserEntity> response = new House365RestResponse<>();
        response.setResult("0");
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        UserEntity userEntity = getUserEntity(phone);
        if (null != userEntity) {
            UserRoleListRequest userRoleListRequest = new UserRoleListRequest();
            userRoleListRequest.setPaging(new Page(Integer.MAX_VALUE));
            Map<String, Object> paraMap = new HashMap<>(10);
            paraMap.put("EQ_userId", userEntity.getId());
            userRoleListRequest.setSearchParams(paraMap);
            StringBuilder roles = new StringBuilder("");
            UserRoleListResponse userRoleResponse = userRole.getUserRoleList(userRoleListRequest);
            if (userRoleResponse.getObjectList() != null && !userRoleResponse.getObjectList().isEmpty()) {
                for (UserRoleEntity ur : userRoleResponse.getObjectList()) {
                    roles.append(ur.getRoleName()).append(",");
                }
            }
            String deptName = "";
            String city = "";
            if (null != userEntity.getDeptId()) {
                DepartmentResponse dr = department.getDepartmentById(userEntity.getDeptId());
                DepartmentEntity dept = dr.getEntity();
                if (dr.getEntity() != null) {
                    deptName = dr.getEntity().getName();
                }

                Integer realDept = PathUtil.extractDept(dept.getUrlPath());
                if (!userEntity.getDeptId().equals(realDept)) {
                    dept = department.getDepartmentById(realDept).getEntity();
                }
                city = dept.getDescripition();
            }
            userEntity.setCity(city);
            userEntity.setWeiXinId(deptName);
            userEntity.setEmail(roles.toString().endsWith(",") ? roles.toString().substring(0,
                    roles.toString().length() - 1) : roles.toString());
            if (null != userEntity.getCreateTime()) {
                userEntity.setCreateIp(DateTimeUtils.parseDate(userEntity.getCreateTime(),
                        DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_FULL));
            } else {
                userEntity.setCreateIp("");
            }

        } else {
            userEntity = new UserEntity();
        }

        House365RestObject<UserEntity> data = new House365RestObject<>();
        data.setEntity(userEntity);

        response.setData(data);
        response.setResult("1");
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getUserInfo==result===:{}", result);
        return result;
    }

    /**
     * 获取客户详情
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object getCustomerInfo(Parameter parameter) throws ServiceRunException {

        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerInfoVO> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            House365RestObject<CustomerInfoVO> data = doGetCustoemrInfo(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getCustomerInfo==result===:{}", result);
        return result;
    }

    @Override
    public Object addCall(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Boolean> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            House365RestObject<Boolean> data = doAddCall(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===addCall==result===:{}", result);
        return result;
    }

    @Override
    public Object saveUserInfo(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Boolean> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.UserParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            House365RestObject<Boolean> data = new House365RestObject<>();
            String id = getMapValueByKey("id", map, "");
            String prop = getMapValueByKey("prop", map, "");
            String newValue = getMapValueByKey("newValue", map, "");
            if (Strings.isNullOrEmpty(id) || Strings.isNullOrEmpty(prop) || Strings.isNullOrEmpty(newValue)) {
                data.setEntity(false);
            } else {
                UserEntity user = userService.getById(Integer.valueOf(id));
                switch (prop) {
                    case "mobile":
                        Map<String, Object> checkExsitSearchMap = new HashMap<>();
                        checkExsitSearchMap.put("EQ_mobile", newValue);
                        QueryParams checkExsit = new QueryParams(checkExsitSearchMap);
                        if (userService.getTotalCount(checkExsit) > 0) {
                            throw new IllegalServiceParameterException("手机号已经存在");
                        } else {
                            String cookieKey = "weChat:userInfo:isValid:" + user.getMobile();
                            //修改后，删除wechat的cookie的key；
                            RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean(
                                    "redisUtils");
                            redisUtils.deleteKey(cookieKey);

                            user.setMobile(newValue);

                            final UserEntity entityPost = user;
                            ExecutorService executor = Executors.newCachedThreadPool();
                            executor.execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        wechatService.callWechatUserAPI(entityPost, "/enterprise/user/update");
                                    } catch (Exception e) {
                                        LOGGER.error(e.getMessage(), e);
                                    }
                                }
                            });
                        }
                        break;
                    case "realName":

                        if (user != null && !StringUtils.isEmpty(user.getRealName()) && !newValue.equals(
                                user.getRealName())) {
                            customer.updateManager(user.getId(), newValue);
                        }
                        user.setRealName(newValue);

                        break;
                    case "position":
                        user.setPosition(newValue);
                        break;
                    default:
                        break;
                }

                userService.update(user);
                data.setEntity(true);
            }

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===saveUserInfo==result===:{}", result);
        return result;
    }

    //我的客户首页数据
    @Override
    public Object myCustomerIndex(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            //置业顾问手机
            String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
            UserEntity userEntity = getUserEntity(phone);
            Map<String, Object> data = customerService.getWechatMyCucstomerSummary(String.valueOf(userEntity.getId()));
            House365RestObject object = new House365RestObject();
            object.setEntity(data);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(object);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===myCustomerIndex==result===:{}", result);
        return result;
    }

    //我的客户首页数据-置业顾问视图
    @Override
    public Object myCustomerUserIndex(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {

            String pageNo = getMapValueByKey("pageNo", map, "0");
            String pageSize = getMapValueByKey("pageSize", map, PAGENO);

            //置业顾问手机
            String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
            UserEntity userEntity = getUserEntity(phone);
            List<Map<String, Object>> data = customerService.getWechatMyCucstomerUserView(
                    String.valueOf(userEntity.getId()), pageNo, pageSize);
            House365RestObject object = new House365RestObject();
            object.setList(data);

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(object);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===myCustomerUserIndex==result===:{}", result);
        return JSONObject.fromObject(response).toString();

    }

    @Override
    public String noticeList(Parameter parameter) {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 获取查询条件

        String pageNo = getMapValueByKey("pageNo", map, "0");
        String pageSize = getMapValueByKey("pageSize", map, PAGENO);

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        UserEntity userEntity = getUserEntity(phone);

        //get department
        DepartmentEntity department = departmentService.getById(userEntity.getDeptId());

        //get city notice list
        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("EQ_city", department.getCityID());
        Page page = new Page(Integer.parseInt(pageSize));

        if (!Strings.isNullOrEmpty(pageNo)) {
            page.setCurrentPage(Integer.parseInt(pageNo));
        }
        NoticeListRequest listRequest = new NoticeListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        NoticeListResponse listResponse = notice.getNoticeList(listRequest);

        if (null != listResponse && listResponse.getObjectList() != null && !listResponse.getObjectList().isEmpty()) {
            List<NoticeEntity> notices = listResponse.getObjectList();
            Date threeDaysAgo = DateTimeUtils.getDaysAgo(new Date(), 3);
            for (NoticeEntity notice : notices) {
                if (notice.getCreateTime().after(threeDaysAgo)) {
                    notice.setCity("new");
                }
            }
        }

        House365RestObject object = new House365RestObject();
        object.setList(listResponse.getObjectList());

        response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
        response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        response.setData(object);
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===noticeList==result===:{}", result);
        return result;
    }

    @Override
    public String noticeDetail(Parameter parameter) {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.NoticeParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 获取查询条件
        String id = getMapValueByKey("id", map, "");

        NoticeResponse noticeResponse = notice.getNoticeById(Integer.valueOf(id));

        NoticeEntity noticeEntity = new NoticeEntity();
        House365RestObject object = new House365RestObject();
        if (noticeResponse.getEntity() != null) {
            LOGGER.info("===noticeDetail==result===:1");
            noticeEntity = (NoticeEntity) noticeResponse.getEntity();
            if (null != noticeEntity.getCreateTime() && noticeEntity.getId() != null) {
                String time = DateTimeUtils.parseDate(noticeEntity.getCreateTime(),
                        DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_FULL);
                LOGGER.info("===noticeDetail==result===:2 {}", time);
                noticeEntity.setCreateTimeStr(time);
            }
        }
        LOGGER.info("===noticeDetail==result===:{}", noticeEntity.getCreateTimeStr());

        object.setEntity(noticeEntity);

        response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
        response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        response.setData(object);
        String result = JSONObject.fromObject(response).toString();
        LOGGER.info("===noticeDetail==result===:{}", result);
        return result;
    }

    /**
     * 是否当天
     *
     * @param date
     * @return
     */
    private static boolean isToday(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String param = sdf.format(date);//参数时间
        String now = sdf.format(new Date());//当前时间
        if (param.equals(now)) {
            return true;
        }
        return false;
    }

    /**
     * 是否是昨天
     *
     * @param date
     * @return
     */
    private static boolean isYestoday(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String param = sdf.format(date);//参数时间
        Date today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date yestodayDate = calendar.getTime();
        String yesDate = sdf.format(yestodayDate);
        if (param.equals(yesDate)) {
            return true;
        }
        return false;
    }


    /**
     * 全链条app触屏端获取待回访客户
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object getMyWaitCallCustomerList(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            String pageNo = getMapValueByKey("pageNo", map, "0");
            String pageSize = getMapValueByKey("pageSize", map, "20");
            //置业顾问手机
            String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
            UserEntity userEntity = getUserEntity(phone);

            Map<String, Object> searchParams = new HashMap<>(10);
            Page page = new Page(Integer.parseInt(pageSize));
            page.setCurrentPage(Integer.parseInt(pageNo));
            //排除400客户状态未跟踪和删除
            String cityId = DepartmentEntity.getCityID(userEntity.getDeptUrlPath());
            DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
            String cityCode = departmentResponse.getEntity().getDescripition();
            searchParams.put("EQ_cityCode", cityCode);
            searchParams.put("EQ_isDelete", "0");
            searchParams.put("EQ_typeFilter", "(isWaitCall = 1)");
            searchParams.put("EQ_orderBy", "create_time desc");
            searchParams.put("EQ_userId", userEntity.getId());

            CustomerListRequest listRequest = new CustomerListRequest();
            listRequest.setSearchParams(searchParams);
            listRequest.setPaging(page);

            CustomerListResponse customerListResponse = customer.getCustomerListFromOld(listRequest);
            List<CustomerListVO> customers = new ArrayList<>();
            if (customerListResponse != null && customerListResponse.getObjectList() != null) {
                List<Integer> customerId = new ArrayList<>();
                for (CustomerEntity c : customerListResponse.getObjectList()) {
                    customerId.add(c.getId());
                }

                for (CustomerEntity customerEntity : customerListResponse.getObjectList()) {
                    //待回访是否私客标志
                    Integer isPrivate = 0;
                    Integer privateId = 0;

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

                    Date bindTime = customerEntity.getBindTime();
                    if (isToday(bindTime)) {
                        customerEntity.setBelongToday("1");
                    }
                    if (isYestoday(bindTime)) {
                        customerEntity.setBelongYestoday("1");
                    }
                    if (!isToday(bindTime) && !isYestoday(bindTime)) {
                        customerEntity.setBelongSince("1");
                    }

                    //star customer display
                    Map<String, Object> searchCU = new HashMap<>(10);
                    if (!customerId.isEmpty()) {
                        searchCU.put("IN_customerIds", customerId);
                    }
                    searchCU.put("EQ_userId", userEntity.getId());
                    CustomerUserListRequest cul = new CustomerUserListRequest();
                    cul.setPaging(new Page(Integer.MAX_VALUE));
                    cul.setSearchParams(searchCU);
                    CustomerUserListResponse res = customerUser.getCustomerUserList(cul);

                    //set collect star style
                    String star = "off";
                    String userId4Star = "";
                    if (res != null && res.getObjectList() != null && !res.getObjectList().isEmpty()) {
                        for (CustomerUserEntity cue : res.getObjectList()) {
                            if (customerEntity.getId().intValue() == cue.getCustomerId().intValue() && userEntity.getId().equals(
                                    cue.getUserId()) && cue.getStar() == 1) {
                                star = "on";
                                break;
                            }
                        }
                    }

                    Map<String, Object> cpMap = new HashMap<>(10);
                    cpMap.put("EQ_customerId", customerEntity.getId());
                    CustomerProjectListRequest customerProjectListRequest = new CustomerProjectListRequest();
                    customerProjectListRequest.setSearchParams(cpMap);
                    CustomerProjectListResponse cpl = customerProject.getCustomerProjectList(customerProjectListRequest);

                    boolean hasCustomerProjects = false;
                    boolean hasNewCustomerProjects = false;
                    if (cpl.getObjectList() != null && cpl.getObjectList().size() != 0) {
                        hasCustomerProjects = true;
                        for (CustomerProjectEntity cpe : cpl.getObjectList()) {
                            if (userEntity.getPreLoginTime() != null && cpe.getLastChangeStatusTime() != null) {
                                if (userEntity.getPreLoginTime().before(cpe.getLastChangeStatusTime())) {
                                    hasNewCustomerProjects = true;
                                    break;
                                }
                            }
                        }
                    }
                    //判断待回访客户是否已经是私客（直接查询新客户表）
                    Map<String, Object> privateMap = new HashMap<>(10);
                    privateMap.put("phone", customerEntity.getPhone());
                    privateMap.put("managerId", customerEntity.getManagerId());
                    privateMap.put("isPrivate", 1);
                    List<CustomerEntity> list = mergeMapper.queryByConditions(privateMap);
                    if (CollectionUtils.isNotEmpty(list)) {
                        isPrivate = 1;
                        privateId = list.get(0).getId();
                    }

                    CustomerListVO customerListVO = new CustomerListVO(customerEntity.getId(), customerEntity.getName(),
                            customerEntity.getPhone(), customerEntity.getSex(),
                            customerEntity.getActSource(),
                            customerEntity.getStatus(),
                            customerEntity.getCreateTime(),
                            customerEntity.getBuyIntention(),
                            customerEntity.getLastVisitTime(),
                            customerEntity.getLastCallTime(),
                            customerEntity.getManagerId(),
                            customerEntity.getManagerName(),
                            customerEntity.getTraceStatus(), star, userId4Star,
                            hasCustomerProjects, hasNewCustomerProjects,
                            customerEntity.getBelongToday(),
                            customerEntity.getBelongYestoday(),
                            customerEntity.getBelongSince(),
                            cc.getObjectList(), null, customerEntity.getIsWaitCall(),
                            customerEntity.getLatestSource(),
                            customerEntity.getBindTime(),
                            customerEntity.getBakPhone1(),
                            customerEntity.getSingupTime(), isPrivate, privateId, customerEntity.getStarCustomer());

                    customers.add(customerListVO);
                }
            }

            House365RestObject object = new House365RestObject();
            if(userEntity.getShowMobile() == null || userEntity.getShowMobile() != 1) {
                customers = customers.stream().map(i-> {
                    i.setPhone(MobileUtil.hidePhone(i.getPhone()));
                    return i;
                }).collect(Collectors.toList());
            }
            object.setList(customers);

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(object);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getMyCustomerList==result===:{}", result);
        return result;

    }

    /**
     * 放弃客户
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object abandonCustomer(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.WaitCallCustomer);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        String customerId = getMapValueByKey("customerId", map, "0");
        String phone = getMapValueByKey("phone", map, "0");
        UserEntity userEntity = getUserEntity(phone);
        if (!Strings.isNullOrEmpty(customerId) && userEntity != null) {
            customer.abandonCustomer(customerId, userEntity.getId(), userEntity.getRealName(), null);
        }
        House365RestObject object = new House365RestObject();

        response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
        response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        response.setData(object);
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===abandonCustomer==result===:{}", result);
        return result;

    }

    //我的客户列表
    @Override
    public Object getMyCustomerList(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {

            String pageNo = getMapValueByKey("pageNo", map, "0");
            String pageSize = getMapValueByKey("pageSize", map, PAGENO);

            //2 最近回访 3 星级客户 1 今日新增 4 最近7天
            String type = getMapValueByKey("queryType", map, "");

            //搜索关键字
            String keyword = getMapValueByKey("keyword", map, "");
            //购房意向
            String buyIntention = getMapValueByKey("buyIntention", map, "");
            //跟踪状态
            String traceStatus = getMapValueByKey("traceStatus", map, "");
            //客户项目状态
            String projectStatus = getMapValueByKey("projectStatus", map, "");
            //创建时间起始
            String createTimeStart = getMapValueByKey("startDate", map, "");
            //创建时间截止
            String createTimeEnd = getMapValueByKey("endDate", map, "");
            //置业顾问手机
            String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
            //客户标签
            String labelId = getMapValueByKey("labelId", map, "");
            UserEntity userEntity = getUserEntity(phone);

            List<Integer> userIds = userService.getUserIdOnPath(userEntity.getId());

            List<Integer> customerIds = new ArrayList<>();

            if (!Strings.isNullOrEmpty(type) && !Strings.isNullOrEmpty(String.valueOf(userEntity.getId()))) {
                switch (type) {
                    case "1":
                        //今日新增客户
                        customerIds = customerService.getNewAddCustomerIds(String.valueOf(userEntity.getId()));
                        break;
                    case "2":
                        //3天内回访的客户
                        customerIds = customerService.getCallInThreeDayIds(String.valueOf(userEntity.getId()));
                        break;
                    case "3":
                        //星标客户
                        customerIds = customerService.getStarCustomerIds(String.valueOf(userEntity.getId()));
                        break;
                    case "4":
                        //7日新增客户
                        customerIds = customerService.getSevenDayNewCustomerIds(String.valueOf(userEntity.getId()));
                        break;
                    default:
                        break;
                }

                //没有客户，不返回
                if (customerIds.isEmpty()) {
                    customerIds.add(-1);
                }
            }

            Page page = new Page(Integer.parseInt(pageSize));
            page.setCurrentPage(Integer.parseInt(pageNo));
            Map<String, Object> searchParams = new HashMap<>(10);

            if (labelId != null && !"".equals(labelId)) {
                searchParams.put("EQ_userId", userEntity.getId());
                searchParams.put("EQ_labelId", labelId);
            }

            if (!Strings.isNullOrEmpty(keyword)) {
                searchParams.put("LIKE_likekeyword", keyword);
            }
            if (!Strings.isNullOrEmpty(createTimeStart)) {
                searchParams.put("GTE_createTimeStart", createTimeStart + " 00:00:00");
            }
            if (!Strings.isNullOrEmpty(createTimeEnd)) {
                searchParams.put("LTE_createTimeEnd", createTimeEnd + " 23:59:59");
            }

            if (!Strings.isNullOrEmpty(buyIntention)) {
                if ("99".equalsIgnoreCase(buyIntention)) {
                    searchParams.put("EQ_buyIntentionIsNull", "1");
                } else {
                    searchParams.put("EQ_buyIntention", buyIntention);
                }
            }

            if (!Strings.isNullOrEmpty(traceStatus)) {
                searchParams.put("EQ_traceStatus", traceStatus);
            }

            if (!Strings.isNullOrEmpty(projectStatus)) {
                searchParams.put("EQ_projectStatus", projectStatus);
            }

            if (!customerIds.isEmpty()) {
                searchParams.put("EQ_customerIds", Joiner.on(",").join(customerIds));
            }

            if (!userIds.isEmpty()) {
                searchParams.put("EQ_userIds", Joiner.on(",").join(userIds));
            }

            //排除400客户状态未跟踪和删除
            String cityId = DepartmentEntity.getCityID(userEntity.getDeptUrlPath());
            DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
            String cityCode = departmentResponse.getEntity().getDescripition();
            searchParams.put("EQ_hotline", "0");
            searchParams.put("EQ_cityCode", cityCode);
            searchParams.put("EQ_isDelete", "0");
            searchParams.put("EQ_typeFilter", "(isWaitCall = 0 or isWaitCall is null)");
            searchParams.put("EQ_orderBy", "create_time desc");
            searchParams.put("EQ_userId", userEntity.getId());

            CustomerListRequest listRequest = new CustomerListRequest();
            listRequest.setSearchParams(searchParams);
            listRequest.setPaging(page);
            CustomerListResponse customerListResponse = new CustomerListResponse();
            if (labelId != null && !"".equals(labelId)) {
                customerListResponse = customer.getCustomerManagementList4Label(listRequest);
            } else {
                customerListResponse = customer.getCustomerManagementList(listRequest);
            }

            List<WechatCustomerListVO> customerVOList = new ArrayList<>();
            if (customerListResponse != null && customerListResponse.getObjectList() != null) {
                List<Integer> customerId = new ArrayList<>();
                //get last call content
                for (CustomerEntity c : customerListResponse.getObjectList()) {
                    customerId.add(c.getId());
                }

                List<Map<String, Object>> lastCallList = new ArrayList<>();

                if (!customerId.isEmpty()) {
                    House365RestResponse rr = customer.getLastestCallback(Joiner.on(",").join(customerId));
                    lastCallList = rr.getData().getList();

                    //设置是否有更新的小红点
                    List<CustomerProjectEntity> customerProjectEntities = new ArrayList<>();
                    Map<String, Object> cpMap = new HashMap<>(10);
                    CustomerProjectListRequest customerProjectListRequest = new CustomerProjectListRequest();
                    cpMap.put("EQ_customerIds", customerId);
                    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 : customerListResponse.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");
                                        break;
                                    } else {
                                        cpe.setRemark("");
                                    }
                                } else {
                                    cpe.setRemark("");
                                }
                                cps.add(cpe);
                            }
                        }
                        customerEntity.setCps(cps);
                    }

                }

                //star customer display
                Map<String, Object> searchCU = new HashMap<>(10);
                if (!customerId.isEmpty()) {
                    searchCU.put("IN_customerIds", customerId);
                }
                searchCU.put("EQ_userIds", userIds);
                CustomerUserListRequest cul = new CustomerUserListRequest();
                cul.setPaging(new Page(Integer.MAX_VALUE));
                cul.setSearchParams(searchCU);
                CustomerUserListResponse res = customerUser.getCustomerUserList(cul);
                //星标客户\安家顾问集合
                Map<Integer, String> customerId2UsrIdMap = new HashMap<>(res.getObjectList().size());
                for (CustomerUserEntity cue : res.getObjectList()) {
                    customerId2UsrIdMap.put(cue.getCustomerId(), String.valueOf(cue.getUserId()));
                }
                String userId4Star = "";
                //get last call content
                for (CustomerEntity c : customerListResponse.getObjectList()) {
                    String content = "";
                    if (lastCallList != null) {
                        for (Map<String, Object> call : lastCallList) {
                            if (call.containsKey("customer_id") && c.getId().toString().equalsIgnoreCase(
                                    String.valueOf(call.get("customer_id")))) {
                                content = String.valueOf(call.get("content"));
                                break;
                            }
                        }
                    }
                    //星标客户对应的直销人员id
                    userId4Star = customerId2UsrIdMap.get(c.getId()) == null ? "" : customerId2UsrIdMap.get
                            (c.getId());

                    //set collect star style
                    String star = "0";
                    if (res.getObjectList() != null && !res.getObjectList().isEmpty()) {
                        for (CustomerUserEntity cue : res.getObjectList()) {
                            if (c.getId().intValue() == cue.getCustomerId().intValue() && userIds.contains(
                                    cue.getUserId()) && cue.getStar() == 1) {
                                star = "1";
                                break;
                            }
                        }
                    }

                    //获取该客户标签、颜色
                    List<LabelEntity> oldList = iuser.queryCustomerLabel(userEntity.getId(), c.getId());
                    Map<String, Object> labelMap = new HashMap<String, Object>();
//                    labelMap.put("createId",userEntity.getId());
                    List<LabelEntity> labelDetailList = iuser.queryCustomerLabel(null, c.getId());
//                    List<LabelEntity> labelColorList = iuser.getLabelColor(labelMap);
                    List<LabelEntity> labelColorList = iuser.getColorLabel4MyCustomer(labelMap);

                    List<Object> labs = new ArrayList<Object>();
                    if (labelColorList != null && labelColorList.size() > 0 && labelDetailList != null && labelDetailList.size() > 0) {
                        for (LabelEntity oldLabEntity : labelDetailList) {
                            String oldLabId = oldLabEntity.getLabelId();
                            for (LabelEntity colorEntity : labelColorList) {
                                String colorLabId = colorEntity.getLabelId();
                                if (oldLabId.equals(colorLabId)) {
                                    oldLabEntity.setColorId(colorEntity.getColorId());
                                    oldLabEntity.setLabelName(colorEntity.getLabelName());
                                    oldLabEntity.setSelected("1");
                                    labs.add(oldLabEntity);
                                }
                            }
                        }
                    }


                    WechatCustomerListVO wechatCustomerListVO = new WechatCustomerListVO(c.getId(), c.getName(),
                            c.getPhone(), c.getSex(),
                            c.getActSource(),
                            c.getStatus(),
                            c.getCreateTime(),
                            c.getBuyIntention(),
                            c.getLastVisitTime(),
                            c.getLastCallTime(),
                            c.getManagerId(),
                            c.getManagerName(),
                            c.getTraceStatus(), content,
                            "new".equalsIgnoreCase(
                                    c.getBakPhone3()) ? "1" : "0",
                            star, userId4Star, labs, String.valueOf(userEntity.getId()));
                    customerVOList.add(wechatCustomerListVO);
                }
            }

            House365RestObject object = new House365RestObject();
            if(userEntity.getShowMobile() == null || userEntity.getShowMobile() != 1) {
                customerVOList = customerVOList.stream().map(i-> {
                    i.setPhone(MobileUtil.hidePhone(i.getPhone()));
                    return i;
                }).collect(Collectors.toList());
            }
            object.setList(customerVOList);

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(object);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getMyCustomerList==result===:{}", result);
        return result;
    }

    @Override
    public Object starToggle(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        // 业务层统一处理
        try {
            // 业务校验统一入口
            try {
                checkInterfaceParameter(map, Constant.CRMStatisticParams);
                response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            } catch (IllegalServiceParameterException e) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg(e.getMessage());
                return JSONObject.fromObject(response).toString();
            }

            String flag = getMapValueByKey("flag", map, "");
            String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
            String customerId = getMapValueByKey("customerId", map, "");
            if (Strings.isNullOrEmpty(flag) || Strings.isNullOrEmpty(customerId)) {
                throw new Exception("Star customer fail,parameter is empty [" + flag + "],[" + customerId + "]!!!");
            }

            UserEntity userEntity = getUserEntity(phone);

            Map<String, Object> search = new HashMap<>(10);
            search.put("EQ_customerId", customerId);
            search.put("EQ_userId", userEntity.getId());
            CustomerUserListRequest cul = new CustomerUserListRequest();
            cul.setPaging(new Page(1));
            cul.setSearchParams(search);

            //update
            CustomerUserListResponse res = customerUser.getCustomerUserList(cul);
            if (res.getObjectList() != null && !res.getObjectList().isEmpty()) {
                CustomerUserEntity entity = res.getObjectList().get(0);
                entity.setStar("on".equalsIgnoreCase(flag) ? 1 : 0);

                CustomerUserRequest updateReq = new CustomerUserRequest();
                updateReq.setEntity(entity);
                customerUser.updateCustomerUser(updateReq);
                //继续更新customer表的星标字段
                customer.updateCustomerStar(entity.getCustomerId(), entity.getStar());
            } else {
                //add new
                CustomerUserEntity entity = new CustomerUserEntity();
                entity.setCustomerId(Integer.valueOf(customerId));
                entity.setUserId(userEntity.getId());
                entity.setStar("on".equalsIgnoreCase(flag) ? 1 : 0);
                entity.setCreateTime(new Date());

                CustomerUserRequest newReq = new CustomerUserRequest();
                newReq.setEntity(entity);
                customerUser.addCustomerUser(newReq);
                //继续更新customer表的星标字段
                customer.updateCustomerStar(entity.getCustomerId(), entity.getStar());
            }

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===starToggle==result===:{}", result);
        return result;
    }

    @Override
    public Object addCustomer(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doAddCustomer(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===addCustomer==result===:{}", result);
        return result;
    }

    @Override
    public Object addSalesReport(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<ReportMarketingEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<ReportMarketingEntity> data = doAddSalesReport(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===addCustomer==result===:{}", result);
        return result;
    }

    /**
     * 修改/保存直销日报
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<ReportMarketingEntity> doAddSalesReport(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<ReportMarketingEntity> restObject = new House365RestObject<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String entityStr = map.get("entity").toString();
        String phone = getMapValueByKey("phone", map, "");
        map.remove("entity");
        JSONObject entity = JSONObject.fromObject(entityStr);
        UserEntity user = getUserEntity(phone);
        String city = departmentService.getCityByDepartmentId(user.getDeptId());
        String callCount = entity.containsKey("callCount") ? entity.getString("callCount") : "";
        String connectCount = entity.containsKey("connectCount") ? entity.getString("connectCount") : "";
        String intentBuyCount = entity.containsKey("intentBuyCount") ? entity.getString("intentBuyCount") : "";
        String source = entity.containsKey("source") ? entity.getString("source") : "";
        String visitedCount = entity.containsKey("visitedCount") ? entity.getString("visitedCount") : "";
        String visitedProject = entity.containsKey("visitedProject") ? entity.getString("visitedProject") : "";
        String twiceVisitedCount = entity.containsKey("twiceVisitedCount") ? entity.getString("twiceVisitedCount") : "";
        String twiceVisitedProject = entity.containsKey("twiceVisitedProject") ? entity.getString("twiceVisitedProject") : "";
        String identificationChipsCount = entity.containsKey("identificationChipsCount") ? entity.getString("identificationChipsCount") : "";
        String identificationChipsProject = entity.containsKey("identificationChipsProject") ? entity.getString("identificationChipsProject") : "";
        String subscriptionCount = entity.containsKey("subscriptionCount") ? entity.getString("subscriptionCount") : "";
        String subscriptionProject = entity.containsKey("subscriptionProject") ? entity.getString("subscriptionProject") : "";

        ReportMarketingEntity reportmarketingentity = new ReportMarketingEntity();
        reportmarketingentity.setCallCount(Integer.valueOf(callCount));
        reportmarketingentity.setConnectCount(Integer.valueOf(connectCount));
        reportmarketingentity.setIntentBuyCount(Integer.valueOf(intentBuyCount));
        reportmarketingentity.setSource(Integer.valueOf(source));
        reportmarketingentity.setVisitedCount(Integer.valueOf(visitedCount));
        reportmarketingentity.setVisitedProject(visitedProject);
        reportmarketingentity.setTwiceVisitedCount(Integer.valueOf(twiceVisitedCount));
        reportmarketingentity.setTwiceVisitedProject(twiceVisitedProject);
        reportmarketingentity.setIdentificationChipsCount(Integer.valueOf(identificationChipsCount));
        reportmarketingentity.setIdentificationChipsProject(identificationChipsProject);
        reportmarketingentity.setSubscriptionCount(Integer.valueOf(subscriptionCount));
        reportmarketingentity.setSubscriptionProject(subscriptionProject);
        reportmarketingentity.setDepartmentId(user.getDeptId());
        reportmarketingentity.setDepartmentName(user.getDeptName());
        reportmarketingentity.setUserId(user.getId());
        reportmarketingentity.setUserName(user.getRealName());
        reportmarketingentity.setCreateTime(new Date());
        try {
            reportmarketingentity.setReportTime(DateTimeUtils.parseDate(sdf.format(new Date()), "yyyy-MM-dd"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        reportmarketingentity.setCity(city);
        Calendar c = Calendar.getInstance();
        Date time = c.getTime();
        String reportTime = sdf.format(time);
        List<ReportMarketingEntity> reportEntities = reportMarketingService.getByUserId(user.getId(), reportTime);//只获取当天直销日报
        if (reportEntities == null || reportEntities.size() == 0) {
            reportMarketingService.save(reportmarketingentity);
        } else {
            reportMarketingService.updateByUserId(reportmarketingentity);
        }
        restObject.setEntity(reportmarketingentity);
        Map<String, Object> result = new HashMap<>();
        result.put("result", "1");
        restObject.setParaMap(result);
        return restObject;
    }

    @Override
    public Object getSalesReport(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<ReportMarketingEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<ReportMarketingEntity> data = doGetSalesReport(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getCustomerSources==result===:{}", result);
        return result;
    }

    /**
     * 获取我的直销日报
     */
    private House365RestObject doGetSalesReport(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<ReportMarketingEntity> reportEntities = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        Date time = c.getTime();
        String reportTime = sdf.format(time);
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        LOGGER.debug("==doGetCustomerSources>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            //只获取当天直销日报
            reportEntities = reportMarketingService.getByUserId(user.getId(), reportTime);
        }

        object.setList(reportEntities);
        return object;
    }

    @Override
    public Object getCustomerSources(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetCustomerSources(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getCustomerSources==result===:{}", result);
        return result;
    }

    @Override
    public Object getManagers(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        UserEntity entity = getUserEntity(phone);

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetManagers(map);
            if(entity.getShowMobile() != 1) {
                if(data.getList() != null) {
                    for (int i = 0; i < data.getList().size(); i++) {
                        data.getList().get(i).setPhone(MobileUtil.hidePhone(data.getList().get(i).getPhone()));
                    }
                }
            }
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getManagers==result===:{}", result);
        return result;
    }

    @Override
    public Object getHotLineCount(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetHotLineCount(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getHotLineCount==result===:{}", result);
        return result;
    }

    /**
     * 更新客户信息
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object modifyCustomerInfo(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doModifyCustomerInfo(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===modifyCustomerInfo==result===:{}", result);
        return result;
    }

    @Override
    public Object addBaseAttachment(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<BaseAttachment> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<BaseAttachment> data = doAddBaseAttachment(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===addBaseAttachment==result===:{}", result);
        return result;
    }


    @Override
    public Object savePicInfo2Attachment(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<BaseAttachment> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<BaseAttachment> data = doAddPic2Attachment(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===addBaseAttachment==result===:{}", result);
        return result;
    }

    @Override
    public Object deleteAttachments(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<BaseAttachment> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<BaseAttachment> data = doDeleteAttachments(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===deleteAttachments==result===:{}", result);
        return result;
    }

    @Override
    public Object getUserRoles(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<WeChatPermissionEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<WeChatPermissionEntity> data = doGetUserRoles(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getUserRoles==result===:{}", result);
        return result;
    }

    @Override
    public Object getUserFunctionRoles(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<PermissionEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<PermissionEntity> data = doGetUserFunctionRoles(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getUserRoles==result===:{}", result);
        return result;
    }

    @Override
    public Object deleteHotLineCustomer(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<WeChatPermissionEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<WeChatPermissionEntity> data = doDeletehotlinecustomer(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===deleteHotLineCustomer==result===:{}", result);
        return result;
    }

    @Override
    public Object checkCustomerPhone(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doCheckCustomerPhone(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===checkCustomerPhone==result===:{}", result);
        return result;
    }

    /**
     * 放弃400客户
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object abandonHotlineCustomer(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doAbandonCustomer(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===checkCustomerPhone==result===:{}", result);
        return result;
    }

    @Override
    public Object checkCustomerPhoneByCustomerIds(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doCheckCustomerPhoneByCustomerIds(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===checkCustomerPhoneByCustomerIds==result===:{}", result);
        return result;
    }

    @Override
    public Object deleteFormOcean(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doDeleteFormOcean(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===deleteFormOcean==result===:{}", result);
        return result;
    }

    @Override
    public Object rushCustomerList(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<RushCustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<RushCustomerEntity> data = doRushCustomerList(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===rushCustomerList==result===:{}", result);
        return result;
    }

    @Override
    public Object rushCustomer(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<RushCustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<RushCustomerEntity> data = doRushCustomer(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===rushCustomer==result===:{}", result);
        return result;
    }

    @Override
    public Object addEvaluateLog(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<EvaluateUserCustomerLogEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<EvaluateUserCustomerLogEntity> data = addEvaluateLog(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===addEvaluateLog==result===:{}", result);
        return result;
    }

    @Override
    public Object getCustomerCallbackTemplateList(Parameter parameter) throws ServiceRunException {

        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map> response = new House365RestResponse<>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.CRMStatisticParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }

        // 业务层统一处理
        try {
            String phone = getMapValueByKey("phone", map, "");
            // 获取用户
            UserEntity user = getUserEntity(phone);
            // 获取城市
            String city = departmentService.getCityByDepartmentId(user.getDeptId());
            // 获取回访内容模板
            CustomerCallbackTemplateListRequest callbackTemplateReq = new CustomerCallbackTemplateListRequest();
            callbackTemplateReq.setPaging(new Page(100));
            Map<String, Object> callbackTemplateParams = new HashMap<>(10);
            callbackTemplateParams.put("EQ_cityKey", city);
            callbackTemplateReq.setSearchParams(callbackTemplateParams);
            CustomerCallbackTemplateListResponse callbackTemplateResponse =
                    customerCallbackTemplate.getCustomerCallbackTemplateList(callbackTemplateReq);
            List<CustomerCallbackTemplateEntity> callbackTemplateList = callbackTemplateResponse.getObjectList();

            House365RestObject object = new House365RestObject();
            object.setList(callbackTemplateList);

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            response.setData(object);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===getCustomerCallbackTemplateList==result===:{}", result);
        return result;
    }

    /**
     * 添加带看评价
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<EvaluateUserCustomerLogEntity> addEvaluateLog(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<EvaluateUserCustomerLogEntity> restObject = new House365RestObject<>();

        String phone = getMapValueByKey("phone", map, "");
        String projectId = getMapValueByKey("projectId", map, "");
        String projectName = getMapValueByKey("projectName", map, "");
        String seeDate = getMapValueByKey("seeDate", map, "");
        String customerName = getMapValueByKey("customerName", map, "");
        String channel = getMapValueByKey("channel", map, "");
        LOGGER.debug("==addEvaluateLog>>phone:{}==projectId:{}==projectName:{}==seeDate:{}==customerName:{}==channel:{}==",
                phone, projectId, projectName, seeDate, customerName, channel);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(projectId)
                && !Strings.isNullOrEmpty(seeDate) && !Strings.isNullOrEmpty(customerName)) {
            UserEntity user = getUserEntity(phone);
            String city = departmentService.getCityByDepartmentId(user.getDeptId());

            EvaluateUserCustomerLogEntity evaluate = new EvaluateUserCustomerLogEntity();
            evaluate.setUserId(user.getId());
            evaluate.setUserName(user.getRealName());
            evaluate.setProjectId(Integer.valueOf(projectId));
            evaluate.setProjectName(projectName);
            evaluate.setCustomerName(customerName);
            evaluate.setIsDeleted(0);
            evaluate.setIsEvaluated(0);
            evaluate.setCheckStatus(0);
            Date date = DateTimeUtils.parseDate(seeDate, "yyyy-MM-dd");
            //创建时间添加判断
            if (date == null) {
                evaluate.setCreateTime(new Date());
            } else {
                evaluate.setCreateTime(DateTimeUtils.parseDate(seeDate, "yyyy-MM-dd"));
            }
            evaluate.setCity(city);
            evaluate.setChannel(Integer.valueOf(channel));
            evaluateUserCustomerLogService.save(evaluate);

            restObject.setEntity(evaluate);
        }
        return restObject;
    }

    /**
     * 抢客操作
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<RushCustomerEntity> doRushCustomer(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<RushCustomerEntity> restObject = new House365RestObject<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String rushCustomerId = getMapValueByKey("rushCustomerId", map, "");
        LOGGER.debug("==doRushCustomer>>customerId:{}==", rushCustomerId);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(rushCustomerId)) {
            RushCustomerEntity rushCustomer = (RushCustomerEntity) rushCustomerService.getById(
                    Integer.valueOf(rushCustomerId));

            if (rushCustomer == null) {
                Map<String, Object> resultMap = new HashMap<>(10);
                resultMap.put("code", "1");
                resultMap.put("msg", "抱歉，抢客失败！客户不存在！");
                restObject.setParaMap(resultMap);
                return restObject;
            }

            UserEntity user = getUserEntity(phone);
            if (user == null) {
                Map<String, Object> resultMap = new HashMap<>(10);
                resultMap.put("code", "1");
                resultMap.put("msg", "抱歉，抢客失败！用户不存在！");
                restObject.setParaMap(resultMap);
                return restObject;
            }

            //锁定客户，去除缓存
            Integer goodCount = redisUtils.popIntegerFromRedisList(HGSConstant.RUSH_CUSTOMER_LEFT_LIST + rushCustomerId);

            if (goodCount == null || goodCount != 1) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("code", "1");
                resultMap.put("msg", "抱歉，抢客失败！客户" + rushCustomer.getName() + "已被抢，请您更换其他客户");
                restObject.setParaMap(resultMap);
                return restObject;
            }

            hgsCacheUtil.delUserSummary(user.getId());

            //客户信息入客户表
            CustomerEntity customerEntity = new CustomerEntity();

            Map<String, Object> customerMap = new HashMap<>(10);
            customerMap.put("EQ_customerRelId", rushCustomerId);
            QueryParams<CustomerEntity> queryParams = new QueryParams<>(customerMap);
            List<CustomerEntity> customerEntities = customerService.queryAll(queryParams);
            if (customerEntities != null && customerEntities.size() != 0) {
                customerEntity = customerEntities.get(0);

                customerEntity.setManagerId(user.getId());
                customerEntity.setIsRecycled(0);
                customerEntity.setManagerName(user.getRealName());
                customerEntity.setUpdateTime(new Date());
                customerEntity.setUpdater(String.valueOf(user.getId()));
                //重置客户绑定置业顾问时间
                customerEntity.setBindTime(new Date());
                customerService.update(customerEntity);
            } else {
                //更新来源
                Integer sourceId = customerSourceService.updateSource(customerEntity.getCityCode(),
                        customerEntity.getActSource(), customerEntity.getCreateSource(), "CRM");
                customerEntity.setActSourceId(sourceId);

                customerEntity.setName(rushCustomer.getName());
                customerEntity.setPhone(rushCustomer.getPhone());
                customerEntity.setCityCode(rushCustomer.getCityCode());
                customerEntity.setCityName(rushCustomer.getCityName());
                customerEntity.setCrmId(rushCustomer.getCrmId());
                customerEntity.setSex(rushCustomer.getSex());
                customerEntity.setBizPort(rushCustomer.getBizPort());
                customerEntity.setActSource(rushCustomer.getActSource());
                customerEntity.setFirstSource(rushCustomer.getFirstSource());
                customerEntity.setCreateSource(rushCustomer.getCreateSource());
                customerEntity.setCustomerType(rushCustomer.getCustomerType());
                customerEntity.setLatestSource(rushCustomer.getLatestSource());
                customerEntity.setCrmLatestCall(rushCustomer.getCrmLatestCall());
                customerEntity.setCrmLatestCallResult(rushCustomer.getCrmLatestCallResult());
                customerEntity.setCreateTime(new Date());
                customerEntity.setCreater(rushCustomer.getCreater());
                customerEntity.setUpdater(user.getName());
                customerEntity.setUpdateTime(new Date());
                customerEntity.setStatus(Constant.CustomerStatusEnum.NORECORD.getStatus());
                customerEntity.setBuyIntention(rushCustomer.getBuyIntention());
                customerEntity.setCustomerSourceType(HGSConstant.CustomerSourceType.ROB.getType());
                customerEntity.setCustomerRelId(rushCustomer.getId());
                customerEntity.setTraceStatus(HGSConstant.TRACE_STATUS_INVALID);
                customerEntity.setCrmSync(HGSConstant.CrmSyncStatus.DONE.getType());
                //数据公海中客户购房意向为“无效”的客户，如果被派工后，统一提升客户的“购房意向”为：待定
                customerEntity.setBuyIntention("");
                customerEntity.setIsDelete(0);

                customerEntity.setManagerId(user.getId());
                customerEntity.setIsRecycled(0);
                customerEntity.setManagerName(user.getRealName());
                customerEntity.setUpdateTime(new Date());
                customerEntity.setUpdater(String.valueOf(user.getId()));
                //重置客户绑定置业顾问时间
                customerEntity.setBindTime(new Date());
                customerService.save(customerEntity);

                //记录客户新增日志
                logUtils.saveCustomerLog(customerEntity, 1, 0, user.getRealName());
            }

            //保存客户被抢信息
            rushCustomer.setManagerId(user.getId());
            rushCustomer.setManagerName(user.getRealName());
            rushCustomer.setRushStatus(1);
            rushCustomer.setUpdateTime(new Date());
            rushCustomer.setStatus(1);
            rushCustomerService.update(rushCustomer);

            Map<String, String> param = new HashMap<>(10);
            param.put("customerId", customerEntity.getId().toString());
            customerService.sendMessageToWechat(NEWCUSTOMER, String.valueOf(user.getId()), param);

            Map<String, Object> resultMap = new HashMap<>(10);
            resultMap.put("code", "0");
            resultMap.put("msg", "恭喜抢客成功！客户" + rushCustomer.getName() + "已添加至客户列表，请前往查看");
            restObject.setParaMap(resultMap);
        }
        return restObject;
    }

    /**
     * 获取抢客列表
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<RushCustomerEntity> doRushCustomerList(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<RushCustomerEntity> restObject = new House365RestObject<>();

        String pageNo = getMapValueByKey("page", map, "0");
        String pageSize = getMapValueByKey("pageSize", map, PAGENO);

        String timeType = getMapValueByKey("timeType", map, "");
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        LOGGER.debug("==doRushCustomerList>>timeType:{}==", timeType);
        if (!Strings.isNullOrEmpty(timeType) && !Strings.isNullOrEmpty(phone)) {
            try {
                UserEntity user = getUserEntity(phone);
                Map<String, Object> searchParams = new HashMap<>(10);

                searchParams.put("EQ_isDeleted", 0);
                searchParams.put("EQ_type" + 0, 0);
                searchParams.put("REGEXP_urlPath", "^" + user.getDeptUrlPath() + "$|^" + user.getDeptUrlPath() + "/");

                Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
                calendar.setTime(new Date());
                // 时间过滤 半小时推送一次
                int minute = Integer.valueOf(DateTimeUtils.parseDate(calendar.getTime(), "mm"));
                //timeType 1:30分钟内；2：30分钟外；
                if ("1".equals(timeType)) {
                    if (minute >= 30) {
                        searchParams.put("LTE_createTimeEnd",
                                DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:30:00"));
                        searchParams.put("GTE_createTimeStart",
                                DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:00:00"));
                    } else {
                        searchParams.put("LTE_createTimeEnd",
                                DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:00:00"));
                        calendar.add(Calendar.HOUR, -1);
                        searchParams.put("GTE_createTimeStart",
                                DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:30:00"));
                    }
                } else if ("2".equals(timeType)) {
                    if (minute >= 30) {
                        searchParams.put("LTE_createTimeEnd",
                                DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:00:00"));
                    } else {
                        calendar.add(Calendar.HOUR, -1);
                        searchParams.put("LTE_createTimeEnd",
                                DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:30:00"));
                    }
                }

                Page page = new Page();
                if (null != pageNo) {
                    page.setCurrentPage(Integer.parseInt(pageNo));
                }
                if (null != pageSize) {
                    page.setPageSize(Integer.parseInt(pageSize));
                }

                QueryParams<RushCustomerEntity> queryParams = new QueryParams<>(searchParams);
                queryParams.setPaging(page);
                queryParams.setOrderColumn("create_time");
                queryParams.setOrderMode("desc");
                List<RushCustomerEntity> rushCustomers = rushCustomerService.queryAllShow(queryParams);
                restObject.setList(rushCustomers);
            } catch (Exception ex) {
                LOGGER.error(ex.getMessage(), ex);
            }
        }
        return restObject;
    }

    /**
     * 删除数据公海无效客户
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<CustomerEntity> doDeleteFormOcean(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();

        String customerId = getMapValueByKey("customerId", map, "");
        LOGGER.debug("==doDeleteFormOcean>>customerId:{}==", customerId);
        if (!Strings.isNullOrEmpty(customerId)) {
            customer.setDeleteFlag(Integer.valueOf(customerId), 0, "deleteFormOcean接口");
        }
        return restObject;
    }

    /**
     * 检查用户手机号
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<CustomerEntity> doCheckCustomerPhone(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();

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

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerPhone = getMapValueByKey("customerPhone", map, "");
        LOGGER.debug("==doCheckCustomerPhone>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(customerPhone)) {
            UserEntity user = getUserEntity(phone);

            Map<String, Object> queryManagerMap = new HashMap<>(10);
            queryManagerMap.put("EQ_phone", customerPhone);
            queryManagerMap.put("EQ_managerId", user.getId());
            queryManagerMap.put("EQ_hotline", "0");
            QueryParams<Map<String, String>> queryManagerParams = new QueryParams<>(queryManagerMap);

            List<CustomerEntity> managerCustomers = customerService.queryAll(queryManagerParams);
            if (CollectionUtils.isNotEmpty(managerCustomers)) {
                result.put("result", "0");
                result.put("msg", "该号码已存在与当前帐号下");
                restObject.setParaMap(result);
                return restObject;
            }

            String city = departmentService.getCityByDepartmentId(user.getDeptId());
            //南京站添加用户，重复用户的提示，仅提示自己名下的重复手机号码，其他站保持线上不变。
            if (!"nj".equals(city)) {
                Map<String, Object> queryCityMap = new HashMap<>(10);
                queryCityMap.put("EQ_phone", customerPhone);
                if (org.apache.commons.lang.StringUtils.isNotBlank(city)) {
                    queryCityMap.put("EQ_cityCode", city);
                }
                queryCityMap.put("EQ_hotline", "0");
                QueryParams<Map<String, String>> queryCityParams = new QueryParams<>(queryCityMap);
                List<CustomerEntity> cityCustomers = customerService.queryAll(queryCityParams);
                if (CollectionUtils.isNotEmpty(cityCustomers)) {
                    result.put("result", "0");
                    result.put("msg", "该号码已存在于他人帐号下");
                    restObject.setParaMap(result);
                    return restObject;
                }
            }

            result.put("result", "1");
            restObject.setParaMap(result);
        }
        return restObject;
    }


    private House365RestObject<CustomerEntity> doAbandonCustomer(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();

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

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerId = getMapValueByKey(Constant.CUSTOMER_ID, map, "");
        LOGGER.debug("==doCheckCustomerPhone>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            Date cur = new Date();
            CustomerEntity customerEntity = customerService.getById(Integer.valueOf(customerId));
            if (customerEntity != null) {
                customerEntity.setStatus(2);//2:放弃
                customerEntity.setUpdateTime(cur);
                customerEntity.setUpdater(String.valueOf(user.getId()));
                customerService.update(customerEntity);
            }
            result.put("msg", "已放弃");
            result.put("result", "1");
            restObject.setParaMap(result);
        }
        return restObject;
    }

    /**
     * 检查用户手机号
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<CustomerEntity> doCheckCustomerPhoneByCustomerIds(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();

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

        String userId = getMapValueByKey("userId", map, "");
        String customerId = getMapValueByKey("customerId", map, "");
        LOGGER.debug("==doCheckCustomerPhoneByCustomerIds>>customerId:{}==", customerId);
        if (!Strings.isNullOrEmpty(userId) && !Strings.isNullOrEmpty(customerId)) {
            UserEntity user = userService.getById(Integer.valueOf(userId));
            CustomerEntity customer = customerService.getById(Integer.valueOf(customerId));

            Map<String, Object> queryManagerMap = new HashMap<>();
            queryManagerMap.put("EQ_phone", customer.getPhone());
            queryManagerMap.put("EQ_managerId", user.getId());
            queryManagerMap.put("EQ_hotline", "0");
            QueryParams<Map<String, String>> queryManagerParams = new QueryParams<>(queryManagerMap);

            List<CustomerEntity> managerCustomers = customerService.queryAll(queryManagerParams);
            if (CollectionUtils.isNotEmpty(managerCustomers)) {
                result.put("result", "0");
                result.put("msg", "该号码已存在与当前帐号下");
                restObject.setParaMap(result);
                return restObject;
            }

            String city = departmentService.getCityByDepartmentId(user.getDeptId());
            //南京站添加用户，重复用户的提示，仅提示自己名下的重复手机号码，其他站保持线上不变。
            if (!"nj".equals(city)) {
                Map<String, Object> queryCityMap = new HashMap<>(10);
                queryCityMap.put("EQ_phone", customer.getPhone());
                if (org.apache.commons.lang.StringUtils.isNotBlank(city)) {
                    queryCityMap.put("EQ_cityCode", city);
                }
                queryCityMap.put("EQ_hotline", "0");
                QueryParams<Map<String, String>> queryCityParams = new QueryParams<>(queryCityMap);
                List<CustomerEntity> cityCustomers = customerService.queryAll(queryCityParams);
                if (CollectionUtils.isNotEmpty(cityCustomers)) {
                    result.put("result", "0");
                    result.put("msg", "该号码已存在于他人帐号下");
                    restObject.setParaMap(result);
                    return restObject;
                }
            }

            result.put("result", "1");
            restObject.setParaMap(result);
        }
        return restObject;
    }

    /**
     * 删除400来电客户
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<WeChatPermissionEntity> doDeletehotlinecustomer(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<WeChatPermissionEntity> restObject = new House365RestObject<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerId = getMapValueByKey(Constant.CUSTOMER_ID, map, "");
        LOGGER.debug("==doDeletehotlinecustomer>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(customerId)) {
            UserEntity user = getUserEntity(phone);

            CustomerEntity customer = customerService.getById(Integer.valueOf(customerId));
            if (customer != null) {
                if (customer.getStatus() == 98) {//98:未跟踪
                    customer.setIsDelete(1);//未跟踪400客户原先删除进入私客改为直接删除,1：删除
                }
                customer.setStatus(Constant.HotLineStatusEnum.DELETE.getMsg());
                customer.setUpdateTime(new Date());
                customer.setUpdater(user.getRealName());
                customerService.update(customer);
            }
        }
        return restObject;
    }

    /**
     * 获取用户权限列表
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<WeChatPermissionEntity> doGetUserRoles(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<WeChatPermissionEntity> restObject = new House365RestObject<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        LOGGER.debug("==doGetUserRoles>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            if (user != null) {
                //不实时更新preLoginTime（两个小时更新一次）
                Date preLoginTime = user.getPreLoginTime();
                Date now = new Date();
                long a = (now.getTime() - preLoginTime.getTime());
                long b = 2 * 60 * 60 * 1000;
                if (a > b) {
                    user.setPreLoginTime(user.getLastLoginTime());
                    user.setLastLoginTime(new Date());
                    userService.update(user);
                }

                List<WeChatPermissionEntity> userRoles = weChatPermissionService.getPermissionsByUserId(user.getId());
                restObject.setList(userRoles);
            }
        }
        return restObject;
    }

    /**
     * 获取用户操作权限列表
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<PermissionEntity> doGetUserFunctionRoles(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<PermissionEntity> restObject = new House365RestObject<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        LOGGER.debug("==doGetUserRoles>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            if (user != null) {
                //不实时更新preLoginTime（两个小时更新一次）
                Date preLoginTime = user.getPreLoginTime();
                Date now = new Date();
                long a = (now.getTime() - preLoginTime.getTime());
                long b = 2 * 60 * 60 * 1000;
                if (a > b) {
                    user.setPreLoginTime(user.getLastLoginTime());
                    user.setLastLoginTime(new Date());
                    userService.update(user);
                }
//                user.setPreLoginTime(user.getLastLoginTime());
//                user.setLastLoginTime(new Date());
//                userService.update(user);

                List<PermissionEntity> userRoles = permissionService.getFunctionPermissionsByUserId(user.getId());
                restObject.setList(userRoles);
            }
        }
        return restObject;
    }

    /**
     * 删除图片
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<BaseAttachment> doDeleteAttachments(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<BaseAttachment> restObject = new House365RestObject<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        LOGGER.debug("==doGetUserRoles>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);

            List<BaseAttachment> attachments = attachmentService.queryByResourceIdAndResouceType(
                    user.getId().toString(), "wechat");
            for (BaseAttachment attachment : attachments) {
                attachmentService.delete(attachment.getId());
            }
        }
        return restObject;
    }


    private House365RestObject<BaseAttachment> doAddPic2Attachment(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<BaseAttachment> restObject = new House365RestObject<>();

        String entityStr = map.get("entity").toString();
        map.remove("entity");
        JSONObject entity = JSONObject.fromObject(entityStr);

        String resourceId = entity.getString("resourceId");

        BaseAttachment attachment = new BaseAttachment();
        String resourceType = entity.getString("resourceType");
        String name = entity.getString("name");
        String suffix = entity.getString("suffix");
        String size = entity.getString("size");
        String remotePath = entity.getString("remotePath");
        attachment.setResourceId(Integer.valueOf(resourceId));
        attachment.setResourceType(resourceType);
        attachment.setBizType(0);
        attachment.setName(name);
        attachment.setSuffix(suffix);
        attachment.setSize(Long.valueOf(size));
        attachment.setRemotePath(remotePath);
        attachmentService.save(attachment);
        restObject.setEntity(attachment);
        return restObject;
    }

    /**
     * 添加图片
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject<BaseAttachment> doAddBaseAttachment(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<BaseAttachment> restObject = new House365RestObject<>();

        String entityStr = map.get("entity").toString();
        map.remove("entity");
        JSONObject entity = JSONObject.fromObject(entityStr);

        String phone = entity.getString("resourceId");
        LOGGER.debug("==doAddBaseAttachment>>phone:{}==entity:{}", phone, entityStr);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);

            BaseAttachment attachment = new BaseAttachment();
            String resourceType = entity.getString("resourceType");
            String name = entity.getString("name");
            String suffix = entity.getString("suffix");
            String size = entity.getString("size");
            String remotePath = entity.getString("remotePath");
            attachment.setResourceId(user.getId());
            attachment.setResourceType(resourceType);
            attachment.setBizType(0);
            attachment.setName(name);
            attachment.setSuffix(suffix);
            attachment.setSize(Long.valueOf(size));
            attachment.setRemotePath(remotePath);
            attachmentService.save(attachment);
            restObject.setEntity(attachment);
        }
        return restObject;
    }

    /**
     * 更新客户信息
     */
    private House365RestObject doModifyCustomerInfo(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerId = getMapValueByKey(Constant.CUSTOMER_ID, map, "0");
        String key = getMapValueByKey("key", map, "");
        String value = getMapValueByKey("value", map, "");

        LOGGER.debug("==doModifyCustomerInfo>>phone:{}==customerId:{}==key:{}==value:{}==", phone, customerId, key,
                value);

        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(customerId)) {
            UserEntity user = getUserEntity(phone);
            CustomerEntity oldEntity = customerService.getById(Integer.valueOf(customerId));
            CustomerEntity customerEntity = mergeMapper.queryById(Integer.valueOf(customerId));

            boolean removeCustomer = false;

            if ("null".equalsIgnoreCase(value)) {
                value = "";
            }

            switch (key) {
                case "customerName":
                    customerEntity.setName(value);
                    break;
                case "sex":
                    customerEntity.setSex(Integer.valueOf(value));
                    break;
                case "buyIntention":
                    if ("5".equalsIgnoreCase(value)) {
                        removeCustomer = true;
                    }
                    customerEntity.setBuyIntention("99".equalsIgnoreCase(value) ? "" : value);
                    break;
                case "traceStatus":
                    customerEntity.setTraceStatus(Integer.valueOf(value));
                    break;
                case "bakPhone1":
                    customerEntity.setBakPhone1(value);
                    break;
                case "bakPhone2":
                    customerEntity.setBakPhone2(value);
                    break;
                case "bakPhone3":
                    customerEntity.setBakPhone3(value);
                    break;
                default:
                    break;
            }
            customerEntity.setUpdater(user.getName());
            customerEntity.setUpdateTime(new Date());
            customerService.update(customerEntity);

            Map<String, Object> updateMap = new HashMap<>(10);
            updateMap.put("name", customerEntity.getName());
            updateMap.put("bakPhone1", customerEntity.getBakPhone1());
            updateMap.put("sex", customerEntity.getSex());
            updateMap.put("updateTime", new Date());
            updateMap.put("updater", user.getName());
            updateMap.put("buyIntention", customerEntity.getBuyIntention());
            updateMap.put("traceStatus", customerEntity.getTraceStatus());
            updateMap.put("id", Integer.valueOf(customerId));
            mergeMapper.update(updateMap);

            //添加客户更新日志
            CustomerEntity newEntity = customerService.getById(Integer.valueOf(customerId));
            logUtils.newRecordOperateLog(oldEntity, newEntity, Integer.valueOf(customerId), 0, user.getRealName());
            if (removeCustomer) {
                //删除合并客户
//                List<CustomerEntity> customerList = customer.getDetailCustomers(oldEntity.getPhone(), oldEntity.getManagerId());
//                Map<String, Object> idMap = new HashMap<String, Object>();
//                List idList = new ArrayList();
//                if(customerList!=null){
//                    for(CustomerEntity ce:customerList){
//                        idList.add(ce.getId());
//                    }
//                }
//                idMap.put("ids", idList);
//                customer.deleteCustomerMergeById(idMap);
                customer.deleteSingleCustomer(customerEntity);
                customer.removeCustomer(customerEntity.getId(), user.getId());
            }
        }
        return object;
    }

    /**
     * 获取400热线计数列表
     */
    private House365RestObject doGetHotLineCount(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        JSONObject hotLineCount = new JSONObject();

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        if (StringUtils.isNotBlank(phone)) {
            UserEntity user = getUserEntity(phone);

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

            //只展示当前城市下的400客户
            DepartmentEntity department = departmentService.getById(user.getDeptId());
            DepartmentEntity city = departmentService.getById(Integer.valueOf(department.getCityID()));
            List<Integer> userIds = userService.getUserIdOnPath(user.getId());

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(DateTimeUtils.getDateByString(DateTimeUtils.parseDate(new Date(), "yyyy-MM-dd 23:59:59")));

            //来源为 400电话
            searchParams.put("EQ_userIds", Joiner.on(",").join(userIds));
            searchParams.put("EQ_createSource", Constant.CustomerSourceEnum.HOTLINE.getMsg());
            searchParams.put("EQ_cityCode", city.getDescripition());
            searchParams.put("NOTEQ_status", Constant.HotLineStatusEnum.DELETE.getMsg().intValue());
            searchParams.put("LTE_createTimeEnd", calendar.getTime());
            calendar.add(Calendar.DATE, -1);
            searchParams.put("GTE_createTimeStart", calendar.getTime());
            QueryParams todayParams = new QueryParams(searchParams);
            int todayCount = customerService.getTotalCount(todayParams);
            hotLineCount.put("todayCount", todayCount);

            searchParams.clear();
            //来源为 400电话
            searchParams.put("EQ_userIds", Joiner.on(",").join(userIds));
            searchParams.put("EQ_createSource", Constant.CustomerSourceEnum.HOTLINE.getMsg());
            searchParams.put("EQ_cityCode", city.getDescripition());
            searchParams.put("NOTEQ_status", Constant.HotLineStatusEnum.DELETE.getMsg().intValue());
            searchParams.put("LTE_createTimeEnd", calendar.getTime());
            calendar.add(Calendar.DATE, -Calendar.DAY_OF_WEEK);
            searchParams.put("GTE_createTimeStart", calendar.getTime());
            QueryParams lastWeekParams = new QueryParams(searchParams);
            int lastWeekCount = customerService.getTotalCount(lastWeekParams);
            hotLineCount.put("lastWeekCount", lastWeekCount);

            searchParams.clear();
            //来源为 400电话
            searchParams.put("EQ_userIds", Joiner.on(",").join(userIds));
            searchParams.put("EQ_createSource", Constant.CustomerSourceEnum.HOTLINE.getMsg());
            searchParams.put("EQ_cityCode", city.getDescripition());
            searchParams.put("NOTEQ_status", Constant.HotLineStatusEnum.DELETE.getMsg().intValue());
            QueryParams historyParams = new QueryParams(searchParams);
            int allCount = customerService.getTotalCount(historyParams);
            hotLineCount.put("allCount", allCount);
        }
        object.setEntity(hotLineCount);
        return object;
    }

    /**
     * 获取置业顾问列表
     */
    private House365RestObject doGetManagers(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<UserEntity> sourceEntities = new ArrayList<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        LOGGER.debug("==doGetManagers>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            Map<String, Object> searchParams = new HashMap<>();

            //是总部员工，选择当前城市和下属所有部门员工 ， 非管理员，选登录用户下属所有部门员工和自己
            String urlPath = user.getDeptUrlPath() + "/";

            searchParams.put("LIKE_deptUrlPath", urlPath);

            QueryParams<UserEntity> queryParams = new QueryParams<>(searchParams);
            sourceEntities = userService.queryAll(queryParams);
            sourceEntities.add(0, user);
        }

        object.setList(sourceEntities);
        return object;
    }

    /**
     * 获取我的项目列表
     */
    private House365RestObject doGetCustomerSources(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<CustomerSourceEntity> sourceEntities = new ArrayList<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        LOGGER.debug("==doGetCustomerSources>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            DepartmentEntity department = departmentService.getById(user.getDeptId());
            DepartmentEntity city = departmentService.getById(Integer.valueOf(department.getCityID()));
            Map<String, Object> searchParams = new HashMap<>(10);
            searchParams.put("EQ_city", city.getDescripition());
            searchParams.put("EQ_status", "1");
            QueryParams<CustomerSourceEntity> queryParams = new QueryParams<>(searchParams);
            sourceEntities = customerSourceService.queryAll(queryParams);
        }

        object.setList(sourceEntities);
        return object;
    }

    private House365RestObject<CustomerEntity> doAddCustomer(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();

        String entityStr = map.get("entity").toString();
        map.remove("entity");
        JSONObject entity = JSONObject.fromObject(entityStr);
        Date newdate = new Date();
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String name = entity.containsKey(Constant.CUSTOMER_NAME) ? entity.getString(Constant.CUSTOMER_NAME) : "";
        String customerPhone = entity.containsKey(Constant.CUSTOMER_PHONE) ? entity.getString(
                Constant.CUSTOMER_PHONE) : "";
        String sex = entity.containsKey(Constant.CUSTOMER_SEX) ? entity.getString(Constant.CUSTOMER_SEX) : "";
        String actSource = entity.containsKey(Constant.CUSTOMER_ACTSOURCE) ? entity.getString(
                Constant.CUSTOMER_ACTSOURCE) : "";

        int traceStatus = entity.containsKey(Constant.CUSTOMER_TRACESTATUS) ? entity.getInt(
                Constant.CUSTOMER_TRACESTATUS) : TRACE_STATUS_INVALID;

        LOGGER.debug("==doAddCustomer>>phone:{}==name:{}==customerPhone:{}==sex:{}==actSource:{}==", phone, name,
                customerPhone, sex, actSource);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(name) && !Strings.isNullOrEmpty(
                customerPhone) && !Strings.isNullOrEmpty(sex) && !Strings.isNullOrEmpty(actSource)) {
            UserEntity user = getUserEntity(phone);
            DepartmentEntity department = departmentService.getById(user.getDeptId());

            String bakPhone1 = entity.containsKey("bakPhone1") ? entity.getString("bakPhone1") : null;
            String bakPhone2 = entity.containsKey("bakPhone2") ? entity.getString("bakPhone2") : null;
            String bakPhone3 = entity.containsKey("bakPhone3") ? entity.getString("bakPhone3") : null;
            String remark = entity.containsKey("remark") ? entity.getString("remark") : "";
            String buyIntention = entity.containsKey("buyIntention") ? entity.getString("buyIntention").equals(
                    "99") ? "" : entity.getString("buyIntention") : "";

            String cityCode = "nj";
            String cityName = "南京";
            DepartmentEntity cityBean = departmentService.getById(Integer.valueOf(department.getCityID()));
            if (cityBean != null) {
                cityCode = cityBean.getDescripition();
                cityName = cityBean.getName();
            }

            actSource = StringUtils.StringFilter(actSource);
            CustomerEntity customerEntity = new CustomerEntity();
            customerEntity.setName(name);
            customerEntity.setPhone(customerPhone);
            customerEntity.setCityCode(cityCode);
            customerEntity.setCityName(cityName);
            customerEntity.setSex(Integer.valueOf(sex));
            customerEntity.setActSource(actSource);
            customerEntity.setCreateSource(Constant.CustomerSourceEnum.WECHAT.getMsg());
            customerEntity.setCustomerType(Constant.CustomerTypeEnum.ONLINE.getMsg());
            customerEntity.setCreateTime(newdate);
            customerEntity.setCreater(Constant.CustomerSourceEnum.WECHAT.getMsg());
            customerEntity.setManagerName(user.getRealName());
            customerEntity.setManagerId(user.getId());
            customerEntity.setIsRecycled(0);
            customerEntity.setUpdater(Constant.CustomerSourceEnum.WECHAT.getMsg());
            customerEntity.setUpdateTime(newdate);
            customerEntity.setStatus(Constant.CustomerStatusEnum.NORECORD.getStatus());
            customerEntity.setBuyIntention(buyIntention);
            customerEntity.setTraceStatus(traceStatus);
            customerEntity.setCrmSync("0");
            customerEntity.setBakPhone1(bakPhone1);
            customerEntity.setBakPhone2(bakPhone2);
            customerEntity.setBakPhone3(bakPhone3);
            customerEntity.setIsDelete(0);
            customerEntity.setRemark(remark);
            //客户类型为常规
            customerEntity.setCustomerSourceType(1);
            //重置客户绑定置业顾问时间
            customerEntity.setBindTime(newdate);
            customerService.createCustomer(customerEntity, user.getRealName(), user.getRealName());
            //添加回访记录
            if (StringUtils.isNotBlank(remark)) {
                addCustomerCallBackNew(customerEntity.getId().toString(), remark, user);
            }
            //合并之后的表:更新or新增
            CustomerEntity oldEntity = customer.getCustomerMerge(customerEntity.getPhone(), user.getId());
            if (oldEntity == null) {
                //系统新增客户回访时间
                handleCustomerMerge(customerEntity);
                customer.saveCustomerMerge(customerEntity);
                //公海客户查询
                List<CustomerEntity> seaCustomers = customer.getSeaCustomerByPhone(customerEntity, user);
                //去公海原顾问名下此客户同步更新
                if (seaCustomers != null && seaCustomers.size() > 0) {
                    customer.updateSeaCustomerByPhone(customerEntity, user);
                }
            } else {
                mergeCustomerUtil.checkMergeCustomer(customerEntity, oldEntity, user.getId(), user.getRealName());
                // 意向等级、跟踪状态更新
                oldEntity.setUpdateTime(newdate);
                oldEntity.setBindTime(newdate);
                oldEntity.setUpdater(String.valueOf(user.getId()));
                oldEntity.setIsActive(0);
                oldEntity.setIsHandover(0);
                handleCustomerMerge(oldEntity);
//                customerEntity.setLastCallTime(newdate);
                mergeMapper.updateCustomerMerge(oldEntity);
            }
            restObject.setEntity(customerEntity);
        }
        return restObject;
    }

    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());
            }
        }
        return currentCustomer;
    }

    private House365RestObject<Boolean> doAddCall(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        object.setEntity(Boolean.FALSE);

        String customerId = getMapValueByKey("customerId", map, "");
        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String content = getMapValueByKey("content", map, "");
        String buyIntention = getMapValueByKey("buyIntention", map, "").equalsIgnoreCase("99") ? "" : getMapValueByKey(
                "buyIntention", map, "");
        LOGGER.debug("==doAddCall>>customerId:{}==phone:{}==", customerId, phone);
        if (null != customerId && !Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(
                content) && !Strings.isNullOrEmpty(buyIntention)) {
            try {
                UserEntity userEntity = getUserEntity(phone);
                CustomerEntity customerEntity = addCustomerCallBack(customerId, content, buyIntention, userEntity);

                if ("4".equalsIgnoreCase(buyIntention)) {
                    customer.removeCustomer(customerEntity.getId(), userEntity.getId());
                }

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

        return object;
    }

    /**
     * 添加回访记录
     *
     * @param customerId   会员id
     * @param content      回访信息
     * @param buyIntention 购房意向
     * @param userEntity   客户经理
     * @return
     */
    private CustomerEntity addCustomerCallBack(
            String customerId, String content, String buyIntention, UserEntity userEntity
    ) {
        addCallBack(userEntity, customerId, content);
        CustomerResponse customerResponse = customer.getCustomerById(Integer.valueOf(customerId));
        CustomerEntity customerEntity = customerResponse.getEntity();
        customerEntity.setBuyIntention("99".equalsIgnoreCase(buyIntention) ? "" : buyIntention);
        //更新回访记录的时候，同时更新会员备注
        customerEntity.setRemark(content);
        CustomerRequest customerRequest = new CustomerRequest();
        customerRequest.setEntity(customerEntity);
        customer.updateCustomerNew(customerRequest, userEntity.getId(), userEntity.getRealName());
        customer.crmAddCallBack(Integer.valueOf(customerId));
        return customerEntity;
    }

    /**
     * 添加回访记录(新增客户使用)
     *
     * @param customerId 会员id
     * @param content    回访信息
     * @param userEntity 客户经理
     * @return
     */
    private void addCustomerCallBackNew(String customerId, String content, UserEntity userEntity) {
        addCallBack(userEntity, customerId, content);
        customer.crmAddCallBack(Integer.valueOf(customerId));
    }

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

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

    private House365RestObject<Boolean> doDeleteCustoemr(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        object.setEntity(Boolean.FALSE);
        String customerId = getMapValueByKey("customerId", map, "");

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity userEntity = getUserEntity(phone);
            House365RestResponse restResponse = new House365RestResponse();
            restResponse.setResult("1");
            if (null != customerId && userEntity != null) {
                try {
                    customer.removeCustomer(Integer.valueOf(customerId), userEntity.getId());
                    object.setEntity(Boolean.TRUE);
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }

        return object;
    }

    private House365RestObject<CustomerInfoVO> doGetCustoemrInfo(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        CustomerInfoVO customerInfoVO = new CustomerInfoVO();
        String customerId = getMapValueByKey("customerId", map, "");


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

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(customerId)) {
            UserEntity userEntity = getUserEntity(phone);

            List<Integer> userIds = userService.getUserIdOnPath(userEntity.getId());

            CustomerResponse customerResponse = customer.getCustomerById(Integer.valueOf(customerId));
            CustomerEntity customerEntity = customerResponse.getEntity();
            if (customerEntity.getManagerId() == null || !userIds.contains(customerEntity.getManagerId())) {
                object.setEntity(null);
                return object;
            }

            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<>();
            callMap.put("EQ_customerId", customerId);
            CustomerCallbackLogListRequest cclr = new CustomerCallbackLogListRequest();
            cclr.setSearchParams(callMap);
            cclr.setPaging(page);

            CustomerCallbackLogListResponse cc = customerCallbackLog.getCustomerCallbackLogList(cclr);
            customerInfoVO.setCallbackLogEntities(cc.getObjectList());
            customerInfoVO.setCustomerProjectEntities(cpl.getObjectList());
            customerInfoVO.setCustomerEntity(customerEntity);

            object.setEntity(customerInfoVO);
        }
        return object;
    }

    private House365RestObject<Boolean> doBindToProjects(Map<String, Object> map) throws Exception {
        House365RestObject<Boolean> object = new House365RestObject();
        object.setEntity(Boolean.FALSE);
        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String projectIds = getMapValueByKey("projectIds", map, "");
        String customerIds = getMapValueByKey("customerIds", map, "");
        try {
            if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(projectIds) && !Strings.isNullOrEmpty(
                    customerIds)) {
                UserEntity userEntity = getUserEntity(phone);

                if (!Strings.isNullOrEmpty(projectIds) && !Strings.isNullOrEmpty(customerIds)) {
                    customer.bindProject(projectIds, customerIds, userEntity.getName());
                    object.setEntity(Boolean.TRUE);
                }

            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return object;
    }


    private House365RestObject<ProjectEntity> doGetAssignProjects(Map<String, Object> map) throws Exception {

        House365RestObject<ProjectEntity> object = new House365RestObject();

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerId = getMapValueByKey("customerId", map, "");
        String projectName = getMapValueByKey("projectName", map, "");
        projectName = URLDecoder.decode(projectName, "UTF-8");

        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(customerId)) {
            UserEntity user = getUserEntity(phone);
            //当前部门 所在城市ID
            String cityId = DepartmentEntity.getCityID(user.getDeptUrlPath());
            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", "zb".equalsIgnoreCase(city.getDescripition()) ? "nj" : city.getDescripition());

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

            listRequest.setSearchParams(searchParams);
            ProjectListResponse response = project.getProjectList(listRequest);
            JSONArray assignProjects = new JSONArray();
            for (ProjectEntity projectEntity : response.getObjectList()) {
                JSONObject project = new JSONObject();
                project.put("id", projectEntity.getId());
                project.put("projectName", projectEntity.getProjectName());
                assignProjects.add(project);
            }
            object.setList(assignProjects);
        } else {
            object.setList(new ArrayList<ProjectEntity>());
        }

        return object;
    }


    private House365RestObject<Boolean> doAssignCustomer(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        object.setEntity(Boolean.FALSE);
        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String userIds = getMapValueByKey("userIds", map, "");
        String customerIds = getMapValueByKey("customerIds", map, "");
        String assignFrom = getMapValueByKey("assignFrom", map, "");

        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(userIds) && !Strings.isNullOrEmpty(customerIds)) {
            //操作者
            UserEntity userEntity = getUserEntity(phone);
            String[] customerIdArray = customerIds.split(",");
            String[] userIdArray = userIds.split(",");

            try {
                customer.bindUser(customerIdArray, userIdArray, userEntity.getId(), false, "", assignFrom);
                object.setEntity(Boolean.TRUE);
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
        }

        return object;
    }

    /**
     * 获取400热线客户列表
     */
    private House365RestObject doGetHotLineCustomer(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<CustomerEntity> customerEntities = new ArrayList<>();
        String pageNo = getMapValueByKey("pageNo", map, "1");
        String pageSize = getMapValueByKey("pageSize", map, PAGENO);

        //置业顾问ID
        String managerFilter = getMapValueByKey("managerFilter", map, "0");
        //创建时间起始
        String createTimeStart = getMapValueByKey("startTime", map, "");
        //创建时间截止
        String createTimeEnd = getMapValueByKey("endTime", map, "");
        //客户状态
        String projectStatus = getMapValueByKey("customerStatus", map, "");

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

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        LOGGER.debug(
                "==doGetHotLineCustomer>>phone:{}==pageNo:{}==pageSize:{}==managerFilter:{}==createTimeStart:{}==" + "createTimeEnd:{}==projectStatus:{}==",
                phone, pageNo, pageSize, managerFilter, createTimeStart, createTimeEnd, projectStatus);

        if (StringUtils.isNotBlank(phone)) {
            UserEntity user = getUserEntity(phone);

            //只展示当前城市下的400客户
            DepartmentEntity department = departmentService.getById(user.getDeptId());
            DepartmentEntity city = departmentService.getById(Integer.valueOf(department.getCityID()));
            customerMap.put("EQ_cityCode", city.getDescripition());

            if (user.getId().toString().equals(managerFilter)) {
                managerFilter = "0";
            }

            if (StringUtils.isNotBlank(managerFilter)) {
                switch (managerFilter) {
                    case "-1":
                        List<Integer> userIds = userService.getUserIdOnPath(user.getId());
                        customerMap.put("EQ_userIds", Joiner.on(",").join(userIds));
                        break;
                    case "0"://当前用户的客户
                        customerMap.put("EQ_userIds", user.getId());
                        break;
                    default:
                        customerMap.put("EQ_userId", managerFilter);
                        break;
                }
            }

            if (!Strings.isNullOrEmpty(createTimeStart)) {
                customerMap.put("GTE_createTimeStart", createTimeStart + " 00:00:00");
            }
            if (!Strings.isNullOrEmpty(createTimeEnd)) {
                customerMap.put("LTE_createTimeEnd", createTimeEnd + " 23:59:59");
            }

            //客户状态 0：未约看（已跟踪） 98：未跟踪 99 已删除
            if (Strings.isNullOrEmpty(projectStatus)) {
                customerMap.put("NOTEQ_status", Constant.HotLineStatusEnum.DELETE.getMsg().intValue());
            } else {
                customerMap.put("EQ_status", projectStatus);
            }
            //来源为 400电话
            customerMap.put("EQ_createSource", Constant.CustomerSourceEnum.HOTLINE.getMsg());

            Page page = new Page();
            if (null != pageNo) {
                page.setCurrentPage(Integer.parseInt(pageNo));
            }
            if (null != pageSize) {
                page.setPageSize(Integer.parseInt(pageSize));
            }

            QueryParams<Map> searchParams = new QueryParams<>(customerMap);
            searchParams.setPaging(page);
            searchParams.setOrderColumn("create_time");
            searchParams.setOrderMode("desc");
            customerEntities = customerService.queryByPage(searchParams);
        }
        object.setList(customerEntities);
        return object;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject doGetMyCustomer(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<CustomerEntity> customerEntities = new ArrayList<>();
        String pageNo = getMapValueByKey("pageNo", map, "0");
        String pageSize = getMapValueByKey("pageSize", map, PAGENO);

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        //客户姓名或电话
        String customerKeyWord = getMapValueByKey("keyword", map, "");
        //楼盘名称
        String houseName = getMapValueByKey("houseName", map, "");
        //置业顾问
        String managerName = getMapValueByKey("managerName", map, "");
        //创建时间起始
        String createTimeStart = getMapValueByKey("createTimeStart", map, "");
        //创建时间截止
        String createTimeEnd = getMapValueByKey("createTimeEnd", map, "");
        //约看状态
        String recordedStatus = getMapValueByKey("recordedStatus", map, "");
        //客户状态
        String projectStatus = getMapValueByKey("projectStatus", map, "");
        //贷款状态
        String loanStatus = getMapValueByKey("loanStatus", map, "");
        //追踪状态
        String traceStatus = getMapValueByKey("traceStatus", map, "");

        LOGGER.debug(
                "==doGetHotLineCustomer>>phone:{}==customerKeyWord:{}==managerName:{}==createTimeStart:{}==createTimeEnd:{}==" + "recordedStatus:{}==projectStatus:{}==loanStatus:{}==traceStatus:{}==",
                phone, customerKeyWord, managerName, createTimeStart, createTimeEnd, recordedStatus, projectStatus,
                loanStatus, traceStatus);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);

            if (user != null) {
                Map<String, Object> customerMap = new HashMap<>();

                //自己和子部门数据
                customerMap.put("EQ_userId", user.getId());
                customerMap.put("EQ_cityId", DepartmentEntity.getCityID(user.getDeptUrlPath()));
                customerMap.put("EQ_recordedStatus", "1");

                if (!Strings.isNullOrEmpty(customerKeyWord)) {
                    customerMap.put("LIKE_likekeyword", customerKeyWord);
                }
                if (!Strings.isNullOrEmpty(managerName)) {
                    customerMap.put("LIKE_managerName", managerName);
                }
                if (!Strings.isNullOrEmpty(createTimeStart)) {
                    customerMap.put("GTE_createTimeStart", createTimeStart + " 00:00:00");
                }
                if (!Strings.isNullOrEmpty(createTimeEnd)) {
                    customerMap.put("LTE_createTimeEnd", createTimeEnd + " 23:59:59");
                }
                if (!Strings.isNullOrEmpty(recordedStatus)) {
                    customerMap.put("EQ_recordedStatus", recordedStatus);
                }
                if (!Strings.isNullOrEmpty(projectStatus)) {
                    customerMap.put("EQ_projectStatus", projectStatus);
                }
                if (!Strings.isNullOrEmpty(loanStatus)) {
                    customerMap.put("EQ_loanStatus", loanStatus);
                }
                if (!Strings.isNullOrEmpty(traceStatus)) {
                    customerMap.put("EQ_traceStatus", traceStatus);
                }

                //排除400客户状态未跟踪和删除
                customerMap.put("EQ_hotline", "0");
                Page page = new Page();
                if (null != pageNo) {
                    page.setCurrentPage(Integer.parseInt(pageNo));
                }
                if (null != pageSize) {
                    page.setPageSize(Integer.parseInt(pageSize));
                }

                QueryParams<Map> searchParams = new QueryParams<>(customerMap);
                searchParams.setPaging(page);
                customerEntities = customerService.queryByPage(searchParams);

            }

        }

        object.setList(customerEntities);
        return object;
    }

    private UserEntity getUserEntity(String phone) {
        UserEntity user = null;
        Map<String, Object> qm = new HashMap<>();
        qm.put("EQ_mobile", phone);
        QueryParams queryParams = new QueryParams(qm);
        List<UserEntity> userEntities = userService.queryAll(queryParams);
        if (userEntities != null && !userEntities.isEmpty()) {
            user = userEntities.get(0);
        }
        return user;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<CustomerEntity> doGetCustomerInOcean(Map<String, Object> map) throws Exception {
        House365RestObject restObject = new House365RestObject();
        String pageNo = getMapValueByKey(Constant.PAGE, map, "1");
        String pageSize = getMapValueByKey(Constant.PAGESIZE, map, "20");
        String createTimeStart = getMapValueByKey("createTimeStart", map, "");
        String createTimeEnd = getMapValueByKey("createTimeEnd", map, "");
        String buyIntention = getMapValueByKey("buyIntention", map, "");

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");

        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            Page page = new Page(Integer.parseInt(pageSize));
            if (null != pageNo) {
                page.setCurrentPage(Integer.parseInt(pageNo));
            }

            //共多少条数据，今日新增多少条
            //当前部门 所在城市ID
            String cityId = DepartmentEntity.getCityID(user.getDeptUrlPath());

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

            //汇总信息
            Map<String, Object> summary = seaSummary.getData().getEntity();
            restObject.setParaMap(summary);

            Map<String, Object> searchParams = new HashedMap();
            if (!Strings.isNullOrEmpty(createTimeStart)) {
                searchParams.put("GTE_oceanDateStart", createTimeStart + " 00:00:00");
            }
            if (!Strings.isNullOrEmpty(createTimeEnd)) {
                searchParams.put("LTE_oceanDateEnd", createTimeEnd + " 23:59:59");
            }

            if (!Strings.isNullOrEmpty(buyIntention)) {
                if ("99".equalsIgnoreCase(buyIntention)) {
                    searchParams.put("EQ_buyIntentionIsNull", "1");
                } else {
                    searchParams.put("EQ_buyIntention", buyIntention);
                }
            }

            searchParams.put("EQ_cityCode", cityCode);
            searchParams.put("EQ_isDelete", "0");
            searchParams.put("ISNULL_managerId", "");

            CustomerListRequest listRequest = new CustomerListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            CustomerListResponse response = customer.getCustomerList(listRequest);
            if (response != null && response.getObjectList() != null && !response.getObjectList().isEmpty()) {
                List<CustomerEntity> list = response.getObjectList();
                for (CustomerEntity customerEntity : list) {
                    if (null != customerEntity.getCreateTime()) {
                        String cutPhone = customerEntity.getPhone();
                        cutPhone = cutPhone.substring(0, 3) + "****" + cutPhone.substring(7, cutPhone.length());

                        customerEntity.setPhone(cutPhone);

                        customerEntity.setCreateTimeStr(DateTimeUtils.parseDate(customerEntity.getCreateTime(),
                                DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_FULL));
                        customerEntity.setCreateDateStr(
                                DateTimeUtils.parseDate(customerEntity.getCreateTime(), "MM-dd HH:mm:ss"));
                    }
                }

                restObject.setList(response.getObjectList());
                restObject.setTotal(String.valueOf(response.getPaging().getRecords()));
            }
        }

        return restObject;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<CustomerEntity> doGetCustomerOceanSummary(Map<String, Object> map) throws Exception {
        House365RestObject restObject = new House365RestObject();
        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");

        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            //共多少条数据，7日数据，今日新增多少条
            //当前部门 所在城市ID
            String cityId = DepartmentEntity.getCityID(user.getDeptUrlPath());
            DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
            String cityCode = departmentResponse.getEntity().getDescripition();
            House365RestResponse<Map<String, Object>> seaSummary = customer.getSeaSummary(cityCode);

            //汇总信息
            Map<String, Object> summary = seaSummary.getData().getEntity();
            restObject.setParaMap(summary);
        }

        return restObject;
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }


    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {

    }

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        return null;
    }

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param defaultValue 默认值
     * @return value
     */
    private String getMapValueByKey(String key, Map<String, Object> map, String defaultValue) {
        String value = "";
        if (map.containsKey(key) && map.get(key) != null && !Strings.isNullOrEmpty(((String[]) map.get(key))[0])) {
            value = ((String[]) map.get(key))[0];
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @author hqc
     */
    protected void checkInterfaceParameter(
            Map<String, Object> map, String[] checkParams
    ) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : checkParams) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

}
