package com.house365.ws.interfaces.rest;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.house365.beans.common.HGSConstant;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.beans.vo.CustomerProjectStatusDetailVo;
import com.house365.beans.vo.CustomerProjectStatusProgressVo;
import com.house365.commons.system.HttpClientUtil;
import com.house365.commons.system.SmsUtils;
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.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.beans.request.CustomerRequest;
import com.house365.ws.beans.request.CustomerStatusLogListRequest;
import com.house365.ws.beans.request.CustomerStatusLogRequest;
import com.house365.ws.beans.request.UserListRequest;
import com.house365.ws.beans.response.CustomerProjectResponse;
import com.house365.ws.beans.response.CustomerResponse;
import com.house365.ws.beans.response.CustomerStatusLogListResponse;
import com.house365.ws.beans.response.UserListResponse;
import com.house365.ws.dao.interfaces.ICustomerDao;
import com.house365.ws.dao.interfaces.IProjectDao;
import com.house365.ws.dao.mapper.*;
import com.house365.ws.interfaces.server.*;
import com.house365.ws.service.interfaces.*;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.system.ReturnResult;
import com.house365.ws.util.Constant;
import com.house365.ws.util.MergeCustomerUtil;
import com.house365.ws.util.OperateLogUtils;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.house365.beans.common.MessageTypeEnum.NEWRECORDCUSTOMER;
import static com.house365.ws.interfaces.impl.CustomerImpl.MD5;

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

    private static final Logger LOGGER = LoggerFactory.getLogger("sysLog");
    private final String CRM_URL_PREFIX = "http://218.94.115.131:97";

    @Autowired
    private IUserService<UserEntity> userService;

    @Autowired
    private IDepartmentService<DepartmentEntity> departmentService;

    @Autowired
    private IProjectUserService<ProjectUserEntity> projectUserService;

    @Autowired
    private IProjectService<ProjectEntity> projectService;

    @Autowired
    private ICustomerProjectService<CustomerProjectEntity> customerProjectService;

    @Autowired
    private ICustomerService<CustomerEntity> customerService;

    @Autowired
    private ICustomer customer;

    @Autowired
    private ICustomerStatusLogService<CustomerStatusLogEntity> statusLogService;

    @Autowired
    private ICustomerCallbackLogService<CustomerCallbackLogEntity> callbackLogService;
    @Autowired
    private IAttachmentService<BaseAttachment> attachmentService;

    @Autowired
    private ICustomerProject customerProject;
    @Autowired
    private IUser iuser;
    @Autowired
    private IEvaluateUserCustomerLogService evaluateUserCustomerLogService;

    @Autowired
    private ICustomerCallbackLogService<CustomerCallbackLogEntity> customerCallbackLogService;

    @Autowired
    private ICustomerDao customerDao;
    @Autowired
    private IProjectDao projectDao;

    @Autowired
    private IMarketCustomer marketCustomer;
    @Autowired
    private ICustomerStatusLog customerStatusLog;
    @Autowired
    private IUser user;
    @Autowired
    private CustomerLogMapper logMapper;
    @Autowired
    private CustomerMergeMapper mergeMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerCallbackMapper callbackMapper;
    @Autowired
    private MergeCustomerUtil mergeCustomerUtil;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private CustomerProjectMapper customerProjectMapper;
    @Autowired
    private OperateLogUtils logUtils;

    /**
     * 获取我的项目列表
     *
     * @throws ServiceRunException
     */
    @Override
    public Object getMyProjects(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 data = doGetMyProject(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("===getMyProjects==result===:{}", result);
        return result;
    }

    /**
     * 获取项目详情
     *
     * @throws ServiceRunException
     */
    @Override
    public Object getProjectDetail(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<ProjectEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<ProjectEntity> data = doGetProjectDetail(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("===getProjectDetail==result===:{}", result);
        return result;
    }

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

        // 业务层统一处理
        try {
            House365RestObject<ProjectEntity> data = doGetDynamicList(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("===getProjectDetail==result===:{}", result);
        return result;
    }

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

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetCustomerProjects(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("===getProjectCustomers==result===:{}", result);
        return result;
    }

    /**
     * 获取项目下客户列表
     *
     * @throws ServiceRunException
     */
    @Override
    public Object getCustomers(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetCustomers(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("===getCustomers==result===:{}", result);
        return result;
    }

    /**
     * 获取客户购房意向
     *
     * @throws ServiceRunException
     */
    @Override
    public Object getCustomerProject(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetCustomerProject(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("===getCustomerProject==result===:{}", result);
        return result;
    }

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

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doGetCustomerDetail(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("===getCustomerDetail==result===:{}", result);
        return result;
    }

    /**
     * 获取客户状态变更记录
     *
     * @throws ServiceRunException
     */
    @Override
    public Object getCustomerStatusChangeLogs(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerStatusLogEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerStatusLogEntity> data = doGetCustomerStatusChangeLogs(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("===getCustomerStatusChangeLogs==result===:{}", result);
        return result;
    }

    /**
     * 约看客户项目信息
     *
     * @throws ServiceRunException
     */
    @Override
    public Object reportCustomer(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerStatusLogEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerStatusLogEntity> data = doReportCustomer(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("===reportCustomer==result===:{}", result);
        return result;
    }

    /**
     * 修改客户备注信息
     *
     * @throws ServiceRunException
     */
    @Override
    public Object modifyRemark(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerStatusLogEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerStatusLogEntity> data = doModifyRemark(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("===modifyRemark==result===:{}", result);
        return result;
    }

    /**
     * 获取回访记录列表
     *
     * @throws ServiceRunException
     */
    @Override
    public Object getVisitCallList(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerStatusLogEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerStatusLogEntity> data = doGetVisitCallList(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("===getVisitCallList==result===:{}", result);
        return result;
    }

    /**
     * 获取回访记录
     *
     * @throws ServiceRunException
     */
    @Override
    public Object getVisitCallLog(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerStatusLogEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerStatusLogEntity> data = doGetVisitCallLog(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("===getVisitCallLog==result===:{}", result);
        return result;
    }

    /**
     * 添加回访记录
     *
     * @throws ServiceRunException
     */
    @Override
    public Object addVisitCallContent(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerStatusLogEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerStatusLogEntity> data = doAddVisitCallContent(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("===addVisitCallContent==result===:{}", result);
        return result;
    }

    /**
     * 待回访添加回访记录
     *
     * @throws ServiceRunException
     */
    @Override
    public Object waitAddVisitCallContent(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerStatusLogEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerStatusLogEntity> data = doWaitAddVisitCallContent(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("===addVisitCallContent==result===:{}", result);
        return result;
    }

    /**
     * 添加客户状态变更记录
     *
     * @throws ServiceRunException
     */
    @Override
    public Object addCustomerStatusLog(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerStatusLogEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerStatusLogEntity> data = doAddCustomerStatusLog(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("===addCustomerStatusLog==result===:{}", result);
        return result;
    }

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

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doModifyCustomerProject(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("===modifyCustomerProject==result===:{}", result);
        return result;
    }

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

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doChangeRecordedStatus(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("===modifyCustomerProject==result===:{}", result);
        return result;
    }

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

        // 业务层统一处理
        try {
            House365RestObject object = new House365RestObject();

            String customerId = getMapValueByKey(Constant.CUSTOMER_ID, map, "");
            LOGGER.debug("==getCRMUrl>>customerId:{}==", customerId);
            System.out.println("____________________" + customerId);
            if (!Strings.isNullOrEmpty(customerId)) {
                String url = "";
//                CustomerEntity ce = customerService.getById(Integer.valueOf(customerId));
                CustomerEntity ce = mergeMapper.queryById(Integer.valueOf(customerId));
                System.out.println("____________________2" + ce);
                if (ce != null) {
                    Date date = new Date();

                    String crmUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("CRM.WECHAT.CUSTOMER.INFO.URL");
                    List<NameValuePair> pairs = new ArrayList<>();
                    crmUrl += "&signature=" + MD5(
                            "" + (date.getTime() / 1000) + "hgs") + "&timestamp=" + (date.getTime() / 1000);
                    crmUrl += "&city=" + ce.getCityCode() + "&memphone=" + ce.getPhone();
                    System.out.println("____________________3" + crmUrl);
                    try {
                        URLEncoder.encode(crmUrl, "utf8");
                        String res = HttpClientUtil.doPostWithCharset(crmUrl, pairs, "utf8", "utf8");
                        System.out.println("____________________4" + res);
                        net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
                        if (StringUtils.isNotBlank(res)) {
                            jsonObject = net.sf.json.JSONObject.fromObject(res);
                            if (jsonObject.get("result") != null && "1".equalsIgnoreCase(
                                    String.valueOf(jsonObject.get("result")))) {
                                url = MemoryPropertyPlaceholderConfigurer.getContextProperty("CRM.TOUCH.HOST") + jsonObject.get("data");
                            }
                        }

                        LOGGER.info("getCRMCustomerURL :{},url:{}", res, url);
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
                object.setEntity(url);
            }

            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("===modifyCustomerProject==result===:{}", result);
        return result;
    }

    /**
     * 保存带看评价信息
     */
    @Override
    public Object createCustomerEvaluate(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();

        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doCreateCustomerEvaluate(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("===createCustomerEvaluate==result===:{}", result);
        return result;
    }

    /**
     * 保存带看评价信息
     */
    private House365RestObject doCreateCustomerEvaluate(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String projectId = getMapValueByKey(Constant.PROJECT_ID, map, "");
        String projectName = getMapValueByKey("projectName", map, "");
        String customerName = getMapValueByKey(Constant.CUSTOMER_NAME, map, "");
        LOGGER.debug("==doCreateCustomerEvaluate>>phone:{}==projectId:{}==projectName:{}==customerName:{}==",
                phone, projectId, projectName, customerName);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(projectId)) {
            UserEntity user = getUserEntity(phone);
            EvaluateUserCustomerLogEntity evaluate = new EvaluateUserCustomerLogEntity();
            evaluate.setCustomerName(customerName);
            evaluate.setProjectId(Integer.valueOf(projectId));
            evaluate.setProjectName(projectName);
            evaluate.setUserId(user.getId());
            evaluate.setUserName(user.getRealName());
            evaluate.setIsEvaluated(0);
            evaluate.setCreateTime(new Date());
            evaluateUserCustomerLogService.save(evaluate);
        }

        return object;
    }

    /**
     * 获取客户回访记录
     */
    private House365RestObject doChangeRecordedStatus(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerProjectId = getMapValueByKey(Constant.CUSTOMER_PROJECT_ID, map, "");
        LOGGER.debug("==doGetVisitCallLog>>phone:{}==customerProjectId:{}==", phone, customerProjectId);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(customerProjectId)) {
            UserEntity user = getUserEntity(phone);
            CustomerProjectEntity customerProjectEntity = customerProjectService.getById(
                    Integer.valueOf(customerProjectId));

            customerProjectEntity.setRecordedStatus(1);
            customerProjectEntity.setRecordedTime(new Date());
            customerProjectEntity.setUpdater(user.getName());
            customerProjectEntity.setUpdateTime(new Date());
            customerProjectService.update(customerProjectEntity);
        }

        return object;
    }

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

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerProjectId = getMapValueByKey(Constant.CUSTOMER_PROJECT_ID, map, "");
        String key = getMapValueByKey("key", map, "");
        String value = getMapValueByKey("value", map, "");
        LOGGER.debug("==doModifyCustomerProject>>phone:{}==customerProjectId:{}==key:{}==value:{}==", phone,
                customerProjectId, key, value);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            CustomerProjectEntity customerProjectEntity = customerProjectService.getById(
                    Integer.valueOf(customerProjectId));

            if (value.equals("null")) {
                value = "";
            }
            switch (key) {
                case "requireArea":
                    customerProjectEntity.setRequireArea(value);
                    break;
                case "requireHouse":
                    customerProjectEntity.setRequireHouse(value);
                    break;
                case "requireHouseType":
                    customerProjectEntity.setRequireHouseType(value);
                    break;
                case "requirePrice":
                    customerProjectEntity.setRequirePrice(value);
                    break;
                case "consultantName":
                    customerProjectEntity.setConsultantName(value);
                    break;
                case "consultantPhone":
                    customerProjectEntity.setConsultantPhone(value);
                    break;
                case "recordedStatus":
                    customerProjectEntity.setRecordedStatus(Integer.valueOf(value));
                    break;
                case "loanStatus":
                    customerProjectEntity.setLoanStatus(value);
                    break;
                case "remark":
                    customerProjectEntity.setRemark(value);
                    break;
                default:
                    break;
            }
            customerProjectEntity.setUpdater(user.getName());
            customerProjectEntity.setUpdateTime(new Date());
            customerProjectService.update(customerProjectEntity);
        }
        return object;
    }

    /**
     * 添加客户回访记录
     */
    private House365RestObject doAddCustomerStatusLog(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<CustomerStatusLogEntity> projectEntities = new ArrayList<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerProjectId = getMapValueByKey(Constant.CUSTOMER_PROJECT_ID, map, "");
        String occurTime = getMapValueByKey("occurTime", map, "");
        LOGGER.debug("******接口发生时间********" + occurTime);
        occurTime = occurTime.replaceAll("T", " ");
        LOGGER.debug("******接口发生时间2********" + occurTime);
        Integer customerStatus = Integer.valueOf(getMapValueByKey("customerStatus", map, "0"));
        String callContent = getMapValueByKey("callContent", map, "");
        LOGGER.debug("==doAddCustomerStatusLog>>phone:{}==projectId:{}==customerStatus:{}==callContent:{}==", phone,
                customerProjectId, customerStatus, callContent, occurTime);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(customerProjectId) && customerStatus != null) {
            UserEntity user = getUserEntity(phone);
            CustomerProjectEntity entity = customerProjectService.getById(Integer.valueOf(customerProjectId));
            Integer oldStatus = entity.getStatus();
            if (oldStatus != null) {

                List<BaseAttachment> attachments = attachmentService.queryByResourceIdAndResouceType(
                        user.getId().toString(), "wechat");

                Map<String, Object> searchParams = new HashMap<>(10);
                searchParams.put("EQ_resourceId", customerProjectId);
                searchParams.put("EQ_resourceType", "hgs_customer_project");
                QueryParams queryParams = new QueryParams(searchParams);
                queryParams.setOrderColumn("bizType");
                queryParams.setOrderMode("desc");
                int nextBizType = 0;

                List<BaseAttachment> oldAttachments = attachmentService.queryByPage(queryParams);
                if (!oldAttachments.isEmpty()) {
                    BaseAttachment attachment = oldAttachments.get(0);
                    nextBizType = oldAttachments.size();
                    nextBizType = attachment.getBizType() + 1;
                }
                for (BaseAttachment attachment : attachments) {
                    attachment.setResourceId(entity.getId());
                    attachment.setBizType(nextBizType);
                    nextBizType++;
                    attachment.setResourceType("hgs_customer_project");
                    attachmentService.update(attachment);
                }

                CustomerProjectResponse response = customerProject.changeStatus(entity.getId(), user.getName(),
                        customerStatus, callContent, occurTime);
                // 判断变更客户项目状态是否成功
                if (ReturnResult.FAIL.getResultCode().equals(response.getResultCode())) {
                    throw new Exception(response.getResultMessage());
                }
            }
        }

        object.setList(projectEntities);
        return object;
    }

    /**
     * 待回访客户添加回访记录
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    protected House365RestObject doWaitAddVisitCallContent(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<ProjectEntity> projectEntities = new ArrayList<>();
        Date newdate = new Date();
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerId = getMapValueByKey(Constant.CUSTOMER_ID, map, "");
        String buyIntention = getMapValueByKey("buyIntention", map, "");
        String callContent = getMapValueByKey("callContent", map, "");
        LOGGER.debug("==doAddVisitCallContent>>phone:{}==callContent:{}==", phone, callContent);
        UserEntity userEntity = getUserEntity(phone);

        CustomerCallbackLogEntity callbackLogEntity = new CustomerCallbackLogEntity();
        callbackLogEntity.setCustomerId(Integer.valueOf(customerId));
        callbackLogEntity.setManagerId(userEntity.getId());
        callbackLogEntity.setManagerName(userEntity.getRealName());
        callbackLogEntity.setCreateTime(newdate);
        callbackLogEntity.setContent("");
        customerCallbackLogService.save(callbackLogEntity);
        try {
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            nameValuePairList.add(new BasicNameValuePair("Call", userEntity.getCornet()));
            nameValuePairList.add(new BasicNameValuePair("Dialed", phone));
            nameValuePairList.add(new BasicNameValuePair("pid", callbackLogEntity.getId().toString()));
            nameValuePairList.add(new BasicNameValuePair("Tag", "1"));

            String result = HttpClientUtil.doGet(CRM_URL_PREFIX + "/CallCenterUnicom/SinglePhone.json", nameValuePairList,
                    10000, "utf-8");

            LOGGER.info("call single phone call:[{}] dialed [{}] id [{}],result:[{}]", userEntity.getCornet(), phone,
                    callbackLogEntity.getId(), result);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        //将客户--》全部列表
        CustomerEntity customerEntity = (CustomerEntity) customerDao.getById(callbackLogEntity.getCustomerId());

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

        //待回访进私客合并客户
        CustomerEntity oldEntity = customer.getCustomerMerge(customerEntity.getPhone(), customerEntity.getManagerId());
        if (oldEntity == null) {
            handleCustomerMerge(customerEntity);
            customer.saveCustomerMerge(customerEntity);
        } else {
            if (Constant.CustomerSourceEnum.HOTLINE.getMsg().equals(oldEntity.getCreateSource())) {
                if (oldEntity.getStatus().intValue() == Constant.HotLineStatusEnum.INIT.getMsg().intValue()) {
                    oldEntity.setStatus(Constant.HotLineStatusEnum.NORECORD.getMsg());
                }
            }
            mergeCustomerUtil.checkMergeCustomer(customerEntity, oldEntity, userEntity.getId(), userEntity.getRealName());
            // 意向等级、跟踪状态更新
            //重置客户绑定置业顾问时间
            oldEntity.setBindTime(newdate);
            oldEntity.setUpdateTime(newdate);
            oldEntity.setUpdater(String.valueOf(userEntity.getId()));
            oldEntity.setIsActive(0);
            oldEntity.setIsHandover(0);
            handleCustomerMerge(oldEntity, newdate);
            customer.updateCustomerMerge(oldEntity);
        }

        customer.crmAddCallBack(callbackLogEntity.getCustomerId());
        marketCustomer.addCallbackCount(customerEntity.getId());

        //无效客户回公海
        if (HGSConstant.BUYINTENTIONENUM.E.getCode().equalsIgnoreCase(buyIntention)) {
            //删除合并客户
            List<CustomerEntity> customerList = customer.getDetailCustomers(customerEntity.getPhone(), customerEntity.getManagerId());
            Map<String, Object> idMap = new HashMap<String, Object>();
            List idList = new ArrayList();
            if (customerList != null) {
                for (CustomerEntity ce : customerList) {
                    idList.add(ce.getId());
                }
            }
            idMap.put("ids", idList);
            customer.deleteCustomerMergeById(idMap);
            //合并前客户回公海
            for (CustomerEntity customerentity : customerList) {
                customer.removeCustomer(customerentity.getId(), userEntity.getId());
            }
        }
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        nameValuePairList.add(new BasicNameValuePair("Call", userEntity.getCornet()));
        String result = HttpClientUtil.doGet(CRM_URL_PREFIX + "/CallCenterUnicom/HandUp.json", nameValuePairList, 10000,
                "utf-8");
        LOGGER.info("handUp phone call:[{}] result:[{}]", userEntity.getCornet(), result);

        object.setList(projectEntities);
        return object;
    }

    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;
    }

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

        // 业务层统一处理
        try {
            House365RestObject<BaseAttachment> data = doDelDynamic(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;
    }

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

        String entityStr = map.get("entity").toString();
        JSONObject entity = JSONObject.fromObject(entityStr);
        ProjectDynamicEntity projectdynamicentity = new ProjectDynamicEntity();
        projectdynamicentity.setDynamicId(Integer.valueOf(entity.getString("dynamicId")));
        //删project_dynamic
        projectDao.delDynamic(Integer.valueOf(entity.getString("dynamicId")));
        //删base_attachment
        customerDao.delDynamic(Integer.valueOf(entity.getString("dynamicId")));
        return restObject;
    }


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

        // 业务层统一处理
        try {
            House365RestObject<BaseAttachment> data = doSaveDynamic(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;
    }


    private House365RestObject<BaseAttachment> doSaveDynamic(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);
        ProjectDynamicEntity projectdynamicentity = new ProjectDynamicEntity();
        if (entity.containsKey("dynamicContent")) {
            projectdynamicentity.setDynamicContent(entity.getString("dynamicContent"));
        }
        projectdynamicentity.setProjectId(Integer.valueOf(entity.getString("projectId")));
        projectdynamicentity.setProjectName(entity.getString("projectName"));
        projectdynamicentity.setCreateUserid(Integer.valueOf(entity.getString("createUserid")));
        projectdynamicentity.setCreateUsername(entity.getString("createUsername"));
        projectdynamicentity.setDynamicId(Integer.valueOf(entity.getString("dynamicId")));
        projectdynamicentity.setCreateTime(new Date());
        projectDao.saveDynamic(projectdynamicentity);
        return restObject;
    }


    /**
     * 添加客户回访记录
     */
    @Transactional(rollbackFor = Exception.class)
    private House365RestObject doAddVisitCallContent(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<ProjectEntity> projectEntities = new ArrayList<>();

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

            if (user != null) {
                CustomerCallbackLogEntity callbackLogEntity = new CustomerCallbackLogEntity();
                callbackLogEntity.setCustomerId(Integer.valueOf(customerId));
                callbackLogEntity.setContent(callContent);
                callbackLogEntity.setManagerId(user.getId());
                callbackLogEntity.setManagerName(user.getRealName());
                callbackLogEntity.setCreateTime(newdate);
                callbackLogService.save(callbackLogEntity);

                CustomerResponse customerResponse = customer.getCustomerById(Integer.valueOf(customerId));
                CustomerEntity customerEntity = customerResponse.getEntity();
                customerEntity.setBuyIntention("99".equalsIgnoreCase(buyIntention) ? "" : buyIntention);
                //更新回访记录的时候，同时更新会员备注
                customerEntity.setRemark(callContent);
//                customerEntity.setLastCallTime(newdate);
                //会员状态 已跟踪 0 跟踪状态为98时，才可以转为已跟踪
                if (Constant.CustomerSourceEnum.HOTLINE.getMsg().equals(customerEntity.getCreateSource())) {
                    if (customerEntity.getStatus().intValue() == Constant.HotLineStatusEnum.INIT.getMsg().intValue()) {
                        customerEntity.setStatus(Constant.HotLineStatusEnum.NORECORD.getMsg());
                    }
                }

                CustomerRequest customerRequest = new CustomerRequest();
                customerRequest.setEntity(customerEntity);
                customer.updateCustomerNew(customerRequest, 0, user.getRealName());
                customer.crmAddCallBack(Integer.valueOf(customerId));
                if (HGSConstant.BUYINTENTIONENUM.E.getCode().equalsIgnoreCase(buyIntention)) {
                    //合并后客户删除
                    List<CustomerEntity> customerList = customer.getDetailCustomers(customerEntity.getPhone(), customerEntity.getManagerId());
                    Map<String, Object> idMap = new HashMap<>(5);
                    List<Integer> idList = new ArrayList<>();
                    if (customerList != null) {
                        for (CustomerEntity ce : customerList) {
                            idList.add(ce.getId());
                        }
                    }
                    idMap.put("ids", idList);
                    customer.deleteCustomerMergeById(idMap);
                    //合并前客户回公海
                    if (CollectionUtils.isNotEmpty(customerList)) {
                        for (CustomerEntity entity : customerList) {
                            customer.removeCustomer(entity.getId(), user.getId());
                        }
                    }
                } else {//跟踪不回公海
                    //合并之后的表:更新or新增
                    CustomerEntity oldEntity = customer.getCustomerMerge(customerEntity.getPhone(), customerEntity.getManagerId());
                    if (oldEntity == null) {
                        handleCustomerMerge(customerEntity, newdate);
                        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);
                        oldEntity.setLastCallTime(newdate);//添加回访：最近回访时间为当前系统时间
//                        handleCustomerMerge(oldEntity, newdate);
                        customer.updateCustomerMerge(oldEntity);
                    }
                }
            }
        }
        object.setList(projectEntities);
        return object;
    }

    /**
     * 移动端400跟踪合并客户最近回访时间-当前系统时间
     *
     * @param currentCustomer
     * @param
     * @return
     */
    public CustomerEntity handleCustomerMerge(CustomerEntity currentCustomer, Date newdate) {
        //先去查询该客户的所有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);
        currentCustomer.setLastCallTime(newdate);
        return currentCustomer;
    }


    /**
     * 获取客户回访记录
     */
    private House365RestObject doGetVisitCallLog(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();

        String logId = getMapValueByKey("logId", map, "");
        LOGGER.debug("==doGetVisitCallLog>>logId:{}==", logId);
        if (!Strings.isNullOrEmpty(logId)) {
            CustomerCallbackLogEntity callbackLog = callbackLogService.getById(Integer.valueOf(logId));

            object.setEntity(callbackLog);
        }

        return object;
    }

    /**
     * 获取当前时间返回当前时间处于当前年的第几周(周一为一周的第一天)
     *
     * @return int
     */
    private Integer weekChina(Date date) {
        Calendar c = Calendar.getInstance();
        //获取当前时间
        c.setTime(date);
        //获取是本年的第几周
        int week = c.get(Calendar.WEEK_OF_YEAR);
        //获致是本周的第几天地, 1代表星期天...7代表星期六
        int day = c.get(Calendar.DAY_OF_WEEK);
        return day == 1 ? (week - 1) : week;
    }

    /**
     * 获取客户回访记录列表
     */
    private House365RestObject doGetVisitCallList(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        LinkedHashMap<String, Map<String, Object>> result = new LinkedHashMap<>();

        String customerId = getMapValueByKey(Constant.CUSTOMER_ID, map, "");
        LOGGER.debug("==doGetVisitCallList>>customerId:{}==", customerId);
        if (!Strings.isNullOrEmpty(customerId)) {

            Map<String, Object> searchParams = new HashMap<>();
            searchParams.put("EQ_customerId", customerId);
            QueryParams<CustomerCallbackLogEntity> queryParams = new QueryParams<>(searchParams);
            queryParams.setOrderColumn("create_time");
            queryParams.setOrderMode("desc");
            List<CustomerCallbackLogEntity> callbackLogs = callbackLogService.queryAll(queryParams);
            object.setList(callbackLogs);

            String todayWeekCount = weekChina(new Date()).toString();
            Map<String, Object> todayWeek = new HashMap<>();
            todayWeek.put("time", "最近一周");
            todayWeek.put("logs", new ArrayList<>());
            result.put("a" + todayWeekCount, todayWeek);
            for (CustomerCallbackLogEntity callbackLog : callbackLogs) {
                String weekCount = weekChina(callbackLog.getCreateTime()).toString();
                Map<String, Object> week = result.get("a" + weekCount);
                List<CustomerCallbackLogEntity> logs = new ArrayList<>();
                if (week != null) {
                    logs = (List<CustomerCallbackLogEntity>) week.get("logs");
                    logs.add(callbackLog);
                } else {
                    week = new HashMap<>();
                    logs.add(callbackLog);
                    StringBuilder time = new StringBuilder();
                    if (todayWeekCount.equals(weekCount)) {
                        week.put("time", "最近一周");
                    } else {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(callbackLog.getCreateTime());
                        calendar.add(Calendar.DATE, getMondayPlus(calendar) + 5);
                        calendar.set(Calendar.HOUR_OF_DAY, 23);
                        calendar.set(Calendar.SECOND, 59);
                        calendar.set(Calendar.MINUTE, 59);
                        calendar.set(Calendar.MILLISECOND, 999);
                        String timeEnd = DateUtils.formatDate(calendar.getTime(), "MM月dd日");
                        calendar.add(Calendar.DATE, getMondayPlus(calendar));
                        calendar.set(Calendar.HOUR_OF_DAY, 0);
                        calendar.set(Calendar.SECOND, 0);
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.MILLISECOND, 1);
                        searchParams.put("GTE_createTimeStart", calendar.getTime());
                        String timeStart = DateUtils.formatDate(calendar.getTime(), "MM月dd日");
                        week.put("time", time.append(timeStart).append(" - ").append(timeEnd).toString());
                    }
                }
                week.put("logs", logs);

                //防止JSONObject 按键值重新排序
                result.put("a" + weekCount, week);
            }
        }

        object.setEntity(result);
        return object;
    }

    /**
     * 修改客户备注信息
     */
    private House365RestObject doModifyRemark(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<ProjectEntity> projectEntities = new ArrayList<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerProjectId = getMapValueByKey(Constant.CUSTOMER_PROJECT_ID, map, "");
        String remark = getMapValueByKey("remark", map, "");
        LOGGER.debug("==doModifyRemark>>phone:{}==customerProjectId:{}==remark:{}==", phone, customerProjectId, remark);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(customerProjectId) && !Strings.isNullOrEmpty(
                remark)) {
            UserEntity user = getUserEntity(phone);
            CustomerProjectEntity cp = customerProjectService.getById(Integer.valueOf(customerProjectId));
            cp.setRemark(remark);
            cp.setUpdater(user.getName());
            cp.setUpdateTime(new Date());
            customerProjectService.update(cp);
        }

        object.setList(projectEntities);
        return object;
    }

    /**
     * 约看客户项目信息
     */
    private House365RestObject doReportCustomer(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();

        String entityStr = map.get("entity").toString();
        map.remove("entity");
        JSONObject entity = JSONObject.fromObject(entityStr);
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerId = entity.getString(Constant.CUSTOMER_ID);
        String projectId = entity.getString(Constant.PROJECT_ID);
        LOGGER.debug("==doReportCustomer>>phone:{}==customerId:{}==projectId:{}==", phone, customerId, projectId);
        if (!Strings.isNullOrEmpty(phone) && !Strings.isNullOrEmpty(customerId) && !Strings.isNullOrEmpty(projectId)) {
            UserEntity user = getUserEntity(phone);
            CustomerEntity c = customerService.getById(Integer.valueOf(customerId));
            CustomerProjectEntity cp = customerProjectService.getById(Integer.valueOf(projectId));

            c.setName(entity.getString("customerName"));
            c.setUpdater(user.getName());
            c.setUpdateTime(new Date());

            cp.setConsultantName(entity.getString("consultantName"));
            cp.setConsultantPhone(entity.getString("consultantPhone"));
            cp.setRecordedStatus(entity.getInt("recordedStatus") == 99 ? null : entity.getInt("recordedStatus"));
            cp.setLoanStatus("99".equals(entity.getString("loanStatus")) ? null : entity.getString("loanStatus"));

            cp.setRequireArea(entity.getString("requireArea"));
            cp.setRequireHouse(entity.getString("requireHouse"));
            cp.setRequireHouseType(entity.getString("requireHouseType"));
            cp.setRequirePrice(entity.getString("requirePrice"));
            cp.setUpdater(user.getName());
            cp.setUpdateTime(new Date());

            customerService.update(c);
            customerProjectService.update(cp);
        }
        return object;
    }

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

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        LOGGER.debug("==doGetMyProject>>phone:{}==", phone);
        if (!Strings.isNullOrEmpty(phone)) {
            UserEntity user = getUserEntity(phone);
            DepartmentEntity department = departmentService.getById(user.getDeptId());
            DepartmentEntity city = departmentService.getById(Integer.valueOf(department.getCityID()));

            projectEntities = projectUserService.getProjectByUserId(user.getId(), city.getDescripition());
        }

        object.setList(projectEntities);
        return object;
    }

    /**
     * 获取项目动态信息
     *
     * @param map
     * @return
     * @throws Exception
     */
    private House365RestObject doGetDynamicList(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<ProjectEntity> projectDynamicList = new ArrayList<>();
        List<BaseAttachment> attachments = new ArrayList<>();
        Integer pageSize = Integer.valueOf(getMapValueByKey("pageSize", map, "20"));
        Integer pageNo = Integer.valueOf(getMapValueByKey("pageNo", map, "0"));
        String projectId = getMapValueByKey(Constant.PROJECT_ID, map, "");
        ProjectDynamicEntity pde = new ProjectDynamicEntity();
        pde.setProjectId(Integer.valueOf(projectId));
        pde.setPageNo(pageNo);
        pde.setPageSize(pageSize);
        LOGGER.debug("==doGetProjectDetail>>projectId:{}==", projectId);
        if (!Strings.isNullOrEmpty(projectId)) {
            projectDynamicList = projectService.getDynamicById(pde);
            attachments = attachmentService.queryByResouceType("wechatdynamic");
            for (int j = 0; j < projectDynamicList.size(); j++) {
                List picListByDynamic = new ArrayList();
                String dynamicId = String.valueOf(projectDynamicList.get(j).getDynamicId());
                for (int i = 0; i < attachments.size(); i++) {
                    BaseAttachment ba = attachments.get(i);
                    if (dynamicId.equals(String.valueOf(ba.getResourceId()))) {
                        picListByDynamic.add(ba.getRemotePath());
                    }
                }
                projectDynamicList.get(j).setPicList(picListByDynamic);
            }

        }
        object.setList(projectDynamicList);
        return object;
    }

    /**
     * 获取项目详情
     */
    private House365RestObject doGetProjectDetail(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        ProjectEntity projectEntity = new ProjectEntity();
        List<BaseAttachment> attachments = new ArrayList<>();

        String projectId = getMapValueByKey(Constant.PROJECT_ID, map, "");
        LOGGER.debug("==doGetProjectDetail>>projectId:{}==", projectId);
        if (!Strings.isNullOrEmpty(projectId)) {
            projectEntity = projectService.getById(Integer.valueOf(projectId));
            attachments = attachmentService.queryByResourceIdAndResouceType(projectId, "hgs");
        }

        object.setEntity(projectEntity);
        object.setList(attachments);
        return object;
    }


    /**
     * 获取客户约看项目列表
     */
    private House365RestObject doGetCustomerProjects(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        List<CustomerProjectEntity> customerProjectEntities = new ArrayList<>();

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

            Map<String, Object> cpMap = new HashMap<>(10);
            cpMap.put("EQ_customerId", customerId);
            QueryParams<CustomerProjectEntity> queryParams = new QueryParams<>(cpMap);
            queryParams.setOrderColumn("update_time");
            queryParams.setOrderMode("desc");
            customerProjectEntities = customerProjectService.queryAll(queryParams);
            for (CustomerProjectEntity cpe : customerProjectEntities) {
                if (user.getPreLoginTime() != null && cpe.getLastChangeStatusTime() != null) {
                    if (user.getPreLoginTime().before(cpe.getLastChangeStatusTime())) {
                        cpe.setRemark("New!");
                    } else {
                        cpe.setRemark("");
                    }
                } else {
                    cpe.setRemark("");
                }
            }
        }

        object.setList(customerProjectEntities);
        return object;
    }

    /**
     * 获取项目下客户列表
     */
    private House365RestObject<CustomerEntity> doGetCustomers(Map<String, Object> map) throws Exception {
        House365RestObject<CustomerEntity> object = new House365RestObject<>();

        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String projectId = getMapValueByKey(Constant.PROJECT_ID, map, "");
        String currentPage = getMapValueByKey(Constant.CURRENT_PAGE, map, "1");
        String timeFilter = getMapValueByKey(Constant.TIME_FILTER, map, "");
        String projectFilter = getMapValueByKey(Constant.PROJECT_FILTER, map, "");
        String buyIntentionFilter = getMapValueByKey(Constant.BUY_INTENTION_FILTER, map, "");
        String keyword = getMapValueByKey("keyword", map, "");
        LOGGER.debug(
                "==doGetCustomers>>projectId:{}==currentPage:{}==timeFilter:{}==projectFilter:{}==buyIntentionFilter:{}==keyword:{}==",
                projectId, currentPage, timeFilter, projectFilter, buyIntentionFilter, keyword);
        if (Strings.isNullOrEmpty(phone) || Strings.isNullOrEmpty(projectId)) {
            return object;
        }

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

        qm.put("EQ_projectId", projectId);
        //4.1版本修改，可以查询公海数据
//        qm.put("ISNOTNULL_managerId", "");
        if (!Strings.isNullOrEmpty(timeFilter)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            switch (timeFilter) {
                case "1":
                    qm.put("LTE_createTimeEnd", calendar.getTime());
                    calendar.add(Calendar.DATE, -7);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 0);
                    qm.put("GTE_createTimeStart", calendar.getTime());
                    break;
                case "2":
                    qm.put("LTE_createTimeEnd", calendar.getTime());
                    calendar.add(Calendar.DATE, -15);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 0);
                    qm.put("GTE_createTimeStart", calendar.getTime());
                    break;
                case "3":
                    qm.put("LTE_createTimeEnd", calendar.getTime());
                    calendar.add(Calendar.DATE, -30);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 0);
                    qm.put("GTE_createTimeStart", calendar.getTime());
                    break;
                default:
                    break;
            }
        }
        if (!Strings.isNullOrEmpty(keyword)) {
            qm.put("EQ_likekeyword", "%" + keyword + "%");
        }
        if (!Strings.isNullOrEmpty(projectFilter)) {
            qm.put("EQ_projectStatus", projectFilter);
            cpMap.put("EQ_status", projectFilter);
        }
        if (!Strings.isNullOrEmpty(buyIntentionFilter)) {
            if (buyIntentionFilter.equals("99")) {
                qm.put("EQ_buyIntentionIsNull", "1");
            } else {
                qm.put("EQ_buyIntention", buyIntentionFilter);
            }
        }

        if (!Strings.isNullOrEmpty(projectId)) {
            cpMap.put("EQ_projectId", projectId);
        }
//        cpMap.put("EQ_isRepeat", 0);
        QueryParams queryParams = new QueryParams(cpMap);

        Set<Integer> customerIds = new HashSet<>();
        List<CustomerProjectEntity> customerProjectEntities = customerProjectService.queryAll(queryParams);
        for (CustomerProjectEntity customerProjectEntity : customerProjectEntities) {
            customerIds.add(customerProjectEntity.getCustomerId());
        }
        //组装客户与客户项目信息
        if (!customerIds.isEmpty()) {
            qm.put("IN_ids", Lists.newArrayList(customerIds));
            qm.put("EQ_orderBy", "last_change_status_time desc");

            QueryParams customerQueryParams = new QueryParams(qm);
            Page cplPage = new Page(10);
            cplPage.setCurrentPage(Integer.valueOf(currentPage));
            customerQueryParams.setPaging(cplPage);
            List<CustomerEntity> customerEntities = customerService.getWechatCustomers(customerQueryParams);
            //约看项目信息
            for (CustomerEntity customerEntity : customerEntities) {
                List<CustomerProjectEntity> cps = new ArrayList<>();

                for (CustomerProjectEntity cpe : customerProjectEntities) {
                    if (customerEntity.getId().equals(cpe.getCustomerId())) {
                        cps.add(cpe);
                    }
                }
                customerEntity.setCps(cps);
            }
            object.setList(customerEntities);
        }
        return object;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject doGetCustomerProject(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        CustomerEntity customerEntity = new CustomerEntity();
        List<BaseAttachment> attachments = new ArrayList<>();
        String projectId = getMapValueByKey(Constant.CUSTOMER_PROJECT_ID, map, "");
        LOGGER.debug("==doGetCustomerProject>>projectId:{}==", projectId);
        if (!Strings.isNullOrEmpty(projectId)) {
            customerEntity = getCustomerProjectEntity(projectId);
            attachments = attachmentService.queryByResourceIdAndResouceType(projectId, "hgs_customer_project");

            // 获取跟进阶段数据
            CustomerProjectStatusProgressVo statusProgress = getStatusProgress(projectId);
            customerEntity.setStatusProgress(statusProgress);
        }
        object.setEntity(customerEntity);
        List<CustomerProjectEntity> customerProjectEntities = customerEntity.getCps();
        if(CollectionUtils.isNotEmpty(customerProjectEntities)){
            CustomerProjectEntity customerProjectEntity = customerProjectEntities.get(0);
            if (customerProjectEntity.getRecordedStatus() == null) {
                customerProjectEntity.setRecordedStatus(-1);
            }
        }
        object.setList(attachments);
        return object;
    }

    /**
     * 获取跟进阶段数据
     *
     * @param customerProjectId
     * @return
     */
    private CustomerProjectStatusProgressVo getStatusProgress(String customerProjectId) {

        // 根据customerProjectId查customer_project表,得到customerId和projectId
        CustomerProjectEntity customerProject = customerProjectService.getById(Integer.valueOf(customerProjectId));

        Map<String, Object> searchParams = new HashMap<>(10);
        searchParams.put("EQ_customerId", customerProject.getCustomerId());
        searchParams.put("EQ_projectId", customerProject.getProjectId());
        Page page = new Page(Integer.MAX_VALUE);
        page.setCurrentPage(0);
        CustomerStatusLogListRequest customerStatusLogReq = new CustomerStatusLogListRequest();
        customerStatusLogReq.setPaging(page);
        customerStatusLogReq.setSearchParams(searchParams);
        CustomerStatusLogListResponse customerStatusLogRes = customerStatusLog.getCustomerStatusLogList(customerStatusLogReq);

        // 获取跟进阶段数据
        List<CustomerStatusLogEntity> listStatusLog = customerStatusLogRes.getObjectList();
        // 最大激活状态ID
        int maxActiveStatusId = -1;
        // 进度条明细
        Map<String, CustomerProjectStatusDetailVo> progressDetail = new HashMap<>();
        for (CustomerStatusLogEntity statusLog : listStatusLog) {
            // 过滤掉无效记录
            if (statusLog.getIsDelete() == 0) {
                // 当前记录的to_status_id
                Integer thisStatusId = statusLog.getToStatusId();
                // 找出最大激活状态ID
                if (thisStatusId > maxActiveStatusId) {
                    maxActiveStatusId = thisStatusId;
                }
                // 相同状态ID的记录只取create_time最大的
                if (!progressDetail.containsKey(String.valueOf(thisStatusId)) || progressDetail.get(String.valueOf(thisStatusId))
                        .getCreateTime()
                        .before(statusLog.getCreateTime())) {

                    Date showDate = statusLog.getOccurTime() == null ? statusLog.getCreateTime() : statusLog
                            .getOccurTime();
                    progressDetail.put(String.valueOf(thisStatusId),
                            new CustomerProjectStatusDetailVo(statusLog.getCreater(),
                                    showDate));
                }
            }
        }

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

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

        return statusProgress;
    }

    /**
     * 获取项目下的客户列表
     *
     * @param projectId 项目id
     * @return
     */
    private CustomerEntity getCustomerProjectEntity(String projectId) {
        CustomerEntity customerEntity = new CustomerEntity();

        CustomerProjectEntity customerProjectEntity = customerProjectService.getById(Integer.valueOf(projectId));
        List<CustomerProjectEntity> customerProjectEntities = new ArrayList<>();
        if (customerProjectEntity != null) {
            int id = customerProjectEntity.getCustomerId();
//            customerEntity = customerService.getById(id);
            customerEntity = mergeMapper.queryById(customerProjectEntity.getCustomerId());
            if (customerEntity == null) {
                CustomerEntity oldEntity = customerService.getById(id);
                if (oldEntity != null && oldEntity.getManagerId() != null) {
                    customerEntity = customer.getCustomerMerge(oldEntity.getPhone(), oldEntity.getManagerId());
                }
            }
            customerProjectEntities.add(customerProjectEntity);
            customerEntity.setCps(customerProjectEntities);
        }
        return customerEntity;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject doGetCustomerDetail(Map<String, Object> map) throws Exception {
        House365RestObject object = new House365RestObject();
        CustomerEntity customerEntity = new CustomerEntity();
        Map<String, Object> resultMap = new HashMap<>(10);

        //置业顾问手机
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String customerId = getMapValueByKey(Constant.CUSTOMER_ID, map, "");
        LOGGER.debug("==doGetCustomerDetail>>phone:{}==customerId:{}==", phone, customerId);
        UserEntity userEntity = getUserEntity(phone);
        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(customerId)) {
            CustomerEntity customer = mergeMapper.queryById(Integer.valueOf(customerId));
            if (customer == null) {
                customer = customerMapper.queryById(Integer.valueOf(customerId));
                Map<String, Object> mergeMap = new HashMap<>(10);
                mergeMap.put("phone", customer.getPhone());
                mergeMap.put("managerId", customer.getManagerId());
                customer = mergeMapper.getCustomerMerge(mergeMap);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            customerEntity = customer;
            //根据新的客户id获取旧表中的id
            Map<String, Object> idMap = new HashMap<>(10);
            idMap.put("phone", customerEntity.getPhone());
            idMap.put("managerId", customerEntity.getManagerId());
            idMap.put("isPrivate", 1);
            List<CustomerEntity> oldList = customerMapper.queryByConditions(idMap);
            if (CollectionUtils.isNotEmpty(oldList)) {
                Collections.reverse(oldList);
                for (CustomerEntity c : oldList) {
                    if (StringUtils.isNotBlank(c.getCreateSource())) {
                        if ("CRM拉取".equals(c.getCreateSource())) {
                            c.setCreateSource("营销活动");
                        } else if ("SYSTEM".equals(c.getCreateSource()) || "WECHAT".equals(c.getCreateSource())) {
                            c.setCreateSource("手动添加");
                        } else if ("HOTLINE".equals(c.getCreateSource())) {
                            c.setCreateSource("400来电");
                        } else if ("PT".equals(c.getCreateSource())) {
                            c.setCreateSource("平台导入");
                        }
                    }
                }
            }
            resultMap.put("oldList", oldList);
            List<Integer> customerIdList = new ArrayList<>();
            customerIdList.add(Integer.valueOf(customerId));
            if (CollectionUtils.isNotEmpty(oldList)) {
                for (CustomerEntity e : oldList) {
                    customerIdList.add(e.getId());
                }
            }

            //查询约看项目
            Map<String, Object> cpMap = new HashMap<>(10);
            cpMap.put("idList", customerIdList);
            List<CustomerProjectEntity> cpList = customerProject.queryList(cpMap);
            UserEntity user = getUserEntity(phone);
            if (CollectionUtils.isNotEmpty(cpList)) {
                for (CustomerProjectEntity cp : cpList) {
                    boolean flag = user.getPreLoginTime() != null && cp.getLastChangeStatusTime() != null && user.getPreLoginTime().before(cp.getLastChangeStatusTime());
                    if (flag) {
                        cp.setRemark("New!");
                    } else {
                        cp.setRemark("");
                    }
                }
            }
            resultMap.put("cpList", cpList);
            //查询回访记录
            List<CustomerCallbackLogEntity> backLogList = callbackMapper.queryByConditions(cpMap);
            if (CollectionUtils.isNotEmpty(backLogList)) {
                for (CustomerCallbackLogEntity c : backLogList) {
                    if (StringUtils.isNotBlank(c.getCallRecordName())) {
                        c.setCallRecordName("http://218.94.115.131:98/uncall_api/downloadFile.php?f_path=" + c.getCallRecordName());
                    }
                }
            }
            resultMap.put("backLogList", backLogList);

            //获取客户标签
            Map<String, Object> labelMap = new HashMap<String, Object>();
//            labelMap.put("createId",userEntity.getId());
            List<LabelEntity> labelDetailList = iuser.queryCustomerLabel(null, customerEntity.getId());
            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());
                            labs.add(oldLabEntity);
                        }
                    }
                }
            }
            resultMap.put("labs", labs);

            //查询客户日志列表
            Map<String, Object> searchMap = new HashMap<>(10);
            searchMap.put("phone", customer.getPhone());
            searchMap.put("managerId", customer.getManagerId());
            searchMap.put("idList", customerIdList);
            List<CustomerLogEntity> list = logMapper.queryByConditions(searchMap);
            List<Map<String, Object>> logShowList = new ArrayList<>(15);
            if (CollectionUtils.isNotEmpty(list)) {
                for (CustomerLogEntity p : list) {
                    //获取String类型的时间
                    String showTime = sdf.format(p.getCreateTime());
                    Map<String, Object> logMap = new HashMap<>(10);
                    logMap.put("createTime", showTime);
                    String showWord = "";
                    if (p.getType() == 1) {
                        showWord = p.getCreateUserName() + "  [新增客户]";
                    } else if (p.getType() == 2) {
                        StringBuilder builder = new StringBuilder();
                        builder.append("   ").append(p.getCreateUserName()).append("  [编辑客户]  ");
                        builder.append("将  '").append(p.getModifyName()).append("'  由  '").append(p.getOldValue())
                                .append("'  修改为  '").append(p.getNewValue()).append("' , ");
                        showWord = builder.toString().substring(0, builder.toString().lastIndexOf(","));
                    } else if (p.getType() == 3) {
                        showWord = p.getCreateUserName() + "  [删除客户]";
                    } else if (p.getType() == 4) {
                        //营销活动派工
                        showWord = p.getCreateUserName() + "  [营销活动-派工客户]" + "给  ";
                        if (StringUtils.isNotBlank(p.getNewValue())) {
                            UserEntity showUser = userService.getById(Integer.valueOf(p.getNewValue()));
                            if (null != showUser) {
                                showWord = showWord + showUser.getRealName();
                            }
                        }
                    } else if (p.getType() == 5) {
                        //公海派工
                        showWord = p.getCreateUserName() + " [公海-派工客户]" + "给  ";
                        if (StringUtils.isNotBlank(p.getNewValue())) {
                            UserEntity showUser = userService.getById(Integer.valueOf(p.getNewValue()));
                            if (null != showUser) {
                                showWord = showWord + showUser.getRealName();
                            }
                        }
                    } else if (p.getType() == 6) {
                        //移入派工
                        showWord = p.getCreateUserName() + " [移入公海]";
                    } else if (p.getType() == 7) {
                        //转移客户
                        showWord = p.getCreateUserName() + " [转移客户]" + "给  ";
                        if (StringUtils.isNotBlank(p.getNewValue())) {
                            UserEntity showUser = userService.getById(Integer.valueOf(p.getNewValue()));
                            if (null != showUser) {
                                showWord = showWord + showUser.getRealName();
                            }
                        }
                    } else if (p.getType() == 8) {
                        //无变动
                        showWord = p.getCreateUserName() + " [无变动]";
                    } else if (p.getType() == 9) {
                        //抢客数据公海派工
                        showWord = p.getCreateUserName() + " [云迹活动-派工客户]" + " 给 " + p.getNewValue();
                    }
                    logMap.put("showWord", showWord);
                    logShowList.add(logMap);
                }
                resultMap.put("logShowList", logShowList);
            }
        }
        resultMap.put("customer", customerEntity);
        object.setEntity(resultMap);
        return object;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<CustomerStatusLogEntity> doGetCustomerStatusChangeLogs(Map<String, Object> map) throws Exception {
        House365RestObject<CustomerStatusLogEntity> object = new House365RestObject<>();
        List<CustomerStatusLogEntity> statusLogEntities = new ArrayList<>();

        String customerId = getMapValueByKey(Constant.CUSTOMER_ID, map, "");
        String projectId = getMapValueByKey(Constant.PROJECT_ID, map, "");
        LOGGER.debug("==doGetCustomerStatusChangeLogs>>customerId:{}==projectId:{}==", customerId, projectId);
        if (!Strings.isNullOrEmpty(customerId) && !Strings.isNullOrEmpty(projectId)) {
            Map<String, Object> logMap = new HashMap<>(10);
            logMap.put("EQ_customerId", customerId);
            logMap.put("EQ_projectId", projectId);
            QueryParams<CustomerStatusLogEntity> queryParams = new QueryParams<>(logMap);
            queryParams.setOrderColumn("create_time");
            queryParams.setOrderMode("desc");
            statusLogEntities = statusLogService.queryByPage(queryParams);
        }

        object.setList(statusLogEntities);
        return object;
    }

    /**
     * 客户报备
     *
     * @param parameter
     * @return
     * @throws ServiceRunException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object customerReport(Parameter parameter) throws ServiceRunException {
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        try {
            House365RestObject<CustomerEntity> data = new House365RestObject<>();
            String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
            String projectId = getMapValueByKey(Constant.PROJECT_ID, map, "");
            String projectName = getMapValueByKey("projectName", map, "");
            String content = getMapValueByKey("content", map, "");
            String customerName = getMapValueByKey(Constant.CUSTOMER_NAME, map, "");
            String customerPhone = getMapValueByKey("customerPhone", map, "");
            Date date = new Date();
            LOGGER.debug("==customerReport>>phone:{}==projectId:{}==projectName:{}==customerName:{}==content:{}==",
                    phone, projectId, customerName, customerPhone, content);
            if (StringUtils.isNotBlank(phone)) {
                UserEntity user = getUserEntity(phone);
                if (user != null) {
                    DepartmentEntity department = departmentService.getById(user.getDeptId());
                    DepartmentEntity dept = departmentService.getById(Integer.valueOf(department.getCityID()));
                    String city = dept.getDescripition();
                    //约看项目 查询是否约看过这个项目
                    ProjectEntity project;
                    if (StringUtils.isNotBlank(projectId) && !"0".equals(projectId)) {
                        project = projectService.getById(Integer.valueOf(projectId));
                    } else {
                        Map<String, Object> queryMap = new HashMap<>(5);
                        queryMap.put("projectName", projectName);
                        queryMap.put("city", city);
                        List<ProjectEntity> projectList = projectMapper.queryByConditions(queryMap);
                        if (CollectionUtils.isNotEmpty(projectList)) {
                            project = projectList.get(0);
                        } else {
                            response.setResult("102");
                            response.setMsg("项目不存在，请重新选择");
                            response.setData(data);
                            return JSONObject.fromObject(response).toString();
                        }
                    }
                    //判断客户是否为报备人私客
                    Map<String, Object> searchMap = new HashMap<>(10);
                    searchMap.put("managerId", user.getId());
                    searchMap.put("phone", customerPhone);
                    List<CustomerEntity> list = mergeMapper.queryByConditions(searchMap);
                    int customerId = 0;
                    final CustomerEntity customerEntity1;
                    if (CollectionUtils.isNotEmpty(list)) {
                        CustomerEntity customer = list.get(0);
                        customerId = customer.getId();
                        CustomerEntity oldEntity = customerService.getById(customerId);
                        customerEntity1 = customer;
                        //需要合并
//                        if (!"1".equals(customer.getBuyIntention())) {
                        customer.setBuyIntention("1");
                        customer.setLastCallTime(date);
                        customerService.update(customer);
                        CustomerEntity newEntity = customerService.getById(customerId);
                        //调用工具类添加日志方法
                        logUtils.newRecordOperateLog(oldEntity, newEntity, customerId, user.getId(), user.getRealName());
                        //更新customer_merge新表
                        Map<String, Object> updateMap = new HashMap<>(10);
                        updateMap.put("buyIntention", "1");
                        updateMap.put("updateTime", date);
                        updateMap.put("id", customerId);
                        updateMap.put("lastCallTime", date);
                        mergeMapper.update(updateMap);
//                        }
                    } else {
                        //创建私客
                        CustomerEntity customer = getCustomer(customerName, customerPhone, user, city, dept.getName());
                        customerId = customerService.save(customer);
                        customer.setId(customerId);
                        mergeMapper.saveCustomerMerge(customer);
                        customerEntity1 = customer;
                        //记录客户新增日志
                        logUtils.saveCustomerLog(customer, 1, user.getId(), user.getRealName());
                    }

                    CustomerProjectEntity cp = new CustomerProjectEntity();
                    Map<String, Object> checkMap = new HashMap<>(10);
                    List<Integer> idList = new ArrayList<>();
                    idList.add(customerId);
                    checkMap.put("projectId", project.getId());
                    checkMap.put("idList", idList);
                    List<CustomerProjectEntity> cpList = customerProjectMapper.queryByConditions(checkMap);
                    if (CollectionUtils.isNotEmpty(cpList)) {
                        //约看过则直接返回
                        response.setResult("101");
                        response.setMsg("该客户已约看到该项目，请核实");
                        response.setData(data);
                        return JSONObject.fromObject(response).toString();
                    } else {
                        if (project != null) {
                            int repeatCount = customerProjectService.checkRepeat(customerPhone, projectId);

                            cp.setCreateTime(date);
                            cp.setCreater(user.getRealName());
                            cp.setStatus(Constant.CustomerStatusEnum.RECORDED.getStatus());
                            cp.setRecordedTime(new Date());
                            cp.setLastChangeStatusTime(date);
                            cp.setContract(project.getContractCode());
                            cp.setCustomerId(customerId);
                            cp.setCustomerPhone(customerPhone);
                            cp.setHouseName(project.getBuildingName());
                            cp.setProjectName(project.getProjectName());
                            cp.setProjectId(project.getId());
                            if (repeatCount > 0) {
                                cp.setIsRepeat(1);
                            } else {
                                cp.setIsRepeat(0);
                            }
                            cp.setProjectId(project.getId());

                            String remark = "楼盘约看";
                            if (repeatCount > 0) {
                                remark += "【" + DateTimeUtils.getCurrentDateString() + "】【重客】";
                            }
                            final Integer cpid = customerProjectService.save(cp);
                            CustomerStatusLogEntity statusLogEntity = new CustomerStatusLogEntity();

                            statusLogEntity.setFromStatusId(0);
                            statusLogEntity.setFromStatusName("");
                            statusLogEntity.setToStatusId(1);
                            statusLogEntity.setToStatusName("约看");
                            statusLogEntity.setRemark(remark);
                            statusLogEntity.setCreater(user.getRealName());
                            statusLogEntity.setCreateTime(date);
                            statusLogEntity.setCustomerId(customerId);
                            statusLogEntity.setCustomerManagerId(customerId);
                            statusLogEntity.setCustomerManagerName(user.getRealName());
                            statusLogEntity.setProjectId(Integer.valueOf(projectId));
                            if (repeatCount > 0) {
                                statusLogEntity.setIsRepeat(1);
                            } else {
                                statusLogEntity.setIsRepeat(0);
                            }
                            statusLogEntity.setNonStatistic(1);
                            statusLogEntity.setOccurTime(date);
                            statusLogEntity.setIsDelete(0);
                            CustomerStatusLogRequest logRequest = new CustomerStatusLogRequest();
                            logRequest.setEntity(statusLogEntity);
                            customerStatusLog.addCustomerStatusLog(logRequest);
                            //添加回访
                            CustomerCallbackLogEntity logEntity = new CustomerCallbackLogEntity();
                            logEntity.setCustomerId(customerId);
                            logEntity.setManagerId(user.getId());
                            logEntity.setManagerName(user.getRealName());
                            logEntity.setContent(content);
                            logEntity.setResult("");
                            logEntity.setCreateTime(new Date());
                            logEntity.setCreater(user.getRealName());
                            callbackMapper.saveCallBackLog(logEntity);


                            //发送通知
                            final ProjectEntity projectEntity = project;
                            final CustomerProjectEntity cpe = cp;
                            final List<String> mobiles = userService.getMobilesByProject(project.getId());

                            // 配置文件
                            final String url = MemoryPropertyPlaceholderConfigurer.getContextProperty(
                                    "system.customer.noticeUrl");
                            final String date1 = DateTimeUtils.getDateString(new Date(),
                                    DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);
                            final String smsMsg = "您好！客户[" + customerName + "] [" + customerPhone + "]在[" + date1 + "]被置业顾问[" + user.getRealName() + "]约看,约看至[" + projectEntity.getProjectName() + "]，请核对!";
                            final String paras = "@1@::[" + com.house365.web.util.StringUtils.StringFilter(
                                    customerName) + "]||@2@::[" + customerPhone + "]||@3@::[" + date + "]||@4@::[" + user.getRealName() + "]||@5@::[" + projectEntity.getProjectName() + "]";
                            final String city1 = city;

                            ExecutorService executor = Executors.newCachedThreadPool();
                            executor.execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        for (String mobile : mobiles) {
                                            SmsUtils.hgsCustomerRecordSendSms(city1, mobile, smsMsg, paras, url);
                                        }
                                        String result = customerProjectService.postToCRM(cpe, new Date(), projectEntity,
                                                customerEntity1);
                                        LOGGER.info("call CRM change customer status result:{}", result);

                                    } catch (java.io.IOException e) {
                                        LOGGER.error("call CRM ERROR:" + e.getMessage(), e);
                                    }
                                }
                            });

                            //send wechat msg
                            executor.execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        final List<String> ids = userService.getIdsByProject(projectEntity.getId());
                                        Map<String, String> param = new HashMap<>();
                                        param.put("customerId", String.valueOf(customerEntity1.getId()));
                                        param.put("projectName", projectEntity.getProjectName());
                                        param.put("customerName", customerEntity1.getName());
                                        param.put("customerPhone", customerEntity1.getPhone());
                                        param.put("managerName", customerEntity1.getManagerName());
                                        param.put("customerProjectId", String.valueOf(cpid));
                                        customerService.sendMessageToWechat(NEWRECORDCUSTOMER, Joiner.on("|").join(ids), param);

                                    } catch (Exception e) {
                                        LOGGER.error("send wechat msg ERROR:" + e.getMessage(), e);
                                    }
                                }
                            });
                        }
                    }
                }
            }
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg("快速报备客户成功");
            response.setData(data);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("快速报备客户失败", e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg("快速报备客户失败:" + e.getMessage());
        }
        String result = JSONObject.fromObject(response).toString();
        LOGGER.debug("===customerReport==result===:{}", result);
        return result;
    }

    private CustomerEntity getCustomer(String name, String phone, UserEntity user, String city, String cityName) {
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setName(name);
        customerEntity.setPhone(phone);
        customerEntity.setBakPhone1("");
        customerEntity.setBakPhone2("");
        customerEntity.setBakPhone3("");
        customerEntity.setSex(2);
        customerEntity.setCustomerType(1);
        customerEntity.setActSource("");
        customerEntity.setBuyIntention("1");
        customerEntity.setFirstSource("");
        customerEntity.setLatestSource("");
        customerEntity.setCrmLatestCall("");
        customerEntity.setStatus(11);
        customerEntity.setCreateSource("WECHAT");
        customerEntity.setCreater(user.getRealName());
        customerEntity.setCreateTime(new Date());
        customerEntity.setBuyIntention("1");
        customerEntity.setLastVisitTime(null);
        customerEntity.setLastCallTime(new Date());
        customerEntity.setManagerId(user.getId());
        customerEntity.setManagerName(user.getRealName());
        customerEntity.setUpdater(user.getRealName());
        customerEntity.setUpdateTime(new Date());
        customerEntity.setCityCode(city);
        customerEntity.setBizPort("");
        customerEntity.setCrmId("");
        customerEntity.setCityName(cityName);
        customerEntity.setActSourceId(0);
        customerEntity.setRemark("");
        customerEntity.setTraceStatus(1);
        customerEntity.setCrmSync("0");
        customerEntity.setHotlineCallTime(null);
        customerEntity.setHotlineCallSpend("");
        customerEntity.setOceanDate(null);
        customerEntity.setIsDelete(0);
        customerEntity.setLastManager("");
        customerEntity.setBindTime(new Date());
        customerEntity.setCustomerSourceType(1);
        customerEntity.setCustomerRelId(0);
        customerEntity.setIsWaitCall(0);
        customerEntity.setSingupTime("");
        customerEntity.setMarketActId(0);
        customerEntity.setMarketActName("");
        customerEntity.setIsPeer(0);
        customerEntity.setStarCustomer(0);
        customerEntity.setIsHandover(0);
        customerEntity.setIsRecycled(0);
        customerEntity.setIsActive(0);
        customerEntity.setActiveTime(null);
        customerEntity.setNewCycle("0");
        return customerEntity;
    }

    @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 + "参数为空!");
            }
        }
    }

    /**
     * 同一楼盘相同约看手机号变更为到访及以后状态，其他约看纪录设置为重客
     *
     * @param phone
     * @param pid
     * @param excludeId
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    private void setRepeat(String phone, Integer pid, Integer excludeId, String oper) throws Exception {
        Page page = new Page(Integer.MAX_VALUE);
        QueryParams queryParams = new QueryParams();
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("NOTEQ_id", excludeId);
        searchMap.put("EQ_status", Constant.CustomerStatusEnum.RECORDED.getStatus());
        searchMap.put("EQ_customerPhone", phone);
        searchMap.put("EQ_projectId", pid);
        searchMap.put("EQ_isRepeat", 0);

        queryParams.setPaging(page);
        queryParams.setSearchParams(searchMap);
        List<CustomerProjectEntity> cpes = customerProjectService.queryAll(queryParams);

        String remark = "【" + DateTimeUtils.getCurrentDateString() + "】【重客】";

        if (cpes != null && !cpes.isEmpty()) {
            for (CustomerProjectEntity cpe : cpes) {
                cpe.setIsRepeat(1);
                customerProjectService.update(cpe);
                //重客 不参与统计
                statusLogService.addStatusLogWithProject(cpe.getCustomerId(), cpe.getStatus(), cpe.getStatus(), remark,
                        oper, null, cpe.getProjectId(), 1, 0);
            }
        }

    }

    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 int getMondayPlus(Calendar calendar) {
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            return -6;
        } else {
            return 2 - dayOfWeek;
        }
    }
}
