package com.house365.ws.interfaces.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerCallbackLogEntity;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.MessageEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.commons.system.HttpClientUtil;
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.MemoryPropertyPlaceholderConfigurer;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.response.CustomerResponse;
import com.house365.ws.dao.mapper.CustomerMapper;
import com.house365.ws.dao.mapper.CustomerMergeMapper;
import com.house365.ws.dao.mapper.MessageMapper;
import com.house365.ws.interfaces.server.ICustomer;
import com.house365.ws.interfaces.server.ICustomerCallbackLog;
import com.house365.ws.service.interfaces.ICustomerService;
import com.house365.ws.service.interfaces.IUserService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.Constant;
import com.house365.ws.util.MergeCustomerUtil;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
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 java.text.SimpleDateFormat;
import java.util.*;

@Service("addPromoteCustomer")
public class AddPromoteCustomerImpl implements IAddPromoteCustomer {
    private static final int TRACE_STATUS_INVALID = 1;
    private static final Logger LOGGER = LoggerFactory.getLogger(AddCustomerInfoImpl.class);
    private String smUrl = "http://mysms.house365.com/index.php/Interface/apiSendMobil/jid/104/depart/1/city/";
    @Autowired
    private ICustomerService<CustomerEntity> customerService;
    @Autowired
    private IUserService<UserEntity> userService;
    @Autowired
    private ICustomer customer;
    @Autowired
    private ICustomerCallbackLog customercallbacklog;
    @Autowired
    private MergeCustomerUtil mergeCustomerUtil;
    @Autowired
    private MessageMapper messagemapper;
    @Autowired
    private CustomerMapper customermapper;
    @Autowired
    private CustomerMergeMapper customermergemapper;

    public static void main(String[] args) {
        System.out.println(MemoryPropertyPlaceholderConfigurer.getContextProperty("tangfanghui.server.url"));
    }


    private synchronized static CustomerEntity getCustomer(Map<String, Object> map) {
        String name = getMapValueByKey(Constant.CUSTOMER_NAME, map, "");
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String cityCode = getMapValueByKey(Constant.CITY_CODE, map, "");
        String cityName = getMapValueByKey(Constant.CITY_NAME, map, "");
        String crmId = getMapValueByKey(Constant.CRMID, map, "");
        String sex = getMapValueByKey(Constant.CUSTOMER_SEX, map,
                String.valueOf(Constant.CustomerSexEnum.NOTSURE.getMsg()));
        String actSource = getMapValueByKey(Constant.CUSTOMER_ACTSOURCE, map, "");
        String firstSource = getMapValueByKey(Constant.CUSTOMER_FIRSTSOURCE, map, "");
        String latestSource = getMapValueByKey(Constant.CUSTOMER_LATESTSOURCE, map, "");
        String latestCall = getMapValueByKey(Constant.CUSTOMER_CRM_LATESTSCALL, map, "");
        String latestCallResult = getMapValueByKey(Constant.CUSTOMER_CRM_LATESTSCALL_RESULT, map, "");
        String bizPort = getMapValueByKey("bizPort", map, "");
        String requestType = getMapValueByKey("requestType", map, "");
        String lastJoinVisitRemark = getMapValueByKey("lastJoinVisitRemark", map, "");

        String lastJoinVisitTime = getMapValueByKey("lastJoinVisitTime", map, "");

        String projectId = getMapValueByKey(Constant.PROJECT_ID, map, "");
        String channel = getMapValueByKey(Constant.CHANNEL, map, "");
        Date newdate = new Date();

        actSource = StringUtils.StringFilter(actSource);
        CustomerEntity customerEntity = new CustomerEntity();

        customerEntity.setProjectId(projectId);
        customerEntity.setChannel(channel);
        customerEntity.setName(name);
        customerEntity.setPhone(phone);
        customerEntity.setCityCode(cityCode);
        customerEntity.setCityName(cityName);
        customerEntity.setCrmId(crmId);
        customerEntity.setSex(Integer.valueOf(sex));
        customerEntity.setBizPort(bizPort);
        customerEntity.setActSource(actSource);
        customerEntity.setFirstSource(firstSource);
        customerEntity.setBindTime(newdate);
        customerEntity.setCrmLatestCallResult(latestCallResult);
        if ("5".equals(requestType)) {
            customerEntity.setCreateSource("留电");
            customerEntity.setCustomerSourceType(5);
            customerEntity.setLastJoinVisitWorker("客户留电");
            if ("".equals(lastJoinVisitRemark.trim())) {
                customerEntity.setLastJoinVisitRemark("客户无备注,详见CRM视图");
            } else {
                customerEntity.setLastJoinVisitRemark(lastJoinVisitRemark);
            }
        }
        if ("6".equals(requestType)) {
            customerEntity.setCreateSource("IM咨询");
            customerEntity.setCustomerSourceType(6);
            customerEntity.setLastJoinVisitWorker("客服");
            if ("".equals(lastJoinVisitRemark.trim())) {
                customerEntity.setLastJoinVisitRemark("客服无备注,详见CRM视图");
            } else {
                customerEntity.setLastJoinVisitRemark("客服已备注:" + lastJoinVisitRemark);
            }
        }
        if ("4".equals(requestType)) {
            customerEntity.setCreateSource("推广宝");
            customerEntity.setCustomerSourceType(4);
        }

        customerEntity.setCustomerType(Constant.CustomerTypeEnum.ONLINE.getMsg());
        customerEntity.setLatestSource(latestSource);
        customerEntity.setCrmLatestCall(latestCall);
        customerEntity.setBuyIntention("1");
        customerEntity.setCreateTime(newdate);
        customerEntity.setCreater("CRM");
        customerEntity.setUpdater("CRM");
        customerEntity.setUpdateTime(newdate);
        //客户状态:状态 0 未约看 1 约看、2 到访、3 认筹、4 认购、5 签约、6 退房
        customerEntity.setStatus(Constant.CustomerStatusEnum.NORECORD.getStatus());
        customerEntity.setTraceStatus(TRACE_STATUS_INVALID);
        customerEntity.setIsDelete(0);

        customerEntity.setLastJoinVisitTime(lastJoinVisitTime);
        return customerEntity;
    }

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param defaultValue 默认值
     * @return value
     */
    private static 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;
    }

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

    @Override
    public void commit() {

    }

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

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

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

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


    /**
     * 业务层统逻辑处理
     */
    private synchronized House365RestObject<CustomerEntity> doBusiness(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();
        Date newdate = new Date();
        CustomerEntity customerEntity = getCustomer(map);

        String lastJoinVisitTime = customerEntity.getLastJoinVisitTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date lastjoinvisittime = sdf.parse(lastJoinVisitTime);
        //客户经理
        String userId = getMapValueByKey(Constant.USER_ID, map, "");

        //请求来源类型:5:留电,6::IM咨询
        String requestType = getMapValueByKey("requestType", map, "");
        String userName1 = "";
        String userName2 = "";
        Map<String, Object> searchMap = new HashMap<>(10);
        if ("6".equals(requestType)) {
            userName1 = "IM咨询";
            userName2 = "IM咨询导入接口";
            searchMap.put("customerSourceType", "6");
        }
        if ("5".equals(requestType)) {
            userName1 = "留电";
            userName2 = "留电导入接口";
            searchMap.put("customerSourceType", "5");
        }
        boolean isProtected = false;
        UserEntity userEntity = new UserEntity();
        //判断有误保护期限制
        searchMap.put("phone", customerEntity.getPhone());
        searchMap.put("cityCode", customerEntity.getCityCode());
        List<CustomerEntity> customerInfo = customermapper.queryManagerByPhone(searchMap);
        //查询该城市设置客户保护期
        Integer period = customermergemapper.getCityPeriod(customerEntity.getCityCode());
        if (StringUtils.isNotBlank(userId)) {
            userEntity = userService.getById(Integer.valueOf(userId));
            if (customerInfo != null) {
                Date nowDate = new Date();
                for (CustomerEntity ce : customerInfo) {
                    Date createTime = ce.getCreateTime();
                    int days = differentDaysByDate(createTime, nowDate);
                    if (days < period) {//仍在保护期内
                        isProtected = true;
                        //查询保护期内置业顾问手机号
                        UserEntity protectManager = userService.getById(ce.getManagerId());
                        userEntity.setMobile(protectManager.getMobile());//保护期内短信下发给保护期内安家顾问
                        customerEntity.setManagerId(ce.getManagerId());//保护期内咨询客户属于保护期内安家顾问
                        userEntity.setRealName(ce.getManagerName());//保护期内咨询客户属于保护期内安家顾问
                        break;
                    }
                }
            }
        } else {
            if (customerInfo != null) {
                Date nowDate = new Date();
                for (CustomerEntity ce : customerInfo) {
                    Date createTime = ce.getCreateTime();
                    int days = differentDaysByDate(createTime, nowDate);
                    if (days < period) {//仍在保护期内
                        isProtected = true;
                        //查询保护期内置业顾问手机号
                        UserEntity protectManager = userService.getById(ce.getManagerId());
                        userEntity.setMobile(protectManager.getMobile());//保护期内短信下发给保护期内安家顾问
                        customerEntity.setManagerId(ce.getManagerId());//保护期内咨询客户属于保护期内安家顾问
                        userEntity.setRealName(ce.getManagerName());//保护期内咨询客户属于保护期内安家顾问
                        break;
                    }
                }
            }
        }
        //保护期内其余客户进线设0，第一条为1
        if (isProtected) {
            customerEntity.setNewCycle("0");
        } else {
            //不在保护期内,客户日志安家顾问id记录
            if (StringUtils.isNotBlank(userId)) {
                if (userEntity.getId() != null && !"".equals(userEntity.getId())) {
                    customerEntity.setManagerId(userEntity.getId());
                }
            }
            customerEntity.setNewCycle("1");
        }
        //先判断保护期后进线
        CustomerEntity newcustomerentity = customerService.createCustomer(customerEntity, Constant.CustomerSourceEnum.CRM.getMsg(), userName1);
        LOGGER.warn("CRMADDCUSTOMER --- [{}]", customerEntity.toString());

        CustomerCallbackLogEntity customercallbacklogentity = new CustomerCallbackLogEntity();
        //留电
        if ("5".equals(requestType)) {
            if (StringUtils.isNotBlank(userId)) {
                UserEntity user = userService.getById(Integer.valueOf(userId));
                if (user != null) {
                    customerEntity.setManagerId(user.getId());
                    //如果传了userid，绑定客户经理
                    customerService.bindCustomer(customerEntity, user);
                }
                customercallbacklogentity.setManagerId(Integer.valueOf(userId));

                //校验客户合并
                CustomerEntity oldentity = customer.getCustomerMerge(customerEntity.getPhone(), Integer.valueOf(userId));
                if (oldentity == null) {
                    customerEntity.setId(newcustomerentity.getId());
                    handleCustomerMerge(customerEntity);
                    customer.saveCustomerMerge(customerEntity);
                    //公海客户查询
                    List<CustomerEntity> seaCustomers = customer.getSeaCustomerByPhone(customerEntity, user);
                    //没有私客，将公海该客户数据同步更新到该顾问名下
                    if (seaCustomers != null && seaCustomers.size() > 0) {
                        customer.updateSeaCustomerByPhone(customerEntity, user);
                    }
                } else {
                    mergeCustomerUtil.checkMergeCustomer(customerEntity, oldentity, 0, userName2);
                    // 意向等级、跟踪状态更新
                    oldentity.setUpdater(user.getName());
                    oldentity.setUpdateTime(newdate);
                    oldentity.setCreateTime(customerEntity.getCreateTime());
                    oldentity.setBindTime(newdate);
                    handleCustomerMerge(oldentity, lastjoinvisittime);
//                    oldentity.setLastCallTime(customerEntity.getLastCallTime());
                    customer.updateCustomerMerge(oldentity);
                }

                MessageEntity customerMe = new MessageEntity();
                customerMe.setManagerId(String.valueOf(customerEntity.getManagerId()));
                customerMe.setCreateTime(newdate);
                customerMe.setPhone(customerEntity.getPhone());
                customerMe.setManagerPhone(user.getMobile());
                Integer sendNum = 0;
                String customermsg = "【三六五】您好,您的咨询需求我们已经收到,安家顾问[" + customerEntity.getManagerName() + "](电话:[" + user.getMobile() + "])将会尽快联系您,沟通定制专属置业方案,请保持手机畅通.";
//                customermsg = URLEncoder.encode(customermsg, "GBK");
                smUrl = smUrl + customerEntity.getCityCode() + "/" + "mobileno/" + customerEntity.getPhone();
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("msg", customermsg));
                String result = HttpClientUtil.doGet(smUrl, params, null);//发送客户
                customerMe.setRequestType("5");
                if (result != null) {
                    customerMe.setCustomerStatus("1");
                    sendNum++;
                } else {
                    customerMe.setCustomerStatus("0");
                }
                String managermsg = "【三六五】你好,你在" + sdf.format(new Date()) + "有一条用户留电需求待处理,留电人手机[" + customerEntity.getPhone() + "]" + ",请尽快登录全链条后台,进行回访处理.";
                smUrl = smUrl + customerEntity.getCityCode() + "/" + "mobileno/" + user.getMobile();
                List<NameValuePair> params2 = new ArrayList<>();
                params2.add(new BasicNameValuePair("msg", managermsg));
                String result2 = HttpClientUtil.doGet(smUrl, params2, null);//发送安家顾问
                if (result2 != null) {
                    customerMe.setManagerStatus("1");
                    sendNum++;
                } else {
                    customerMe.setManagerStatus("0");
                }
                customerMe.setSendNum(sendNum);
                //日志记录
                messagemapper.saveMessageLog(customerMe);
            }
        }
        //IM咨询
        if ("6".equals(requestType)) {
            if (StringUtils.isNotBlank(userId)) {
                //判定绑定安家顾问
                if (isProtected) {
                    userEntity.setId(customerEntity.getManagerId());
                    customerService.bindCustomer(customerEntity, userEntity);
                    customercallbacklogentity.setManagerId(customerEntity.getManagerId());
                } else {//不在保护期:newcycle开始新一轮周期
                    if (userEntity != null) {
                        customerEntity.setManagerId(userEntity.getId());
                        //如果传了userid，绑定客户经理
                        customerService.bindCustomer(customerEntity, userEntity);
                    }
                    customercallbacklogentity.setManagerId(Integer.valueOf(userId));
                }
                //校验客户合并
                CustomerEntity oldentity = customer.getCustomerMerge(customerEntity.getPhone(), customerEntity.getManagerId());
                if (oldentity == null) {
                    customerEntity.setId(newcustomerentity.getId());
                    handleCustomerMerge(customerEntity);
                    customer.saveCustomerMerge(customerEntity);
                    //公海客户查询
                    List<CustomerEntity> seaCustomers = customer.getSeaCustomerByPhone(customerEntity, userEntity);
                    //没有私客，将公海该客户数据同步更新到该顾问名下
                    if (seaCustomers != null && seaCustomers.size() > 0) {
                        customer.updateSeaCustomerByPhone(customerEntity, userEntity);
                    }
                } else {
                    mergeCustomerUtil.checkMergeCustomer(customerEntity, oldentity, 0, userName2);
                    // 意向等级、跟踪状态更新
                    oldentity.setUpdater(userEntity.getName());
                    oldentity.setUpdateTime(newdate);
                    oldentity.setCreateTime(customerEntity.getCreateTime());
                    oldentity.setBindTime(newdate);
                    handleCustomerMerge(oldentity, lastjoinvisittime);
                    customer.updateCustomerMerge(oldentity);
                }
                //发送短信
                MessageEntity customerMe = new MessageEntity();
                customerMe.setManagerId(String.valueOf(customerEntity.getManagerId()));
                customerMe.setCreateTime(newdate);
                customerMe.setPhone(customerEntity.getPhone());
                customerMe.setManagerPhone(userEntity.getMobile());
                Integer sendNum = 0;
                String customermsg = "感谢您咨询365淘房房博士,根据您的置业需求,我们将安排安家顾问[" + customerEntity.getManagerName() + "],电话[" + userEntity.getMobile() + "],在您合适的时间给您回电,请注意接听,谢谢支持";
                smUrl = smUrl + customerEntity.getCityCode() + "/" + "mobileno/" + customerEntity.getPhone();
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("msg", customermsg));
                String sendresult = HttpClientUtil.doGet(smUrl, params, null);//发送客户
                customerMe.setRequestType("6");
                if (sendresult != null) {
                    customerMe.setCustomerStatus("1");
                    sendNum++;
                } else {
                    customerMe.setCustomerStatus("0");
                }
                String time = sdf.format(newdate);
                String managermsg = "";
                if (isProtected) {//在保护期内=非第一次IM咨询
                    managermsg = "你好,客户[" + customerEntity.getPhone() + "]再次咨询,咨询时间[" + time + "],请登录全链条后台查看.";
                } else {
                    managermsg = "你好,你在[" + time + "]有一条新的用户咨询需要处理,用户手机[" + customerEntity.getPhone() + "],请登录全链条后台查看.";
                }
                smUrl = smUrl + customerEntity.getCityCode() + "/" + "mobileno/" + userEntity.getMobile();
                List<NameValuePair> params2 = new ArrayList<>();
                params2.add(new BasicNameValuePair("msg", managermsg));
                String result2 = HttpClientUtil.doGet(smUrl, params2, null);//发送安家顾问
                if (result2 != null) {
                    customerMe.setManagerStatus("1");
                    sendNum++;
                } else {
                    customerMe.setManagerStatus("0");
                }
                customerMe.setSendNum(sendNum);
                //日志记录
                messagemapper.saveMessageLog(customerMe);
            } else {//没带导购id
                //查询淘房汇对应绑定楼盘的安家顾问id
                String projectId = customerEntity.getProjectId();
                String channel = customerEntity.getChannel();
                //判断有误保护期限制
                if (isProtected) {//在保护期内直接归属保护期内名下，短信通知保护期安家顾问
                    userEntity.setId(customerEntity.getManagerId());//没有带代购id且在保护期内，安家顾问未保护期内安家顾问
                    customerService.bindCustomer(customerEntity, userEntity);
                    customercallbacklogentity.setManagerId(userEntity.getId());
                    //校验客户合并
                    CustomerEntity oldentity = customer.getCustomerMerge(customerEntity.getPhone(), userEntity.getId());
                    if (oldentity == null) {
                        customerEntity.setId(newcustomerentity.getId());
                        handleCustomerMerge(customerEntity);
                        customer.saveCustomerMerge(customerEntity);
                        //公海客户查询
                        List<CustomerEntity> seaCustomers = customer.getSeaCustomerByPhone(customerEntity, userEntity);
                        //没有私客，将公海该客户数据同步更新到该顾问名下
                        if (seaCustomers != null && seaCustomers.size() > 0) {
                            customer.updateSeaCustomerByPhone(customerEntity, userEntity);
                        }
                    } else {
                        mergeCustomerUtil.checkMergeCustomer(customerEntity, oldentity, 0, userName2);
                        // 意向等级、跟踪状态更新
                        oldentity.setUpdater(userEntity.getName());
                        oldentity.setUpdateTime(newdate);
                        oldentity.setCreateTime(customerEntity.getCreateTime());
                        oldentity.setBindTime(newdate);
//                        oldentity.setLastCallTime(customerEntity.getLastCallTime());
                        handleCustomerMerge(oldentity, lastjoinvisittime);
                        customer.updateCustomerMerge(oldentity);
                    }

                    //发送短信
                    MessageEntity customerMe = new MessageEntity();
                    customerMe.setManagerId(String.valueOf(customerEntity.getManagerId()));
                    customerMe.setCreateTime(newdate);
                    customerMe.setPhone(customerEntity.getPhone());
                    customerMe.setManagerPhone(userEntity.getMobile());
                    Integer sendNum = 0;
                    String customermsg = "感谢您咨询365淘房房博士,根据您的置业需求,我们将安排安家顾问[" + customerEntity.getManagerName() + "],电话[" + userEntity.getMobile() + "],在您合适的时间给您回电,请注意接听,谢谢支持";
                    smUrl = smUrl + customerEntity.getCityCode() + "/" + "mobileno/" + customerEntity.getPhone();
                    List<NameValuePair> params = new ArrayList<>();
                    params.add(new BasicNameValuePair("msg", customermsg));
                    String sendresult = HttpClientUtil.doGet(smUrl, params, null);//发送客户
                    customerMe.setRequestType("6");
                    if (sendresult != null) {
                        customerMe.setCustomerStatus("1");
                        sendNum++;
                    } else {
                        customerMe.setCustomerStatus("0");
                    }
                    String time = sdf.format(newdate);
                    String managermsg = "";
                    if (isProtected) {//在保护期内=非第一次IM咨询
                        managermsg = "你好,客户[" + customerEntity.getPhone() + "]再次咨询,咨询时间[" + time + "],请登录全链条后台查看.";
                    } else {
                        managermsg = "你好,你在[" + time + "]有一条新的用户咨询需要处理,用户手机[" + customerEntity.getPhone() + "]请登录全链条后台查看.";
                    }
                    smUrl = smUrl + customerEntity.getCityCode() + "/" + "mobileno/" + userEntity.getMobile();
                    List<NameValuePair> params2 = new ArrayList<>();
                    params2.add(new BasicNameValuePair("msg", managermsg));
                    String result2 = HttpClientUtil.doGet(smUrl, params2, null);//发送安家顾问
                    if (result2 != null) {
                        customerMe.setManagerStatus("1");
                        sendNum++;
                    } else {
                        customerMe.setManagerStatus("0");
                    }
                    customerMe.setSendNum(sendNum);
                    //日志记录
                    messagemapper.saveMessageLog(customerMe);
                } else {//不在保护期
                    //未导购未带楼盘id
                    if (StringUtils.isEmpty(projectId)) {//导购id和楼盘id无,也不在保护期,回公海

                    } else {
                        List<NameValuePair> param = new ArrayList<>();
                        param.add(new BasicNameValuePair("serviceCode", "TaoFangHui"));
                        param.add(new BasicNameValuePair("serviceName", "getBindInfo"));
                        param.add(new BasicNameValuePair("city", customerEntity.getCityCode()));
                        param.add(new BasicNameValuePair("projectId", projectId));
                        if (StringUtils.isEmpty(channel)) {
                            param.add(new BasicNameValuePair("channel", "1"));
                        }
                        param.add(new BasicNameValuePair("channel", customerEntity.getChannel()));
                        String result = HttpClientUtil.doGet(MemoryPropertyPlaceholderConfigurer.getContextProperty("tangfanghui.server.url"), param, 4000, null);
                        if (result != null && !"".equals(result)) {
                            ObjectMapper objectMapper = new ObjectMapper();
                            Map<String, Map<String, Map>> webMap = objectMapper.readValue(result, Map.class);
                            List<Map<String, Object>> list = (List<Map<String, Object>>) webMap.get("data").get("entity").get("list");
                            int uId = Integer.parseInt(list.get(0).get("userId").toString());
                            UserEntity userEntity2 = userService.getById(uId);
                            if (userEntity != null) {
                                customerEntity.setManagerId(userEntity2.getId());
                                //如果传了userid，绑定客户经理
                                customerService.bindCustomer(customerEntity, userEntity2);
                            }
                            customercallbacklogentity.setManagerId(uId);

                            //校验客户合并
                            CustomerEntity oldentity = customer.getCustomerMerge(customerEntity.getPhone(), uId);
                            if (oldentity == null) {
                                customerEntity.setId(newcustomerentity.getId());
                                handleCustomerMerge(customerEntity);
                                customer.saveCustomerMerge(customerEntity);
                                //公海客户查询
                                List<CustomerEntity> seaCustomers = customer.getSeaCustomerByPhone(customerEntity, userEntity2);
                                //没有私客，将公海该客户数据同步更新到该顾问名下
                                if (seaCustomers != null && seaCustomers.size() > 0) {
                                    customer.updateSeaCustomerByPhone(customerEntity, userEntity2);
                                }
                            } else {
                                mergeCustomerUtil.checkMergeCustomer(customerEntity, oldentity, 0, userName2);
                                // 意向等级、跟踪状态更新
                                oldentity.setUpdater(userEntity2.getName());
                                oldentity.setUpdateTime(newdate);
                                oldentity.setCreateTime(customerEntity.getCreateTime());
                                oldentity.setBindTime(newdate);
                                handleCustomerMerge(oldentity, lastjoinvisittime);
                                customer.updateCustomerMerge(oldentity);
                            }
                            //发送短信
                            MessageEntity customerMe = new MessageEntity();
                            customerMe.setManagerId(String.valueOf(customerEntity.getManagerId()));
                            customerMe.setCreateTime(newdate);
                            customerMe.setPhone(customerEntity.getPhone());
                            customerMe.setManagerPhone(userEntity2.getMobile());
                            Integer sendNum = 0;
                            String customermsg = "感谢您咨询365淘房房博士,根据您的置业需求,我们将安排安家顾问[" + customerEntity.getManagerName() + "],电话[" + userEntity2.getMobile() + "],在您合适的时间给您回电,请注意接听,谢谢支持";
                            smUrl = smUrl + customerEntity.getCityCode() + "/" + "mobileno/" + customerEntity.getPhone();
                            List<NameValuePair> params = new ArrayList<>();
                            params.add(new BasicNameValuePair("msg", customermsg));
                            //发送客户
                            String sendresult = HttpClientUtil.doGet(smUrl, params, null);
                            customerMe.setRequestType("6");
                            if (sendresult != null) {
                                customerMe.setCustomerStatus("1");
                                sendNum++;
                            } else {
                                customerMe.setCustomerStatus("0");
                            }
                            String time = sdf.format(newdate);
                            String managermsg = "";
                            //在保护期内=非第一次IM咨询
                            if (isProtected) {
                                managermsg = "你好,客户[" + customerEntity.getName() + "]再次咨询,咨询时间[" + time + "],请登录全链条后台查看.";
                            } else {
                                managermsg = "你好,你在[" + time + "]有一条新的用户咨询需要处理,用户手机[" + customerEntity.getPhone() + "]请登录全链条后台查看.";
                            }
                            smUrl = smUrl + customerEntity.getCityCode() + "/" + "mobileno/" + userEntity2.getMobile();
                            List<NameValuePair> params2 = new ArrayList<>();
                            params2.add(new BasicNameValuePair("msg", managermsg));
                            String result2 = HttpClientUtil.doGet(smUrl, params2, null);//发送安家顾问
                            if (result2 != null) {
                                customerMe.setManagerStatus("1");
                                sendNum++;
                            } else {
                                customerMe.setManagerStatus("0");
                            }
                            customerMe.setSendNum(sendNum);
                            //日志记录
                            messagemapper.saveMessageLog(customerMe);
                        }
                    }

                }

            }
        }

        customercallbacklogentity.setManagerName(customerEntity.getLastJoinVisitWorker());
        //保存客户回访记录
        customercallbacklogentity.setCustomerId(newcustomerentity.getId());
        customercallbacklogentity.setContent(customerEntity.getLastJoinVisitRemark());

        customercallbacklogentity.setCreateTime(lastjoinvisittime);
        customercallbacklogentity.setCreater(customerEntity.getLastJoinVisitWorker());
        customercallbacklog.saveCallBackLog(customercallbacklogentity);

        restObject.setEntity(customerEntity);
        return restObject;
    }

    private static int differentDaysByDate(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;

    }

    /**
     * 非客户转移-处理合并最新回访时间
     *
     * @param currentCustomer
     * @return
     */
    private 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;
    }

    /**
     * 客户转移-处理合并客户最近回访时间
     *
     * @param currentCustomer
     * @param
     * @return
     */
    public CustomerEntity handleCustomerMerge(CustomerEntity currentCustomer, Date lastjoinvisittime) {
        //先去查询该客户的所有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 && lastjoinvisittime.before(callbacklist.get(0).getCreateTime())) {
                currentCustomer.setLastCallTime(callbacklist.get(0).getCreateTime());
            } else {
                currentCustomer.setLastCallTime(lastjoinvisittime);
            }
        }
        return currentCustomer;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @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 + "参数为空!");
            }
        }
    }
}
