/**
 * Description: 客户项目信息WS接口
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-15 下午 15:36:18
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-15   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.interfaces.impl;

import com.house365.beans.entity.*;
import com.house365.beans.system.DomainObject;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.beans.request.CustomerProjectListRequest;
import com.house365.ws.beans.request.CustomerProjectRequest;
import com.house365.ws.beans.response.CustomerProjectListResponse;
import com.house365.ws.beans.response.CustomerProjectResponse;
import com.house365.ws.beans.response.MapListResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.dao.mapper.*;
import com.house365.ws.interfaces.server.ICustomerProject;
import com.house365.ws.interfaces.server.IMarketCustomer;
import com.house365.ws.service.interfaces.*;
import com.house365.ws.system.ReturnResult;
import com.house365.ws.util.Constant;
import com.house365.ws.util.HttpUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
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 org.springframework.transaction.interceptor.TransactionAspectSupport;

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

import static com.house365.beans.common.MessageTypeEnum.UPDATECUSTOMERSTATUS;


/**
 * 客户项目信息WS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-15
 * @see
 * @since 1.0
 */
@Service("customerProject")
public class CustomerProjectImpl implements ICustomerProject {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CustomerProjectImpl.class);

    /**
     * 客户项目信息服务对象
     */
    @Autowired
    private ICustomerProjectService<CustomerProjectEntity> customerProjectService;
    @Autowired
    private ICustomerStatusLogService customerStatusLogService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IHgsCacheUtil hgsCacheUtil;
    @Autowired
    private IMarketCustomer marketCustomerService;

    @Autowired
    private CustomerProjectMapper customerProjectMapper;
    @Autowired
    private CustomerStatusLogMapper logMapper;
    @Autowired
    private CustomerApproximateMapper customerapproximatemapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectUserMapper projectUserMapper;

    /**
     * 客户项目信息列表查询
     *
     * @param request 客户项目信息列表查询请求
     * @return 客户项目信息列表查询响应
     */
    @Override
    public CustomerProjectListResponse getCustomerProjectList(CustomerProjectListRequest request) {
        CustomerProjectListResponse response = new CustomerProjectListResponse();
        try {
            QueryParams<CustomerProjectEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<CustomerProjectEntity> customerProjects = customerProjectService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(customerProjects);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    @Override
    public List<CustomerProjectEntity> getCustomerProjectList(Map<String, Object> searchMap) {

        return customerapproximatemapper.getCustomerProjectList(searchMap);
    }

    @Override
    public List<CustomerProjectEntity> getCustomerProjectInfo(Map<String, Object> searchMap) {
        return customerProjectMapper.getCustomerProjectInfo(searchMap);
    }

    @Override
    public int queryPlatCustomerStatus(Map<String, Object> searchMap) {
        return customerProjectMapper.queryPlatCustomerStatus(searchMap);
    }

    @Override
    public int getCount(CustomerProjectListRequest request) {
        QueryParams<CustomerProjectEntity> queryParams = new QueryParams<>(request.getSearchParams());
        queryParams.setPaging(request.getPaging());
        queryParams.setOrderColumn(request.getOrderColumn());
        queryParams.setOrderMode(request.getOrderMode());
        return 0;
    }

    /**
     * 保存客户项目信息
     *
     * @param request 客户项目信息请求
     * @return 保存客户项目信息响应
     */
    @Override
    public CustomerProjectResponse addCustomerProject(CustomerProjectRequest request) {
        CustomerProjectResponse response = new CustomerProjectResponse();
        try {
            CustomerProjectEntity entity = request.getEntity();
            customerProjectService.save(entity);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 删除客户项目信息通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除客户项目信息响应
     */
    @Override
    public CustomerProjectResponse deleteCustomerProjectById(Integer id) {
        CustomerProjectResponse response = new CustomerProjectResponse();
        try {
            customerProjectService.delete(id);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改客户项目信息
     *
     * @param request 修改客户项目信息请求
     * @return 修改客户项目信息响应
     */
    @Override
    public CustomerProjectResponse updateCustomerProject(CustomerProjectRequest request) {
        CustomerProjectResponse response = new CustomerProjectResponse();
        try {
            customerProjectService.update(request.getEntity());
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 通过ID获取客户项目信息
     *
     * @param id 唯一标识
     * @return 通过ID获取客户项目信息响应
     */
    @Override
    public CustomerProjectResponse getCustomerProjectById(Integer id) {
        CustomerProjectResponse response = new CustomerProjectResponse();
        try {
            CustomerProjectEntity entity = customerProjectService.getById(id);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 变更客户项目状态
     *
     * @param id     id
     * @param oper   操作人
     * @param status
     * @param remark
     */
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public CustomerProjectResponse changeStatus(Integer id, String oper, Integer status, String remark, String occurTime) throws Exception {
        CustomerProjectResponse response = new CustomerProjectResponse();
        CustomerProjectEntity entity = customerProjectService.getById(id);
        if (entity.getIsRepeat() == 1) {
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage("该客户为重客，无法维护");
            return response;
        }

        //查询该客户回访记录，无到访时不让变更
        Map<String, Object> map = new HashMap<>(10);
        map.put("customerId", entity.getCustomerId());
        map.put("toStatusId", 2);
        map.put("projectId", entity.getProjectId());
        List<CustomerStatusLogEntity> list = logMapper.queryByConditions(map);
        if (CollectionUtils.isEmpty(list) && status != 2) {
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage("请先添加到访状态");
            return response;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date occurtime = sdf.parse(occurTime);
        //判断发生时间要大于前面状态的时间(约看时间不算)
        map.put("toStatusId", status);
        List<CustomerStatusLogEntity> newList = logMapper.queryByStatus(map);
        if (CollectionUtils.isNotEmpty(newList)) {
            Date time;
            if (status == 2) {
                time = null;
            } else {
                time = newList.get(0).getOccurTime();
            }
            if (time != null && occurtime.before(time)) {
                response.setResultCode(ReturnResult.FAIL.getResultCode());
                response.setResultMessage("发生时间不能小于前一状态");
                return response;
            }
        }

        entity.setOccurTime(occurtime);
        Integer oldStatus = entity.getStatus();
        if (oldStatus != null) {

            //状态不变，不更新客户项目状态纪录，添加状态日志。 统计时应过滤重复数据。 如果是到访 更新到访次数
            Integer statisticFlag = (oldStatus.compareTo(status) != 0) ? 1 : 0;

            //同一个项目 同一个客户 同一个状态 同一个置业顾问 状态变更 标记是否统计为否
            customerStatusLogService.addStatusLogWithProject(entity.getCustomerId(), oldStatus, status, remark, oper, occurtime,
                    entity.getProjectId(), entity.getIsRepeat(),
                    statisticFlag);
            if (oldStatus.compareTo(status) != 0) {
                entity.setStatus(status);
                entity.setUpdateTime(new Date());
                entity.setUpdater(oper);
                entity.setLastChangeStatusTime(new Date());
            }

            if (Constant.CustomerStatusEnum.VISITED.getStatus() == status) {
                entity.setVisitTime((entity.getVisitTime() == null ? 0 : entity.getVisitTime()) + 1);
                marketCustomerService.addVisitCount(entity.getCustomerId());
            }

            if (Constant.CustomerStatusEnum.BUY.getStatus() == status) {
                marketCustomerService.addBuyCount(entity.getCustomerId());
            }
            customerProjectService.update(entity);
            //到访及之后的状态，检查同一楼盘相同手机号纪录置为重客
            if (status.compareTo(Constant.CustomerStatusEnum.VISITED.getStatus()) >= 0) {
                setRepeat(entity.getCustomerPhone(), entity.getProjectId(), entity.getId(), oper, occurtime);
            }

            //call CRM
            final CustomerEntity customerEntity = (CustomerEntity) customerService.getById(entity.getCustomerId());
            final ProjectEntity projectEntity = (ProjectEntity) projectService.getById(entity.getProjectId());
            final CustomerProjectEntity cpe = entity;

            String occurtimeToCrm = String.valueOf(sdf.parse(occurTime).getTime() / 1000);

            cpe.setOccurTimeToCrm(Long.valueOf(occurtimeToCrm));

            ExecutorService executor = Executors.newCachedThreadPool();
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String result = customerProjectService.postToCRM(cpe, new Date(), projectEntity, customerEntity);
                        logger.info("call CRM change customer status result:{}", result);
                    } catch (java.io.IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            });

            if (customerEntity.getManagerId() != null) {
                DomainObject o = userService.getById(customerEntity.getManagerId());
                if (o != null) {
                    String cStatus = String.valueOf(status);
                    if ("1".equalsIgnoreCase(cStatus)) {
                        cStatus = "约看";
                    } else if ("2".equalsIgnoreCase(cStatus)) {
                        cStatus = "到访";
                        customerEntity.setLastVisitTime(new Date());
                        hgsCacheUtil.delUserSummary(customerEntity.getManagerId());
                        customerService.update(customerEntity);
                    } else if ("3".equalsIgnoreCase(cStatus)) {
                        cStatus = "认筹";
                    } else if ("4".equalsIgnoreCase(cStatus)) {
                        cStatus = "认购";
                    } else if ("5".equalsIgnoreCase(cStatus)) {
                        cStatus = "签约";
                    } else if ("6".equalsIgnoreCase(cStatus)) {
                        cStatus = "退房";
                    } else if ("0".equalsIgnoreCase(cStatus)) {
                        cStatus = "未约看";
                    }

                    Map<String, String> param = new HashMap<>();
                    param.put("customerName", customerEntity.getName());
                    param.put("customerProjectId", String.valueOf(id));
                    param.put("toStatus", cStatus);
                    UserEntity user = (UserEntity) o;
                    if (oldStatus.compareTo(status) != 0) {
                        customerService.sendMessageToWechat(UPDATECUSTOMERSTATUS, String.valueOf(user.getId()), param);
                    }
                }
            }

        } else {
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage("状态参数无效");
            return response;
        }

        response.setEntity(entity);
        response.setResultCode(ReturnResult.SUCCESS.getResultCode());
        response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        return response;
    }

    /**
     * 同一楼盘相同约看手机号变更为到访及以后状态，其他约看纪录设置为重客
     *
     * @param phone
     * @param pid
     * @param excludeId
     */
    private void setRepeat(String phone, Integer pid, Integer excludeId, String oper, Date occurtime) throws Exception {
        Page page = new Page(Integer.MAX_VALUE);
        QueryParams queryParams = new QueryParams();
        Map<String, Object> searchMap = new HashMap<>(10);
        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 (CollectionUtils.isNotEmpty(cpes)) {
            for (CustomerProjectEntity cpe : cpes) {
                cpe.setIsRepeat(1);
                customerProjectService.update(cpe);
                //重客 不参与统计
                customerStatusLogService.addStatusLogWithProject(cpe.getCustomerId(), cpe.getStatus(), cpe.getStatus(),
                        remark, oper, occurtime, cpe.getProjectId(), 1, 0);
            }
        }

    }

    @Override
    public int checkRepeat(String phone, String pid) {
        return customerProjectService.checkRepeat(phone, pid);
    }

    @Override
    public void updateProjectNameAndCode(Integer id, String name, String code) {
        Map<String, Object> map = new HashMap<>(10);
        map.put("projectId", id);
        map.put("projectName", name);
        map.put("contract", code);
        map.put("updateTime", new Date());
        customerProjectMapper.updateNameAndCode(map);
    }

    @Override
    public List<CustomerProjectEntity> queryList(Map<String, Object> map) {
        List<CustomerProjectEntity> list = customerProjectMapper.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        return Collections.emptyList();
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public CustomerProjectResponse changeStatusNew(Integer id, String oper, Integer status, String remark, String occurTime) throws Exception {
        CustomerProjectResponse response = new CustomerProjectResponse();
        CustomerProjectEntity entity = customerProjectService.getById(id);
        //判断状态为约看时且是接口调用，不做变更
        if (entity.getStatus() == 1) {
            String reason = "无到访，不同步经管最新状态";
            saveLog(entity, reason);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage("无到访，不同步经管最新状态");
            return response;
        }
        //查询该客户回访记录，无到访时不让变更
        Map<String, Object> map = new HashMap<>(10);
        map.put("customerId", entity.getCustomerId());
        map.put("toStatusId", 2);
        map.put("projectId", entity.getProjectId());
        List<CustomerStatusLogEntity> list = logMapper.queryByConditions(map);
        if (CollectionUtils.isEmpty(list)) {
            String reason = "无到访，不同步经管最新状态";
            saveLog(entity, reason);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage("无到访，不同步经管最新状态");
            return response;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date occurtime = sdf.parse(occurTime);
        //判断发生时间要大于前面状态的时间
        map.put("toStatusId", status);
        List<CustomerStatusLogEntity> newList = logMapper.queryByStatus(map);
        if (CollectionUtils.isNotEmpty(newList)) {
            Date time;
            if (status == 2) {
                time = null;
            } else {
                time = newList.get(0).getOccurTime();
            }
            if (time != null && occurtime.before(time)) {
                String reason = "发生时间小于前一状态，不同步经管最新状态";
                saveLog(entity, reason);
                response.setResultCode(ReturnResult.FAIL.getResultCode());
                response.setResultMessage("发生时间小于前一状态，不同步经管最新状态");
                return response;
            }
        }

        entity.setOccurTime(occurtime);
        Integer oldStatus = entity.getStatus();
        if (oldStatus != null) {

            //状态不变，不更新客户项目状态纪录，添加状态日志。 统计时应过滤重复数据。 如果是到访 更新到访次数
            Integer statisticFlag = (oldStatus.compareTo(status) != 0) ? 1 : 0;

            //同一个项目 同一个客户 同一个状态 同一个置业顾问 状态变更 标记是否统计为否
            customerStatusLogService.addStatusLogWithProject(entity.getCustomerId(), oldStatus, status, remark, oper, occurtime,
                    entity.getProjectId(), entity.getIsRepeat(),
                    statisticFlag);
            if (oldStatus.compareTo(status) != 0) {
                entity.setStatus(status);
                entity.setUpdateTime(new Date());
                entity.setUpdater(oper);
                entity.setLastChangeStatusTime(new Date());
            }

            if (Constant.CustomerStatusEnum.VISITED.getStatus() == status) {
                entity.setVisitTime((entity.getVisitTime() == null ? 0 : entity.getVisitTime()) + 1);
                marketCustomerService.addVisitCount(entity.getCustomerId());
            }

            if (Constant.CustomerStatusEnum.BUY.getStatus() == status) {
                marketCustomerService.addBuyCount(entity.getCustomerId());
            }
            customerProjectService.update(entity);
            //到访及之后的状态，检查同一楼盘相同手机号纪录置为重客
            if (status.compareTo(Constant.CustomerStatusEnum.VISITED.getStatus()) >= 0) {
                setRepeat(entity.getCustomerPhone(), entity.getProjectId(), entity.getId(), oper, occurtime);
            }

            //call CRM
            final CustomerEntity customerEntity = (CustomerEntity) customerService.getById(entity.getCustomerId());
            final ProjectEntity projectEntity = (ProjectEntity) projectService.getById(entity.getProjectId());
            final CustomerProjectEntity cpe = entity;

            String occurtimeToCrm = String.valueOf(sdf.parse(occurTime).getTime() / 1000);

            cpe.setOccurTimeToCrm(Long.valueOf(occurtimeToCrm));

            ExecutorService executor = Executors.newCachedThreadPool();
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String result = customerProjectService.postToCRM(cpe, new Date(), projectEntity, customerEntity);
                        logger.info("call CRM change customer status result:{}", result);
                    } catch (java.io.IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            });

            if (customerEntity.getManagerId() != null) {
                DomainObject o = userService.getById(customerEntity.getManagerId());
                if (o != null) {
                    String cStatus = String.valueOf(status);
                    if ("1".equalsIgnoreCase(cStatus)) {
                        cStatus = "约看";
                    } else if ("2".equalsIgnoreCase(cStatus)) {
                        cStatus = "到访";
                        customerEntity.setLastVisitTime(new Date());
                        hgsCacheUtil.delUserSummary(customerEntity.getManagerId());
                        customerService.update(customerEntity);
                    } else if ("3".equalsIgnoreCase(cStatus)) {
                        cStatus = "认筹";
                    } else if ("4".equalsIgnoreCase(cStatus)) {
                        cStatus = "认购";
                    } else if ("5".equalsIgnoreCase(cStatus)) {
                        cStatus = "签约";
                    } else if ("6".equalsIgnoreCase(cStatus)) {
                        cStatus = "退房";
                    } else if ("0".equalsIgnoreCase(cStatus)) {
                        cStatus = "未约看";
                    }

                    Map<String, String> param = new HashMap<>();
                    param.put("customerName", customerEntity.getName());
                    param.put("customerProjectId", String.valueOf(id));
                    param.put("toStatus", cStatus);
                    UserEntity user = (UserEntity) o;
                    if (oldStatus.compareTo(status) != 0) {
                        customerService.sendMessageToWechat(UPDATECUSTOMERSTATUS, String.valueOf(user.getId()), param);
                    }
                }
            }

        } else {
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage("状态参数无效");
            return response;
        }

        response.setEntity(entity);
        response.setResultCode(ReturnResult.SUCCESS.getResultCode());
        response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        return response;
    }

    private void saveLog(CustomerProjectEntity entity, String reason) {
        try {
            CustomerStatusLogEntity logEntity = new CustomerStatusLogEntity();
            logEntity.setFromStatusId(0);
            logEntity.setFromStatusName("");
            logEntity.setToStatusId(0);
            logEntity.setToStatusName("");
            logEntity.setCreater("经管系统");
            logEntity.setCreateTime(new Date());
            logEntity.setCustomerId(entity.getCustomerId());
            logEntity.setProjectId(entity.getProjectId());
            logEntity.setIsRepeat(entity.getIsRepeat());
            logEntity.setCustomerManagerId(0);
            logEntity.setCustomerManagerName("");
            logEntity.setRemark(reason);
            logEntity.setNonStatistic(0);
            logEntity.setOccurTime(new Date());
            logEntity.setIsDelete(1);
            logMapper.save(logEntity);
        } catch (Exception e) {
            logger.error("添加经管同步失败记录错误", e);
        }
    }

    @Override
    @Transactional
    public HResult setMajorCustomer(int id, String userName) {
        HResult result = new HResult();
        try {
            CustomerProjectEntity entity = customerProjectMapper.queryById(id);
            //重客变为主客，并添加日志
            Map<String, Object> oldUpdateMap = new HashMap<>(10);
            oldUpdateMap.put("isRepeat", 0);
            oldUpdateMap.put("id", id);
            oldUpdateMap.put("updateTime", new Date());
            customerProjectMapper.updateCustomerStatus(oldUpdateMap);
            saveStatusLog(entity.getCustomerId(), entity.getProjectId(), 0, userName, "判为主客");
            //设置主客，同时把开始的主客设为约看状态，同时添加两条日志
            Map<String, Object> map = new HashMap<>(5);
            map.put("customerPhone", entity.getCustomerPhone());
            map.put("customerId", entity.getCustomerId());
            map.put("projectId", entity.getProjectId());
            map.put("isRepeat", 0);
            List<CustomerProjectEntity> list = customerProjectMapper.queryByConditions(map);
            if (CollectionUtils.isNotEmpty(list)) {
                for (CustomerProjectEntity c : list) {
                    //设置为重客，且更新客户状态至约看，同时更新客户状态日志表
                    int majorId = c.getId();
                    Map<String, Object> updateMap = new HashMap<>(10);
                    updateMap.put("isRepeat", 1);
                    updateMap.put("id", majorId);
                    updateMap.put("status", 1);
                    updateMap.put("updateTime", new Date());
                    customerProjectMapper.updateCustomerStatus(updateMap);
                    int projectId = c.getProjectId();
                    Map<String, Object> logMap = new HashMap<>(10);
                    logMap.put("customerId", c.getCustomerId());
                    logMap.put("projectId", projectId);
                    logMapper.updateRepeatStatus(logMap);
                    logMapper.updateMajorCustomer(logMap);
                    //添加设置重客日志
                    saveStatusLog(c.getCustomerId(), c.getProjectId(), 1, userName, "判为重客");
                }
            }
        } catch (Exception e) {
            logger.error("设置主客失败", e);
            result.setStatus(-1);
            result.setErrorMessage("设置主客失败");
        }
        return result;
    }

    private void saveStatusLog(int customerId, int projectId, int isRepeat, String userName, String remark) {
        try {
            CustomerStatusLogEntity logEntity = new CustomerStatusLogEntity();
            logEntity.setFromStatusId(0);
            logEntity.setFromStatusName("");
            //7表示设置主客的日志，8为设置成重客，4.1版本新增
            logEntity.setToStatusId(0);
            logEntity.setToStatusName("人工判重");
            logEntity.setCreater(userName);
            logEntity.setCreateTime(new Date());
            logEntity.setCustomerId(customerId);
            logEntity.setProjectId(projectId);
            logEntity.setIsRepeat(isRepeat);
            logEntity.setCustomerManagerId(0);
            logEntity.setCustomerManagerName("");
            logEntity.setRemark(remark);
            logEntity.setNonStatistic(0);
            String time = "2014-01-01 00:00:00";
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date time1 = format.parse(time);
            logEntity.setOccurTime(time1);
            logEntity.setIsDelete(0);
            logMapper.save(logEntity);
        } catch (Exception e) {
            logger.error("添加设置主客日志失败", e);
        }
    }

    @Override
    public MapListResponse list(CustomerProjectListRequest request, String city, String startTime, String endTime) {
        MapListResponse response = new MapListResponse();
        try {
            Map<String, Object> map = new HashMap<>(10);
            Map<String, Object> searchParams = request.getSearchParams();
            int start = 20 * (request.getPaging().getCurrentPage() - 1);
            map.put("city", city);
            map.put("start", start);
            map.put("limit", 20);
            map.put("name", searchParams.get("name"));
            map.put("phone", searchParams.get("phone"));
            map.put("projectName", searchParams.get("projectName"));
            map.put("isMatch", searchParams.get("isMatch"));
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            int dateType = 0;
            if (null != searchParams.get("dateType")) {
                dateType = Integer.parseInt(searchParams.get("dateType").toString());
            }
            map.put("dateType", dateType);
            List<Map<String, Object>> list = customerProjectMapper.queryReport(map);
            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> m : list) {
                    if (null != m.get("projectId")) {
                        int projectId = Integer.parseInt(m.get("projectId").toString());
                        Map<String, Object> searchMap = new HashMap<>(5);
                        searchMap.put("projectId", projectId);
                        List<ProjectUserEntity> projectUserList = projectUserMapper.queryByConditions(searchMap);
                        if (CollectionUtils.isNotEmpty(projectUserList)) {
                            StringBuilder builder = new StringBuilder();
                            for (ProjectUserEntity p : projectUserList) {
                                int userId = p.getUserId();
                                UserEntity user = userMapper.getById(userId);
                                if (null != user && StringUtils.isNotBlank(user.getRealName())) {
                                    builder.append(user.getRealName()).append(",");
                                }
                            }
                            String residentUserName = builder.toString();
                            if(residentUserName.contains(",")) {
                                residentUserName = residentUserName.substring(0, residentUserName.lastIndexOf(","));
                            }
                            m.put("residentUserName", residentUserName);
                        } else {
                            m.put("residentUserName", "");
                        }
                    }
//                    if (null != m.get("residentUserId")) {
//                        int userId = Integer.parseInt(m.get("residentUserId").toString());
//                        UserEntity user = userMapper.getById(userId);
//                        if (null != user && StringUtils.isNotBlank(user.getRealName())) {
//                            m.put("residentUserName", user.getRealName());
//                        }
//                    }
                }
            }
            int count = customerProjectMapper.queryReportCount(map);
            request.getPaging().setRecords(count);
            response.setPaging(request.getPaging());
            response.setObjectList(list);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public HResult updateJgData(List<Integer> list, int type, String name) {
        HResult result = new HResult();
        try {
            long startTime1 = System.currentTimeMillis();
            System.out.println("-------------进入updateJgData方法---------------： " + (startTime1) + "ms");
            if (CollectionUtils.isNotEmpty(list)) {
                JSONArray jsonArray = new JSONArray();
                Map<String, Object> map = new HashMap<>(5);
                map.put("projectIdList", list);
                map.put("isVisit", 1);
                map.put("isRepeat", 0);
                List<CustomerProjectEntity> cpList1 = customerProjectMapper.queryByConditions(map);

                if (CollectionUtils.isNotEmpty(cpList1)) {
                    for (CustomerProjectEntity cp : cpList1) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("contract_no", cp.getContract());
                        jsonObject.put("phone", cp.getCustomerPhone());
                        jsonArray.add(jsonObject);
                    }
                }
                System.out.println("-------------updateJgData查询数据数目---------------： " + jsonArray.size());
                long endTime1 = System.currentTimeMillis();
                System.out.println("-------------updateJgData查询数据结束---------------： " + (endTime1 - startTime1) + "ms");
                if (jsonArray.size() > 0) {
                    //调用经管接口
                    long startTime = System.currentTimeMillis();
                    System.out.println("-------------进入调用经管接口---------------： " + (startTime) + "ms");
                    String url = MemoryPropertyPlaceholderConfigurer.getContextProperty("projects.server.url");
                    url += "?s=/Apiqlt/getmemberstatus";
                    String data = HttpUtil.postWithJsonNew(jsonArray, url);
                    long endTime = System.currentTimeMillis();
                    System.out.println("-------------同步经管调用接口运行时间---------------： " + (endTime - startTime) + "ms");
                    JSONObject json = JSONObject.fromObject(data);
                    String code = json.get("result").toString();
                    if ("1".equals(code)) {
                        final JSONArray array = (JSONArray) json.get("data");
                        System.out.println("-------------updateJgData经管返回数目---------------： " + array.size());
                        final Date date = new Date();
                        final int logType = type;
                        final String userName = name;
                        ExecutorService executor = Executors.newCachedThreadPool();
                        executor.execute(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < array.size(); i++) {
                                    try {
                                        JSONObject obj = array.getJSONObject(i);
                                        String contractNo = obj.get("CONTRACT_NO").toString();
                                        String phone = obj.get("PHONE").toString();
                                        int jgStatus = Integer.parseInt(obj.get("CARDSTATUS").toString());
                                        String buyTime = obj.get("SUBSCRIBETIME").toString();
                                        String signTime = obj.get("SIGNTIME").toString();
                                        String backTime = obj.get("BACKTIME").toString();
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                        Map<String, Object> searchMap = new HashMap<>(10);
                                        searchMap.put("contract", contractNo);
                                        searchMap.put("customerPhone", phone);
                                        searchMap.put("isRepeat", 0);
                                        searchMap.put("limit", 1);
                                        if (jgStatus == 3) {
                                            continue;
                                        }
                                        List<CustomerProjectEntity> cpList = customerProjectMapper.queryByConditions(searchMap);
                                        if (CollectionUtils.isNotEmpty(cpList)) {
                                            CustomerProjectEntity entity = cpList.get(0);
                                            int status = entity.getStatus();
                                            //全链条状态小于经管时做同步操作
                                            if (status < jgStatus) {
                                                entity.setStatus(jgStatus);
                                                entity.setUpdater("经管系统");
                                                entity.setUpdateTime(date);
                                                Date occurTime = date;
                                                //同时更新customer_status_log表数据
                                                int customerId = entity.getCustomerId();
                                                Map<String, Object> queryMap = new HashMap<>(10);
                                                queryMap.put("customerId", customerId);
                                                queryMap.put("projectId", entity.getProjectId());
                                                if (jgStatus == 4) {
                                                    occurTime = sdf.parse(buyTime);
                                                } else if (jgStatus == 5) {
                                                    occurTime = sdf.parse(signTime);
                                                    Date oldOccurTime = sdf.parse(buyTime);
                                                    addOldLog(queryMap, oldOccurTime, 4, entity, logType, userName);
                                                } else if (jgStatus == 6) {
                                                    occurTime = sdf.parse(backTime);
                                                    Date oldOccurTime = sdf.parse(signTime);
                                                    addOldLog(queryMap, oldOccurTime, 5, entity, logType, userName);
                                                    Date oldOccurTimeTwo = sdf.parse(buyTime);
                                                    addOldLog(queryMap, oldOccurTimeTwo, 4, entity, logType, userName);
                                                }
                                                String reason;
                                                if (logType == 1) {
                                                    reason = "主动同步经管";
                                                } else {
                                                    reason = "自动同步经管";
                                                }
                                                saveLogNew(entity, reason, jgStatus, occurTime, userName);
                                                entity.setLastChangeStatusTime(occurTime);
                                                customerProjectService.update(entity);
                                            }
                                        }
                                    } catch (Exception e) {
                                        logger.error("同步经管状态失败", e);
                                    }
                                }
                            }
                        });
                    } else {
                        result.setStatus(500);
                        result.setErrorMessage("查询经管信息接口失败");
                        return result;
                    }
                }
            }
        } catch (Exception e) {
            result.setStatus(500);
            result.setErrorMessage("同步经管状态失败");
            logger.error("同步经管状态失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    private void addOldLog(Map<String, Object> queryMap, Date occurTime, int oldStatus, CustomerProjectEntity entity, int type, String userName) {
        queryMap.put("toStatusId", oldStatus);
        List<CustomerStatusLogEntity> logList = logMapper.queryByConditions(queryMap);
        if (CollectionUtils.isEmpty(logList)) {
            String reason;
            if (type == 1) {
                reason = "主动同步经管";
            } else {
                reason = "自动同步经管";
            }
            saveLogNew(entity, reason, oldStatus, occurTime, userName);
        }
    }

    private void saveLogNew(CustomerProjectEntity entity, String reason, int jgStatus, Date time, String userName) {
        CustomerStatusLogEntity logEntity = new CustomerStatusLogEntity();
        logEntity.setFromStatusId(jgStatus - 1);
        String fromName;
        String toName;
        if (jgStatus == 4) {
            fromName = "认筹";
            toName = "认购";
        } else if (jgStatus == 5) {
            fromName = "认购";
            toName = "签约";
        } else {
            fromName = "签约";
            toName = "退房";
        }
        logEntity.setFromStatusName(fromName);
        logEntity.setToStatusId(jgStatus);
        logEntity.setToStatusName(toName);

        logEntity.setCreater(userName);
        logEntity.setCreateTime(new Date());
        logEntity.setCustomerId(entity.getCustomerId());
        logEntity.setProjectId(entity.getProjectId());
        logEntity.setIsRepeat(entity.getIsRepeat());
        CustomerEntity customer = (CustomerEntity) customerService.getById(entity.getCustomerId());
        logEntity.setCustomerManagerId(customer.getManagerId());
        logEntity.setCustomerManagerName(customer.getManagerName());
        logEntity.setRemark(reason);
        logEntity.setNonStatistic(0);
        logEntity.setOccurTime(time);
        logEntity.setIsDelete(0);
        logMapper.save(logEntity);
    }

    /**
     * 以下均为自动生成
     */

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

    @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() {
    }
}
