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

import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CustomerListVO;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.cached.RedisUtilsInterface;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.*;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.*;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

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

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入客户信息WS实现
     */
    @Autowired
    private ICustomer customer;
    @Autowired
    private ICustomerProject customerProject;
    @Autowired
    private ICustomerUser customerUser;
    @Autowired
    private IDepartment department;
    @Autowired
    private IUser user;
    @Autowired
    private ICustomerCallbackLog customerCallbackLog;
    @Autowired
    private IDictionary dictionary;
    @Autowired
    private RedisUtilsInterface redisUtil;
    @Autowired
    private ICityCallInterface callInterface;
    @Autowired
    private ICustomerCallbackTemplate customerCallbackTemplate;
    @Autowired
    private IPropertyReportInterface reportInterface;

    /**
     * 置业顾问视图
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "managerView", method = RequestMethod.GET)
    public String managerView(Integer number, Model model, HttpServletRequest request) {
        return getAutoUrl();
    }

    /**
     * 我的客户统计栏目
     *
     * @param number
     * @param pageSize
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "customerCount", method = RequestMethod.GET)
    public String customerCount(Integer number, Integer pageSize, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(pageSize == null ? 20 : pageSize);
        if (null != number) {
            page.setCurrentPage(number);
        }

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

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        String managerId = request.getParameter("managerId");
        //自己和子部门数据
        if (StringUtils.isBlank(managerId)) {
            searchParams.put("EQ_userId", userEntity.getId());
        } else {
            searchParams.put("EQ_managerId", managerId);
        }
        searchParams.put("EQ_cityCode", cityCode);
        searchParams.put("EQ_isDelete", "0");
        //共多少条数据，今日新增多少条
        House365RestResponse<Map<String, Object>> seaSummary = customer.getSummarySimple(String.valueOf(userEntity.getId()));
        model.addAttribute("summary", seaSummary.getData().getEntity());
        //TODO: 统计数据可以整理为视图或一个sql
        Map<String, Object> callSearchParams = new HashMap<>(10);
        callSearchParams.putAll(searchParams);
        filterParams(callSearchParams);
        callSearchParams.put("EQ_isDelete", "0");
        callSearchParams.put("EQ_totalCall", "1");
        CustomerListRequest totalCount = new CustomerListRequest();
        totalCount.setPaging(new Page(Integer.MAX_VALUE));
        totalCount.setSearchParams(callSearchParams);
        Date yesterday = DateTimeUtils.getDaysAgo(new Date(), 1);
        Date today = DateTimeUtils.getToday(new Date());

        //计算昨日数据
        callSearchParams.put("GTE_callTimeStart", yesterday);
        callSearchParams.put("LT_callTimeEnd", today);
        //电话回访：展示昨日的，待回访列表中被电话回访过且正常进入全链条的数据总量
        String yesterdayCallKey = "customer:yesterdayCall:" + DateTimeUtils.parseDate(yesterday,
                DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT) + ":" + userEntity.getId() + ":" + cityCode;
        Integer yesterdayCall;

        if (redisUtil.hasKey(yesterdayCallKey)) {
            yesterdayCall = redisUtil.getIntegerByKey(yesterdayCallKey);
        } else {
            yesterdayCall = customer.getTotalCallOptimize(totalCount);
            redisUtil.addKeyVal(yesterdayCallKey, String.valueOf(yesterdayCall));
        }
        callSearchParams.remove("EQ_totalCall");
        callSearchParams.put("EQ_allCall", "1");

        //二次跟进：展示昨日的，全部、新增、已回访、有效、成交、暂缓TAB标签下所有被电话回访过的客户数量，仅添加文字回访的客户不在此计算范围之内

        String yesterdayAllCallKey = "customer:yesterdayAllCall:" + DateTimeUtils.parseDate(yesterday,
                DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT) + ":" + userEntity.getId() + ":" + cityCode;

        Integer yesterdayAllCall;
        if (redisUtil.hasKey(yesterdayAllCallKey)) {
            yesterdayAllCall = redisUtil.getIntegerByKey(yesterdayAllCallKey);
        } else {
            yesterdayAllCall = customer.getTotalCallOptimize(totalCount);
            redisUtil.addKeyVal(yesterdayAllCallKey, String.valueOf(yesterdayAllCall));
        }

        callSearchParams.remove("EQ_allCall");
        callSearchParams.put("EQ_normalCall", "1");
        //普通回访
        String yesterdayNormalCallKey = "customer:yesterdayNormalCallKey:" + DateTimeUtils.parseDate(yesterday,
                DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT) + ":" + userEntity.getId() + ":" + cityCode;
        Integer yesterdayNormalCall;
        if (redisUtil.hasKey(yesterdayNormalCallKey)) {
            yesterdayNormalCall = redisUtil.getIntegerByKey(yesterdayNormalCallKey);
        } else {
            yesterdayNormalCall = customer.getTotalCallOptimize(totalCount);
            redisUtil.addKeyVal(yesterdayNormalCallKey, String.valueOf(yesterdayNormalCall));
        }

        //计算今日数据

        //电话回访：展示今日的，待回访列表中被电话回访过且正常进入全链条的数据总量
        callSearchParams.remove("LT_callTimeEnd");
        callSearchParams.remove("EQ_normalCall");
        callSearchParams.put("EQ_totalCall", "1");
        callSearchParams.put("GTE_callTimeStart", today);
        Integer todayCall = customer.getTotalCallOptimize(totalCount);

        //二次跟进 展示今日的，全部、新增、已回访、有效、成交、暂缓TAB标签下所有被电话回访过的客户数量，仅添加文字回访的客户不在此计算范围之内
        callSearchParams.remove("EQ_totalCall");
        callSearchParams.put("EQ_allCall", "1");
        Integer todayAllCall = customer.getTotalCallOptimize(totalCount);

        callSearchParams.remove("EQ_allCall");
        callSearchParams.put("EQ_normalCall", "1");
        //普通回访
        Integer todaynormalCall = customer.getTotalCallOptimize(totalCount);

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

        filterParams(abandonSearchParams);
        if (abandonSearchParams.containsKey("EQ_typeFilter")) {
            abandonSearchParams.remove("EQ_typeFilter");
        }
        if (abandonSearchParams.containsKey("EQ_isDelete")) {
            abandonSearchParams.remove("EQ_isDelete");
        }
        abandonSearchParams.put("GTE_abandonTimeStart", yesterday);
        abandonSearchParams.put("LT_abandonTimeEnd", today);
        abandonSearchParams.put("EQ_totalAbandon", "1");
        CustomerListRequest totalAbandonRequest = new CustomerListRequest();
        totalAbandonRequest.setPaging(new Page(Integer.MAX_VALUE));
        totalAbandonRequest.setSearchParams(abandonSearchParams);
        //展示今日、昨日两天的，待回访列表中被放弃过的客户数量总和
        Integer yesterdayTotalAbandon = customer.getTotalAbandon(totalAbandonRequest);

        abandonSearchParams.put("GTE_abandonTimeStart", today);
        abandonSearchParams.remove("LT_abandonTimeEnd");
        Integer todayTotalAbandon = customer.getTotalAbandon(totalAbandonRequest);

        model.addAttribute("yesterdayTotalCall", yesterdayCall);
        model.addAttribute("yesterdayAllCall", yesterdayAllCall);
        model.addAttribute("yesterdayNormalCall", yesterdayNormalCall);
        model.addAttribute("todayTotalCall", todayCall);
        model.addAttribute("todayAllCall", todayAllCall);
        model.addAttribute("todaynormalCall", todaynormalCall);

        model.addAttribute("yesterdayTotalAbandon", yesterdayTotalAbandon);
        model.addAttribute("todayTotalAbandon", todayTotalAbandon);

        return getAutoUrl();
    }

    /**
     * 查询客户信息
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "myCustomerNew", method = RequestMethod.GET)
    public String myCustomerNew(String labelId, Integer number, Integer pageSize, Model model, HttpServletRequest request) {

        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(pageSize == null ? 100 : pageSize);
        if (null != number) {
            page.setCurrentPage(number);
        }

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

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        model.addAttribute("city", cityCode);
        //判断是否有城市外呼配置
        if (org.apache.commons.lang3.StringUtils.isNotBlank(cityCode)) {
            List<CityCallConfig> list = callInterface.queryByCity(cityCode);
            if (CollectionUtils.isNotEmpty(list)) {
                model.addAttribute("hasPhone", 1);
            }
        }

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

        //去除400未跟踪客户
        searchParams.put("EQ_hotline", "0");

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

        // 回访状态
        String isBack = String.valueOf(searchParams.get("EQ_isBack"));
        if ("1".equals(isBack)) {
            // 全部
            searchParams.remove("EQ_isBack");
            searchParams.remove("EQ_isNotBack");
        } else if ("2".equals(isBack)) {
            // 查询有回访记录的数据
            searchParams.remove("EQ_isNotBack");
        } else if ("3".equals(isBack)) {
            // 查询无回访的数据
            searchParams.remove("EQ_isBack");
            searchParams.put("EQ_isNotBack", "3");
        } else if ("4".equals(isBack)) {
            // 3~7天未回访
            searchParams.remove("EQ_isNotBack");
            searchParams.put("EQ_isNotBackFour", "4");
        } else if ("5".equals(isBack)) {
            // 7~14天未回访
            searchParams.remove("EQ_isNotBack");
            searchParams.put("EQ_isNotBackFive", "5");
        } else if ("6".equals(isBack)) {
            // 14天以上未回访
            searchParams.remove("EQ_isNotBack");
            searchParams.put("EQ_isNotBackSix", "6");
        } else if ("7".equals(isBack)) {
            // 30天以上未回访
            searchParams.remove("EQ_isNotBack");
            searchParams.put("EQ_isNotBackSeven", "7");
        } else if ("8".equals(isBack)) {
            // 50天以上未回访
            searchParams.remove("EQ_isNotBack");
            searchParams.put("EQ_isNotBackEight", "8");
        }

        // 星标
        String isStar = String.valueOf(searchParams.get("EQ_isStar"));
        if ("2".equals(isStar)) {
            // 有星标
            searchParams.remove("EQ_isNotStar");
        } else if ("3".equals(isStar)) {
            // 无星标
            searchParams.remove("EQ_isStar");
            searchParams.put("EQ_isNotStar", "3");
        } else {
            searchParams.remove("EQ_isStar");
            searchParams.remove("EQ_isNotStar");
        }

        // 客户类型
        String createSource = String.valueOf(searchParams.get("EQ_createSource"));
        List<String> createSourceList = new ArrayList<>();
        if ("CRM拉取".equals(createSource)) {
            createSourceList.add("CRM拉取");
        } else if ("CRM导入".equals(createSource)) {
            createSourceList.add("CRM导入");
        } else if ("MANUAL".equals(createSource)) {
            createSourceList.add("SYSTEM");
            createSourceList.add("WECHAT");
        } else if ("HOTLINE".equals(createSource)) {
            createSourceList.add("HOTLINE");
        } else if ("IM咨询".equals(createSource)) {
            searchParams.remove("EQ_createSource");
            searchParams.put("EQ_customerSourceType2", "6");
        } else if ("留电".equals(createSource)) {
            searchParams.remove("EQ_createSource");
            searchParams.put("EQ_customerSourceType2", "5");
        } else if ("云迹".equals(createSource)) {
            searchParams.remove("EQ_createSource");
            searchParams.put("EQ_customerSourceType2", "7");
        } else if ("PT".equals(createSource)) {
            searchParams.remove("EQ_createSource");
            searchParams.put("EQ_customerSourceType2", "8");
        }
        if (createSourceList.size() > 0) {
            searchParams.put("IN_createSource", createSourceList);
        }

        //类型过滤
        StringBuilder typeFilter = new StringBuilder();
        String type = request.getParameter("type") == null ? "" : request.getParameter("type");

        switch (type) {
            case "newadd":
                typeFilter.append(
                        "(isWaitCall = 0 or isWaitCall is null) and (select count(*) from customer_callback_log ccl where ccl.customer_id = c.id )= 0 and(select count(*) from customer_status_log csl where csl.customer_id = c.id)= 0");
                searchParams.put("EQ_tabType", "0");
                break;
            case "callback":
                typeFilter.append("(isWaitCall = 0 or isWaitCall is null) and last_call_time is not null");
                searchParams.put("EQ_tabType", "1");
                break;
            case "valid":
                typeFilter.append("(isWaitCall = 0 or isWaitCall is null) and trace_status = 1");
                searchParams.put("EQ_tabType", "2");
                break;
            case "deal":
                typeFilter.append("(isWaitCall = 0 or isWaitCall is null) and (trace_status = 2 or trace_status = 3)");
                searchParams.put("EQ_tabType", "3");
                break;
            case "respite":
                typeFilter.append("(isWaitCall = 0 or isWaitCall is null) and trace_status = 4");
                searchParams.put("EQ_tabType", "4");
                break;
            case "waitCall":
                typeFilter.append("isWaitCall = 1");
                model.addAttribute("addType", "waitCall");
                searchParams.put("EQ_tabType", "5");
                break;
            case "":
                typeFilter.append("(isWaitCall = 0 or isWaitCall is null)");
                searchParams.put("EQ_tabType", "6");
                break;
            case "handover":
                typeFilter.append("(isHandover = 1)");
                searchParams.put("EQ_tabType", "7");
                break;
            case "active":
                typeFilter.append("(is_active = 1)");
                searchParams.put("EQ_tabType", "8");
                break;
            case "cloud":
                searchParams.put("EQ_tabType", "9");
                break;
            default:
                break;
        }

        if (typeFilter.length() != 0) {
            searchParams.put("EQ_typeFilter", typeFilter.toString());
        }

        //统计信息过滤条件
        String summaryType = request.getParameter("summaryType");
        //是否根据customerid过滤，是的话没有customerids会设置为-1
        if (!Strings.isNullOrEmpty(summaryType)) {
            model.addAttribute("summaryType", summaryType);
            searchParams.put("EQ_summaryType" + summaryType, summaryType);
        }

        //时间过滤
        String timePeriod = request.getParameter("timePeriod") == null ? "0" : request.getParameter("timePeriod");
        model.addAttribute("timePeriod", timePeriod);

        // 派工时间
        if (searchParams.containsKey("GTE_bindTimeStart") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
                ("GTE_bindTimeStart")))) {
            searchParams.put("GTE_bindTimeStart", searchParams.get("GTE_bindTimeStart") + " 00:00:00");
        }
        if (searchParams.containsKey("LTE_bindTimeEnd") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
                ("LTE_bindTimeEnd")))) {
            searchParams.put("LTE_bindTimeEnd", searchParams.get("LTE_bindTimeEnd") + " 23:59:59");
        }

        // 报名时间
        if (searchParams.containsKey("GTE_singupTimeStart") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
                ("GTE_singupTimeStart")))) {
            searchParams.put("GTE_singupTimeStart", searchParams.get("GTE_singupTimeStart") + " 00:00:00");
        }
        if (searchParams.containsKey("LTE_singupTimeEnd") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
                ("LTE_singupTimeEnd")))) {
            searchParams.put("LTE_singupTimeEnd", searchParams.get("LTE_singupTimeEnd") + " 23:59:59");
        }

        // 添加时间
        if (searchParams.containsKey("GTE_createTimeStart") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
                ("GTE_createTimeStart")))) {
            searchParams.put("GTE_createTimeStart", searchParams.get("GTE_createTimeStart") + " 00:00:00");
        }
        if (searchParams.containsKey("LTE_createTimeEnd") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
                ("LTE_createTimeEnd")))) {
            searchParams.put("LTE_createTimeEnd", searchParams.get("LTE_createTimeEnd") + " 23:59:59");
        }
        // 初始化进入待回访以外的tab,添加时间为近7天
//        if (!"waitCall".equals(type) && "0".equals(timePeriod)) {
//            Calendar cal = Calendar.getInstance();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            searchParams.put("LTE_createTimeEnd", sdf.format(cal.getTime()) + " 23:59:59");
//            cal.add(Calendar.DATE, -6);
//            searchParams.put("GTE_createTimeStart", sdf.format(cal.getTime()) + " 00:00:00");
//        }

        // 自定义时间
        if (searchParams.containsKey("GTE_customTimeStart") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
                ("GTE_customTimeStart")))) {
            searchParams.put("GTE_customTimeStart", searchParams.get("GTE_customTimeStart") + " 00:00:00");
        }
        if (searchParams.containsKey("LTE_customTimeEnd") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get
                ("LTE_customTimeEnd")))) {
            searchParams.put("LTE_customTimeEnd", searchParams.get("LTE_customTimeEnd") + " 23:59:59");
        }
        // 自定义时间类型
        String customTimeType = String.valueOf(searchParams.get("EQ_customTimeType"));
        if (!Strings.isNullOrEmpty(String.valueOf(searchParams.get("GTE_customTimeStart")))
                || !Strings.isNullOrEmpty(String.valueOf(searchParams.get("LTE_customTimeEnd")))) {
            if ("1".equals(customTimeType)) {
                // 回访时间
                searchParams.put("EQ_customTimeTypeOne", "1");
            } else if ("2".equals(customTimeType)) {
                // 约看时间
                searchParams.put("EQ_customTimeTypeTwo", "1");
            } else if ("3".equals(customTimeType)) {
                // 到访时间
                searchParams.put("EQ_customTimeTypeThree", "1");
            } else if ("4".equals(customTimeType)) {
                // 认筹时间
                searchParams.put("EQ_customTimeTypeFour", "1");
            } else if ("5".equals(customTimeType)) {
                // 认购时间
                searchParams.put("EQ_customTimeTypeFive", "1");
            } else if ("6".equals(customTimeType)) {
                // 签约时间
                searchParams.put("EQ_customTimeTypeSix", "1");
            }
        }

        StringBuilder sortColumn = new StringBuilder();
        //时间排序
        boolean daoxuFlag = false;
        boolean shunxuFlag = false;
        if (searchParams.containsKey("EQ_orderByTime") && !Strings.isNullOrEmpty(String.valueOf(searchParams.get("EQ_orderByTime")))) {
            if (sortColumn.length() != 0) {
                sortColumn.append(",");
            }
            int orderByTime = Integer.parseInt(searchParams.get("EQ_orderByTime").toString());
            if (orderByTime <= 2) {
                // 按添加时间排序
                sortColumn.append("create_time ");
                if (orderByTime < 2) {
                    sortColumn.append("desc");
                }
            } else if (orderByTime <= 4) {
                // 按派工时间排序
                sortColumn.append("bind_time ");
                if (orderByTime < 4) {
                    sortColumn.append("desc");
                }
            } else if (orderByTime <= 6) {
                // 按回访时间排序
                sortColumn.append("last_call_time ");
                if (orderByTime < 6) {
                    sortColumn.append("desc");
                }
            } else if (orderByTime <= 8) {
                // 按倒计时排序
                sortColumn.append("countdown_time ");
                if (orderByTime < 8) {
                    sortColumn.append("desc");
                }
            }
        }

        searchParams.put("EQ_orderBy", sortColumn.toString());

        String managerId = request.getParameter("managerId");
        //自己和子部门数据
        if (StringUtils.isBlank(managerId)) {
            searchParams.put("EQ_userId", userEntity.getId());
        } else {
            searchParams.put("EQ_userId", managerId);
        }
        searchParams.put("EQ_cityCode", cityCode);
        searchParams.put("EQ_isDelete", "0");
        searchParams.put("EQ_manager", userEntity.getId());
        if (labelId != null && !"".equals(labelId)) {
            searchParams.put("EQ_userId", userEntity.getId());
            searchParams.put("EQ_labelId", labelId);
        }
        CustomerListRequest listRequest = new CustomerListRequest();

        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CustomerListResponse response;
        List<MarketingActivityEntity> alist = new ArrayList<>();
        //区分查询待回访
        logger.error("-------------------------1:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if ("waitCall".equalsIgnoreCase(type)) {
            response = customer.getCustomerListFromOld(listRequest);
            if (listRequest.getSearchParams().containsKey("EQ_activeId")) {
                listRequest.getSearchParams().remove("EQ_activeId");
            }
            List<Map<String, Object>> list = customer.getMarketInfo(listRequest);
            for (Map<String, Object> act : list) {
                MarketingActivityEntity ac = new MarketingActivityEntity();
                ac.setName(String.valueOf(act.get("marketActName")));
                ac.setId((Integer) act.get("marketActId"));
                alist.add(ac);
            }
        } else {
            response = customer.getCustomerManagementList4Label(listRequest);
            logger.error("-------------------------2:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }

        model.addAttribute("actList", alist);

        List<CustomerListVO> customers = new ArrayList<>();
        //用户标签
        List<LabelEntity> userLabelList = user.queryUserLabel(userEntity.getId());//标签库中当前用户创建的标签
        if (userLabelList != null && userLabelList.size() > 0) {
            model.addAttribute("hasOwnlabel", "1");
            model.addAttribute("userLabelList", userLabelList);
        } else {
            model.addAttribute("hasOwnlabel", "0");
        }
        if (response != null && response.getObjectList() != null) {
            // 按objectList大小初始化list
            customers = new ArrayList<>(response.getObjectList().size());
            // 只有待回访tab需要计算倒计时
            double retainMinutes = 0.0d;
            if (org.apache.commons.lang3.StringUtils.equals("waitCall", type)) {
                boolean hasCustomerRemoveDaysNocall = false;
                List<DictionaryEntity> lstCityNocall = dictionary.getListByKey("customer.remove.days.nocall");
                for (DictionaryEntity cityNocall : lstCityNocall) {
                    if (org.apache.commons.lang3.StringUtils.equals(departmentEntity.getDescripition(), cityNocall.getCity())) {
                        String dicValue = cityNocall.getDicValue();
                        retainMinutes = Double.valueOf(dicValue) * 60;
                        hasCustomerRemoveDaysNocall = true;
                        model.addAttribute("hasCustomerRemoveDaysNocall", hasCustomerRemoveDaysNocall);
                        break;
                    }
                }
            }
            //星标客户\安家顾问集合
            Map<Integer, String> customerId2UsrIdMap = new HashMap<>(response.getObjectList().size());

            //加载客户标签
            Map<String, Object> labelMap = new HashMap<>(10);
            labelMap.put("createId", userEntity.getId());
            labelMap.put("cityCode", cityCode);
            List<LabelEntity> lelist = user.getColorLabel4MyCustomer(labelMap);
            String[] emplabel;
            List<String> labIds = new ArrayList<>();

            if (labelId != null && !"".equals(labelId)) {
                if (!labelId.contains(",")) {
                    emplabel = new String[1];
                    emplabel[0] = labelId;
                } else {
                    emplabel = labelId.split(",");
                }
                for (String lid : emplabel) {
                    labIds.add(lid);
                }
            }

            //重覆客户标签搜索条件
            if (CollectionUtils.isNotEmpty(lelist)) {
                model.addAttribute("labellist", lelist);
                for (LabelEntity le : lelist) {
                    for (String emp : labIds) {
                        if (emp.equals(le.getLabelId())) {
                            le.setSelected("1");
                        }
                    }
                }
                model.addAttribute("haslabel", "1");
                model.addAttribute("labList", lelist);
            }
            //获取该客户标签、颜色
            Map<String, Object> labelMap2 = new HashMap<>(10);
            labelMap2.put("cityCode", cityCode);
            List<LabelEntity> lelist2 = user.getColorLabel4MyCustomer(labelMap2);//所有标签+颜色
            for (CustomerEntity customerEntity : response.getObjectList()) {

                String countdownTime = "";

                String star = "off";
                String userId4Star = "";
                boolean hasCustomerProjects = false;
                boolean hasNewCustomerProjects = false;
                //待回访是否私客标志
                Integer isPrivate = 0;
                List<CustomerCallbackLogEntity> callbacklist = new ArrayList<>();
                List<Object> lids = new ArrayList<>();
                // 待回访以外的tab才需要显示回访记录 star 约看记录
                List<LabelEntity> oldList = new ArrayList<>();
                if (!org.apache.commons.lang3.StringUtils.equals("waitCall", type)) {
                    //获取客户标签
                    oldList = user.queryCustomerLabel(null, customerEntity.getId());
                } else {
                    Map<String, Object> callMap = new HashMap<>(10);
                    callMap.put("managerId", customerEntity.getManagerId());
                    callMap.put("phone", customerEntity.getPhone());
                    //先去查询该客户合并id
                    CustomerEntity mergerentity = customer.getMergeCustomerId(callMap);
                    if (mergerentity != null) {
                        //该客户获得的所有标签
                        oldList = user.queryCustomerLabel(null, mergerentity.getId());
                    }
                }

                if (!org.apache.commons.lang3.StringUtils.equals("waitCall", type)) {

                    Map<String, Object> cpMap = new HashMap<>(10);
                    cpMap.put("phone", customerEntity.getPhone());
                    cpMap.put("managerId", customerEntity.getManagerId());
                    List<CustomerProjectEntity> appointList = customerProject.getCustomerProjectInfo(cpMap);
                    if (appointList != null && appointList.size() > 0) {
                        hasCustomerProjects = true;
                    }
                    for (CustomerProjectEntity cpe : appointList) {
                        if (userEntity.getPreLoginTime() != null && cpe.getLastChangeStatusTime() != null) {
                            if (userEntity.getPreLoginTime().before(cpe.getLastChangeStatusTime())) {
                                hasNewCustomerProjects = true;
                            }
                        }
                    }

                    // 获取回访记录
                    Page callbackLogPage = new Page(3);
                    callbackLogPage.setCurrentPage(0);
                    Map<String, Object> callMap = new HashMap<>(10);
                    callMap.put("EQ_customerId", customerEntity.getId());
                    CustomerCallbackLogListRequest cclr = new CustomerCallbackLogListRequest();
                    cclr.setSearchParams(callMap);
                    cclr.setPaging(callbackLogPage);
                    //先去查询该客户的所有id
                    List<CustomerEntity> idList = customer.getCustomerIds(customerEntity.getId(), cityCode);
                    //再获取所有id的回访记录
                    List<Integer> ids = new ArrayList<>();
                    for (CustomerEntity entity : idList) {
                        ids.add(entity.getId());
                    }
                    Map<String, Object> searchMap = new HashMap<>(10);
                    searchMap.put("ids", ids);
                    searchMap.put("managerId", userEntity.getId());
                    searchMap.put("cityCode", cityCode);
                    if (ids.size() > 0) {
                        callbacklist = customer.getCallBackList(searchMap);
                    }


                    if (CollectionUtils.isNotEmpty(oldList)) {
                        for (LabelEntity oldLabEntity : oldList) {
                            String oldLabId = oldLabEntity.getLabelId();
                            for (LabelEntity colorEntity : lelist2) {
                                String colorLabId = colorEntity.getLabelId();
                                if (oldLabId.equals(colorLabId)) {
                                    oldLabEntity.setColorId(colorEntity.getColorId());
                                    oldLabEntity.setLabelName(colorEntity.getLabelName());
                                    lids.add(oldLabEntity);
                                }
                            }
                        }
                    }

                    // 获取star
                    star = customerEntity.getStarCustomer() == 1 ? "on" : "off";
                    userId4Star = customerId2UsrIdMap.get(customerEntity.getId()) == null ? "" : customerId2UsrIdMap.get(customerEntity.getId());
                } else {
                    // 计算倒计时
                    Date bindTime = customerEntity.getBindTime();
                    Date now = new Date();
                    long passedMills = now.getTime() - bindTime.getTime();
                    long passedMinutes = passedMills / (1000 * 60);
                    double countdownMinutes = retainMinutes - passedMinutes;
                    BigDecimal numCountdownTime = new BigDecimal(countdownMinutes).divide(new BigDecimal(60), 1,
                            BigDecimal.ROUND_HALF_UP);
                    countdownTime = numCountdownTime.toString();

                    //判断待回访客户是否已经是私客
                    Map<String, Object> map = new HashMap<>(10);
                    map.put("phone", customerEntity.getPhone());
                    map.put("managerId", customerEntity.getManagerId());
                    map.put("isPrivate", 1);
                    map.put("limit", 1);
                    List<CustomerEntity> list = customer.queryMergeByConditions(map);
                    if (CollectionUtils.isNotEmpty(list)) {
                        isPrivate = 1;
                    }
                }
                //标签当前用户所添加标签选中
                String markedLabelId = "";
                for (LabelEntity userCreateLabel : userLabelList) {
                    for (LabelEntity oldLabEntity : oldList) {
                        if (userCreateLabel.getLabelId().equals(oldLabEntity.getLabelId())) {
                            userCreateLabel.setSelected("1");
                            markedLabelId += userCreateLabel.getLabelId() + ",";
                        }
                    }
                }
                if (markedLabelId.contains(",")) {
                    markedLabelId = markedLabelId.substring(0, markedLabelId.length() - 1);
                }
                customerEntity.setMarkedLabelId(markedLabelId);
                int hasReport = 0;
                if (!"waitCall".equals(type)) {
                    Map<String, Object> map = new HashMap<>(5);
                    map.put("customerId", customerEntity.getId());
                    List<PropertyReportEntity> reportList = reportInterface.queryByConditions(map);
                    if (CollectionUtils.isNotEmpty(reportList)) {
                        hasReport = 1;
                    } else {
                        hasReport = 0;
                    }
                }
                String createSourceShow = "";
                if (org.apache.commons.lang3.StringUtils.isNotBlank(customerEntity.getCreateSource())) {
                    if ("CRM拉取".equals(customerEntity.getCreateSource())) {
                        createSourceShow = "营销活动";
                    } else if ("SYSTEM".equals(customerEntity.getCreateSource()) || "WECHAT".equals(customerEntity.getCreateSource())) {
                        createSourceShow = "手动添加";
                    } else if ("HOTLINE".equals(customerEntity.getCreateSource())) {
                        createSourceShow = "400来电";
                    } else if ("PT".equals(customerEntity.getCreateSource())) {
                        createSourceShow = "平台导入";
                    } else {
                        createSourceShow = customerEntity.getCreateSource();
                    }
                }
                CustomerListVO customerListVO = new CustomerListVO(customerEntity.getId(), customerEntity.getName(),
                        customerEntity.getPhone(), customerEntity.getSex(),
                        customerEntity.getActSource(),
                        customerEntity.getStatus(),
                        customerEntity.getCreateTime(),
                        customerEntity.getBuyIntention(),
                        customerEntity.getLastVisitTime(),
                        customerEntity.getLastCallTime(),
                        customerEntity.getManagerId(),
                        customerEntity.getManagerName(),
                        customerEntity.getTraceStatus(), star, userId4Star,
                        hasCustomerProjects, hasNewCustomerProjects,
                        customerEntity.getBelongToday(),
                        customerEntity.getBelongYestoday(),
                        customerEntity.getBelongSince(),
                        callbacklist, lids, customerEntity.getIsWaitCall(),
                        customerEntity.getLatestSource(),
                        customerEntity.getBindTime(),
                        customerEntity.getBakPhone1(),
                        customerEntity.getSingupTime(), countdownTime, customerEntity.getIsPeer(), isPrivate,
                        customerEntity.getStarCustomer(), customerEntity.getMarkedLabelId(), hasReport, createSourceShow
                );
                customers.add(customerListVO);

            }

        }
        logger.error("-------------------------3:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //对回访时间逻辑排序
        List<CustomerListVO> newCustomers = new ArrayList<>();//新排序数据
        List<CustomerListVO> customers2 = new ArrayList<>();//可移除的客户集合
        customers2 = customers;
        Integer huizhicishu = 0;
        if (!"waitCall".equals(type)) {
            for (int i = 0; i < customers.size(); i++) {
                CustomerListVO vo = customers.get(i);
                List<CustomerCallbackLogEntity> callbackLogEntities1 = vo.getCallbackLogEntities();
                CustomerCallbackLogEntity callbackenity = callbackLogEntities1.size() == 0 ? null : callbackLogEntities1.get(0);

                if (callbackenity == null) {//回访时间为空的一律置后
                    customers.add(customers.size(), vo);//再重新列序
                    customers.remove(i);//将当前不符合排序规则的数据移除

                    huizhicishu++;
                    if (huizhicishu == customers.size()) {
                        break;
                    }
                    i = -1;
                    continue;
                }
                Date callTime1 = callbackenity.getCreateTime();
                //处理倒序
                if (daoxuFlag) {
                    for (int j = i; j < customers2.size(); j++) {
                        CustomerListVO vo2 = customers2.get(j);
                        List<CustomerCallbackLogEntity> callbackLogEntities2 = vo2.getCallbackLogEntities();
                        CustomerCallbackLogEntity callbackenity2 = callbackLogEntities2.isEmpty() ? null : callbackLogEntities2.get(0);
                        if (callbackenity2 == null) {
                            continue;
                        }
                        Date callTime2 = callbackenity2.getCreateTime();
                        if (callTime2.after(callTime1)) {//后一日期比前一日期靠后,不符合倒叙
                            customers.add(i, customers2.get(j));
                            customers.remove(j + 1);
                        }
                    }
                }
                //处理顺序
                if (shunxuFlag) {
                    for (int j = i + 1; j < customers2.size(); j++) {
                        CustomerListVO vo2 = customers2.get(j);
                        List<CustomerCallbackLogEntity> callbackLogEntities2 = vo2.getCallbackLogEntities();
                        CustomerCallbackLogEntity callbackenity2 = callbackLogEntities2.isEmpty() ? null : callbackLogEntities2.get(0);
                        if (callbackenity2 == null) {
                            continue;
                        }
                        Date callTime2 = callbackenity2.getCreateTime();
                        if (callTime2.before(callTime1)) {//后一日期比前一日期靠前,不符合倒叙
                            customers.add(i, customers2.get(j));
                            customers.remove(j + 1);
                        }
                    }
                }
            }
        }
        logger.error("-------------------------4:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        model.addAttribute("page", response.getPaging());
        model.addAttribute("customers", customers);

        //未曾使用
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        // 判断当前用户是否为主管
        boolean isDirector = user.isDirector(userEntity.getId());
        model.addAttribute("isDirector", isDirector);
        model.addAttribute("currentUserId", userEntity.getId());
        // 回访内容模板
        model.addAttribute("callbackTemplateList", callbackTemplateList);
        return getAutoUrl();
    }

    private void filterParams(Map<String, Object> callSearchParams) {

        if (callSearchParams.containsKey("EQ_projectStatus")) {
            callSearchParams.remove("EQ_projectStatus");
        }
        if (callSearchParams.containsKey("EQ_orderByCreateTime")) {
            callSearchParams.remove("EQ_orderByCreateTime");
        }
        if (callSearchParams.containsKey("EQ_orderBy")) {
            callSearchParams.remove("EQ_orderBy");
        }
        if (callSearchParams.containsKey("EQ_timeType")) {
            callSearchParams.remove("EQ_timeType");
        }
        if (callSearchParams.containsKey("LIKE_likekeyword")) {
            callSearchParams.remove("LIKE_likekeyword");
        }
        if (callSearchParams.containsKey("EQ_orderByStar")) {
            callSearchParams.remove("EQ_orderByStar");
        }
        if (callSearchParams.containsKey("LTE_lastCallTimeEnd")) {
            callSearchParams.remove("LTE_lastCallTimeEnd");
        }
        if (callSearchParams.containsKey("GTE_lastCallTimeStart")) {
            callSearchParams.remove("GTE_lastCallTimeStart");
        }
        if (callSearchParams.containsKey("GTE_createTimeStart")) {
            callSearchParams.remove("GTE_createTimeStart");
        }
        if (callSearchParams.containsKey("LTE_createTimeEnd")) {
            callSearchParams.remove("LTE_createTimeEnd");
        }
        if (callSearchParams.containsKey("EQ_typeFilter")) {
            callSearchParams.remove("EQ_typeFilter");
        }

        if (callSearchParams.containsKey("EQ_typeFilter")) {
            callSearchParams.remove("EQ_typeFilter");
        }
        if (callSearchParams.containsKey("EQ_buyIntentionIsNull")) {
            callSearchParams.remove("EQ_buyIntentionIsNull");
        }
        if (callSearchParams.containsKey("EQ_buyIntention")) {
            callSearchParams.remove("EQ_buyIntention");
        }

    }

    /**
     * 查询客户回访记录
     *
     * @return 结果视图
     */
    @RequestMapping(value = "getCustomerCallbackLogs", method = RequestMethod.GET)
    @ResponseBody
    public List getCustomerCallbackLogs(HttpServletRequest request, Integer customerId, Integer managerId) {
        Page page = new Page(100);
        page.setCurrentPage(0);
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        Map<String, Object> searchMap = new HashMap<>(10);
        //先去查询该客户的所有id
        List<CustomerEntity> idList = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        if (StringUtils.isNotEmpty(String.valueOf(managerId))) {
            idList = customer.getCustomerIds(customerId, cityCode);
            //再获取所有id的回访记录
            for (CustomerEntity entity : idList) {
                ids.add(entity.getId());
            }
            searchMap.put("ids", ids);
        } else {
            ids.add(customerId);
            searchMap.put("ids", ids);
        }
        return customerCallbackLog.getCustomerCallbackLogList(searchMap);
    }

    /**
     * 查询客户约看记录
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "getCustomerProjects", method = RequestMethod.GET)
    @ResponseBody
    public List getCustomerProjects(HttpServletRequest request, Integer customerId, Integer managerId) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        Map<String, Object> cpMap = new HashMap<>(10);
        cpMap.put("EQ_customerId", customerId);
        CustomerProjectListRequest customerProjectListRequest = new CustomerProjectListRequest();
        Page page = new Page(100);
        page.setCurrentPage(0);
        customerProjectListRequest.setPaging(page);
        customerProjectListRequest.setSearchParams(cpMap);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        List<CustomerEntity> idList = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        Map<String, Object> searchMap = new HashMap<>(10);
        //先去查询该客户的所有id
        if (StringUtils.isNotEmpty(String.valueOf(managerId))) {
            idList = customer.getCustomerIds(customerId, cityCode);
            //再获取所有id的回访记录
            for (CustomerEntity entity : idList) {
                ids.add(entity.getId());
            }
            searchMap.put("ids", ids);
        } else {
            ids.add(customerId);
            searchMap.put("ids", ids);
        }
        List<CustomerProjectEntity> list = customerProject.getCustomerProjectList(searchMap);
        for (CustomerProjectEntity cpe : list) {
            if (userEntity.getPreLoginTime() != null && cpe.getLastChangeStatusTime() != null) {
                if (userEntity.getPreLoginTime().before(cpe.getLastChangeStatusTime())) {
                    cpe.setRemark("New!");
                } else {
                    cpe.setRemark("");
                }
            } else {
                cpe.setRemark("");
            }
        }
        return list;
    }

    @RequestMapping(value = "starToggle", method = RequestMethod.GET)
    @ResponseBody
    public Object starToggle(HttpServletRequest request, String flag, Integer customerId) throws ServiceRunException {
        // 取得所需参数
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            int userId = userEntity.getId();
            int star = "on".equalsIgnoreCase(flag) ? 1 : 0;
            dealStarCustomer(customerId, userId, star, 1);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        logger.debug("===starToggle==result===:{}", result);
        return result;
    }

    /**
     * 拨打电话
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "callCustomer", method = RequestMethod.GET)
    public String callCustomer(Model model, String memPhone, Integer managerId, Integer customerId, Integer buyIntention, String abandon
            , Integer isPeer, int star, HttpServletRequest request) {

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

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

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

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

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

        model.addAttribute("memPhone", memPhone);
        model.addAttribute("customerId", customerId);
        model.addAttribute("buyIntention", buyIntention);
        model.addAttribute("abandon", abandon);
        model.addAttribute("isPeer", isPeer);
        model.addAttribute("star", star);

        return getAutoUrl("callCustomer");
    }

    /**
     * 拨打电话
     *
     * @return
     */
    @RequestMapping(value = "calling", method = RequestMethod.GET)
    @ResponseBody
    public Object calling(HttpServletRequest request, String memPhone, Integer customerId) {
        Integer userId = (Integer) request.getSession().getAttribute(SessionConstants.THREAD_USERID_KEY);
        Integer callbackLogId = customerCallbackLog.calling(memPhone, customerId, userId);
        return callbackLogId;
    }

    /**
     * 挂断电话
     *
     * @return
     */
    @RequestMapping(value = "handUp", method = RequestMethod.GET)
    @ResponseBody
    public Object handUp(
            HttpServletRequest request, String memPhone, Integer callbackLogId, String callContent, Integer oldCustomerId, String labelIds, String buyIntention,
            String abandon
    ) {
        Integer userId = (Integer) request.getSession().getAttribute(SessionConstants.THREAD_USERID_KEY);
//        callbackLogId = customerCallbackLog.calling(memPhone, oldCustomerId, userId);
        customerCallbackLog.handUp(callbackLogId, callContent, buyIntention, userId, labelIds, abandon);
        return "";
    }

    /**
     * 更新客户是否同行状态(type 0 非私客触发 1私客触发)
     *
     * @return
     */
    @RequestMapping(value = "/updatePeerAndTime/{type}", method = {RequestMethod.POST})
    @ResponseBody
    public HResult updatePeer(HttpServletRequest request, @RequestBody CustomerEntity entity, @PathVariable int type) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            int userId = userEntity.getId();
            DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
            String cityId = departmentEntity.getCityID();
            DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
            String cityCode = departmentResponse.getEntity().getDescripition();
            Date returnRemindTime = entity.getReturnRemindTime();
            if (returnRemindTime != null) {
                Date date = new Date();
                if (returnRemindTime.before(date)) {
                    result.setStatus(-1);
                    result.setErrorMessage("回访提醒时间不能小于当前时间");
                    return result;
                }
            }
            int customerId = entity.getId();
            int isPeer = entity.getIsPeer();
            int starCustomer = entity.getStarCustomer();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(entity.getBuyIntention()) && entity.getBuyIntention().equals("5")) {
                returnRemindTime = null;
            }
            customer.updatePeer(customerId, isPeer, returnRemindTime, userId, cityCode);

            if (!"5".equals(entity.getBuyIntention())) {
                dealStarCustomer(customerId, userId, starCustomer, type);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("修改客户状态失败");
            logger.error("修改客户是否同行状态失败", e);
        }
        return result;
    }

    /**
     * 更新客户是否同行状态
     *
     * @return
     */
    @RequestMapping(value = "/updateStar", method = {RequestMethod.POST})
    @ResponseBody
    public HResult updateStar(HttpServletRequest request, @RequestBody CustomerEntity entity) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            int userId = userEntity.getId();

            int customerId = entity.getId();
            int starCustomer = entity.getStarCustomer();
            //查询的customerMerge表
            if (!"5".equals(entity.getBuyIntention())) {
                dealStarCustomer(customerId, userId, starCustomer, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("修改客户星标状态失败");
            logger.error("修改客户星标状态失败", e);
        }
        return result;
    }

    private void dealStarCustomer(int customerId, int userId, int star, int type) {
        try {
            boolean flag = true;
            //非私客触发更新星标状态，直接更新旧表
            if (type == 0) {
                CustomerResponse customerResponse = customer.getCustomerById(customerId);
                if (customerResponse != null && customerResponse.getEntity() != null) {
                    CustomerEntity entity = customerResponse.getEntity();
                    if (entity.getManagerId() != null && entity.getManagerId() == userId) {
                        customer.updateOldCustomerStar(entity.getId(), star);
                        Map<String, Object> map = new HashMap<>(5);
                        map.put("phone", entity.getPhone());
                        map.put("managerId", entity.getManagerId());
                        List<CustomerEntity> list = customer.queryMergeByConditions(map);
                        if (CollectionUtils.isNotEmpty(list)) {
                            CustomerEntity mergeEntity = list.get(0);
                            if (mergeEntity.getManagerId() != userId) {
                                flag = false;
                            } else {
                                customerId = mergeEntity.getId();
                            }
                        }
                    }
                }
            }
            //当星标状态为1，且不是私客走变更时，合并表星标状态不做变动
            if (type == 0 && star == 0) {
                flag = false;
            }
            if (type == 1 || flag) {
                Map<String, Object> search = new HashMap<>(10);
                search.put("EQ_customerId", customerId);
                search.put("EQ_userId", userId);
                CustomerUserListRequest cul = new CustomerUserListRequest();
                cul.setPaging(new Page(1));
                cul.setSearchParams(search);
                //update
                CustomerUserListResponse res = customerUser.getCustomerUserList(cul);
                if (res.getObjectList() != null && !res.getObjectList().isEmpty()) {
                    CustomerUserEntity entity = res.getObjectList().get(0);
                    entity.setStar(star);

                    CustomerUserRequest updateReq = new CustomerUserRequest();
                    updateReq.setEntity(entity);
                    customerUser.updateCustomerUser(updateReq);
                    //继续更新customer表的星标字段------->改为更新客户合并表对应的字段
                    customer.updateCustomerStar(entity.getCustomerId(), entity.getStar());
                } else {
                    //add new
                    CustomerUserEntity entity = new CustomerUserEntity();
                    entity.setCustomerId(customerId);
                    entity.setUserId(userId);
                    entity.setStar(star);
                    entity.setCreateTime(new Date());

                    CustomerUserRequest newReq = new CustomerUserRequest();
                    newReq.setEntity(entity);
                    customerUser.addCustomerUser(newReq);
                    //继续更新customer表的星标字段------->改为更新客户合并表对应的字段
                    customer.updateCustomerStar(entity.getCustomerId(), entity.getStar());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("dealStarCustomer失败", e);
        }
    }

    @RequestMapping(value = "/newsList")
    @ResponseBody
    public HResult newsList(HttpServletRequest request) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            int userId = userEntity.getId();
            DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
            String cityId = departmentEntity.getCityID();
            DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
            String cityCode = departmentResponse.getEntity().getDescripition();
            Map<String, Object> map = new HashMap<>(10);
            map.put("userId", userId);
            map.put("cityCode", cityCode);
            map.put("time", new Date());
            List<CustomerRemindEntity> list = customer.queryByCondition(map);
            result.setData(list);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("查询提醒消息列表失败");
            logger.error("查询提醒消息列表失败", e);
        }
        return result;
    }

    @RequestMapping(value = "/deleteTips/{id}")
    @ResponseBody
    public HResult deleteTips(@PathVariable int id) {
        HResult result = new HResult();
        try {
            customer.deleteTips(id);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("删除提醒消息失败");
            logger.error("删除提醒消息失败", e);
        }
        return result;
    }

    /**
     * 判断是否私客
     *
     * @param id 主键id
     * @return
     */
    @RequestMapping(value = "/judgeStar/{id}")
    @ResponseBody
    public HResult judgeStar(@PathVariable int id, HttpServletRequest request) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            int userId = userEntity.getId();
            CustomerResponse customerResponse = customer.getCustomerById(id);
            if (customerResponse != null && customerResponse.getEntity() != null) {
                CustomerEntity entity = customerResponse.getEntity();
                if (entity.getManagerId() != null) {
                    int managerId = entity.getManagerId();
                    if (managerId != userId) {
                        result.setStatus(-1);
                        result.setErrorMessage("不能为其他客户改变星标状态");
                    }
                } else {
                    result.setStatus(-1);
                    result.setErrorMessage("判断星标客户失败");
                }
            } else {
                result.setStatus(-1);
                result.setErrorMessage("判断星标客户失败");
            }
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("判断星标客户失败");
            e.printStackTrace();
            logger.error("判断星标客户失败", e);
        }
        return result;
    }

    /**
     * 成交客户列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/successList")
    public String successList(Integer number, Model model, HttpServletRequest request) {
        try {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            //时间过滤
            String timePeriod = request.getParameter("timePeriod") == null ? "0" : request.getParameter("timePeriod");
            model.addAttribute("timePeriod", timePeriod);
            String city = dept.getDescripition();
            searchParams.put("city", city);
            searchParams.put("userId", userEntity.getId());
            Page page = new Page(100);
            if (null != number) {
                page.setCurrentPage(number);
            }
            MapListRequest listRequest = new MapListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            MapListResponse response = customer.successList(listRequest, userEntity);
            model.addAttribute("page", response.getPaging());
            model.addAttribute("dataList", response.getObjectList());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询成交客户列表失败", e);
        }
        return getAutoUrl();
    }

}
