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.beans.vo.CustomerVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.*;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.*;
import com.house365.ws.interfaces.server.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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 javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/platformmanagement")
public class PlatformManagementController extends BaseController {

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

    /**
     * 自动注入客户信息WS实现
     */
    @Autowired
    private ICustomer customer;
    @Autowired
    private ICustomerProject customerProject;
    @Autowired
    private IPlatRule platRule;
    @Autowired
    private IDepartment department;
    @Autowired
    private IUser iuser;
    @Autowired
    private ICustomerSource customerSource;
    @Autowired
    private MergeCustomerUtil mergeCustomerUtil;
    @Autowired
    private ICustomerCallbackLog customerCallbackLog;
    @Autowired
    private ICustomerLogInterface logInterface;


    @RequestMapping(value = "myPlatformCustomer", method = RequestMethod.GET)
    public String myPlatformCustomer(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);
        //去除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 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_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");
        }

        // 自定义时间
        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("createTime ");
                if (orderByTime < 2) {
                    sortColumn.append("desc");
                }
            } else if (orderByTime <= 4) {
                // 按派工时间排序
                sortColumn.append("bindTime ");
                if (orderByTime < 4) {
                    sortColumn.append("desc");
                }
            } else if (orderByTime <= 6) {
                // 按回访时间排序
                sortColumn.append("lastCallTime ");
                if (orderByTime < 6) {
                    sortColumn.append("desc");
                }

            } else if (orderByTime <= 8) {
                // 按倒计时排序
                sortColumn.append("countdown_time ");
                if (orderByTime < 8) {
                    sortColumn.append("desc");
                }
            }
        } else {
            sortColumn.append("createTime desc");
        }
        searchParams.put("EQ_orderBy", sortColumn.toString());
        searchParams.put("EQ_cityCode", cityCode);
        searchParams.put("EQ_isDelete", "0");
        searchParams.put("EQ_platformCreater", userEntity.getId());
        searchParams.put("EQ_customerSourceType", "8");
        searchParams.put("EQ_platformCreateSource", "PT");
        //过滤公海、跟进中
        String eqPlatProjectStatus = String.valueOf(searchParams.get("EQ_platProjectStatus"));
        if (eqPlatProjectStatus != null && "7".equals(eqPlatProjectStatus)) {//跟进中
            searchParams.remove("EQ_platProjectStatus");
            searchParams.put("EQ_platProjectStatus7", "7");
        }
        if (eqPlatProjectStatus != null && "8".equals(eqPlatProjectStatus)) {//回公海
            searchParams.remove("EQ_platProjectStatus");
            searchParams.put("EQ_platManager", "8");
        }
        CustomerListRequest listRequest = new CustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CustomerListResponse response = customer.getPlatformCustomerList(listRequest);
        List<CustomerListVO> customers = new ArrayList<>();
        if (response != null && response.getObjectList() != null) {
            List<CustomerEntity> resultList = response.getObjectList();
            logger.info("***********查询结果集************" + resultList.size());

            // 按objectList大小初始化list
            customers = new ArrayList<>(response.getObjectList().size());
            // customerId集合

            //星标客户\安家顾问集合
            Map<Integer, String> customerId2UsrIdMap = new HashMap<>(response.getObjectList().size());

            for (CustomerEntity customerEntity : response.getObjectList()) {
                String countdownTime = "";
                String userId4Star = "";
                boolean hasCustomerProjects = false;
                boolean hasNewCustomerProjects = false;
                //待回访是否私客标志
                Integer isPrivate = 0;
                List<CustomerCallbackLogEntity> callbackList = new ArrayList<>();

                // 获取回访记录
                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);
                List<CustomerEntity> idList = new ArrayList<>();
                if (StringUtils.isNotEmpty(String.valueOf(customerEntity.getManagerId()))) {
                    //先去查询该客户的所有id
                    idList = customer.getCustomerIds(customerEntity.getId(), cityCode);
                } else {
                    idList.add(customerEntity);//平台客户回公海
                }
                //再获取所有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 (CollectionUtils.isNotEmpty(ids)) {
                    callbackList = customer.getCallBackList(searchMap);
                }

                userId4Star = customerId2UsrIdMap.get(customerEntity.getId()) == null ? "" : customerId2UsrIdMap.get
                        (customerEntity.getId());

                // 获取约看记录
                Map<String, Object> cpMap = new HashMap<>(10);
                if (StringUtils.isNotEmpty(String.valueOf(customerEntity.getManagerId()))) {
                    cpMap.put("phone", customerEntity.getPhone());
                    cpMap.put("managerId", customerEntity.getManagerId());
                    List<CustomerProjectEntity> appointList = customerProject.getCustomerProjectInfo(cpMap);
                    if (CollectionUtils.isNotEmpty(appointList)) {
                        hasCustomerProjects = true;
                    }
                    for (CustomerProjectEntity cpe : appointList) {
                        if (userEntity.getPreLoginTime() != null && cpe.getLastChangeStatusTime() != null) {
                            if (userEntity.getPreLoginTime().before(cpe.getLastChangeStatusTime())) {
                                hasNewCustomerProjects = true;
                            }
                        }
                    }
                } else {
                    cpMap.put("customerIdNew", customerEntity.getId());
                    List<CustomerProjectEntity> cpList = customerProject.queryList(cpMap);
                    if (CollectionUtils.isNotEmpty(cpList)) {
                        hasCustomerProjects = true;
                    }
                    for (CustomerProjectEntity cpe : cpList) {
                        if (userEntity.getPreLoginTime() != null && cpe.getLastChangeStatusTime() != null) {
                            if (userEntity.getPreLoginTime().before(cpe.getLastChangeStatusTime())) {
                                hasNewCustomerProjects = true;
                            }
                        }
                    }
                }
                //平台客户状态判定
                if (StringUtils.isEmpty(String.valueOf(customerEntity.getManagerId()))) {
                    customerEntity.setPlatCustomerStatus("回公海");
                    //回公海创建时间、绑定时间、最近回访时间
                } else {//查询CustomerProject状态
                    UserUtil.showPlatCustomerStatus(customerEntity, cpMap);
                }

                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(), null, userId4Star,
                        hasCustomerProjects, hasNewCustomerProjects,
                        customerEntity.getBelongToday(),
                        customerEntity.getBelongYestoday(),
                        customerEntity.getBelongSince(),
                        callbackList, null, customerEntity.getIsWaitCall(),
                        customerEntity.getLatestSource(),
                        customerEntity.getBindTime(),
                        customerEntity.getBakPhone1(),
                        customerEntity.getSingupTime(), countdownTime, customerEntity.getIsPeer(), isPrivate,
                        customerEntity.getStarCustomer(), customerEntity.getMarkedLabelId(), null, "", customerEntity.getPlatCustomerStatus(), customerEntity.getCreater()
                );
                customers.add(customerListVO);
            }
        }
        //对回访时间逻辑排序
        List<CustomerListVO> customers2 = new ArrayList<>();//可移除的客户集合
        customers2 = customers;
        Integer huizhicishu = 0;
        for (int i = 0; i < customers.size(); i++) {
            CustomerListVO vo = customers.get(i);
            List<CustomerCallbackLogEntity> callbackLogEntities1 = vo.getCallbackLogEntities();
            CustomerCallbackLogEntity callbackenity = callbackLogEntities1.isEmpty() ? 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 callbackEntity2 = callbackLogEntities2.isEmpty() ? null : callbackLogEntities2.get(0);
                    if (callbackEntity2 == null) {
                        continue;
                    }
                    Date callTime2 = callbackEntity2.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 callbackEntity2 = callbackLogEntities2.isEmpty() ? null : callbackLogEntities2.get(0);
                    if (callbackEntity2 == null) {
                        continue;
                    }
                    Date callTime2 = callbackEntity2.getCreateTime();
                    if (callTime2.before(callTime1)) {//后一日期比前一日期靠前,不符合倒叙
                        customers.add(i, customers2.get(j));
                        customers.remove(j + 1);
                    }
                }
            }
        }

        model.addAttribute("page", response.getPaging());
        model.addAttribute("customers", customers);

        //未曾使用
        if (eqPlatProjectStatus != null && "7".equals(eqPlatProjectStatus)) {//跟进中
            searchParams.put("EQ_platProjectStatus", "7");
        }
        if (eqPlatProjectStatus != null && "8".equals(eqPlatProjectStatus)) {//跟进中
            searchParams.put("EQ_platProjectStatus", "8");
        }
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        // 判断当前用户是否为主管
        boolean isDirector = iuser.isDirector(userEntity.getId());
        model.addAttribute("isDirector", isDirector);
        model.addAttribute("currentUserId", userEntity.getId());
        return getAutoUrl();
    }


    @RequestMapping(value = "newCustomer", method = RequestMethod.GET)
    public String newCustomer(Model model, 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));
        DepartmentEntity city = departmentResponse.getEntity();

        Map<String, Object> csMap = new HashMap<>(10);
        csMap.put("EQ_city", city.getDescripition());
        csMap.put("EQ_status", "1");
        csMap.put("EQ_type", "1");
        CustomerSourceListRequest cslr = new CustomerSourceListRequest();
        Page page = new Page(Integer.MAX_VALUE);
        page.setCurrentPage(0);
        cslr.setPaging(page);
        cslr.setSearchParams(csMap);
        cslr.setOrderColumn("sort");
        cslr.setOrderMode("desc");
        //平台导入活动来源
        CustomerSourceListResponse cslrs = customerSource.getCustomerSourceList(cslr);
        CustomerVo vo = new CustomerVo();
        CustomerEntity ce = new CustomerEntity();
        ce.setCustomerType(1);
        ce.setSex(2);
        vo.setEntity(ce);
        csMap.clear();
        //跟进人,匹配：直销人员,默认:直销主管
        List<UserEntity> managers;
        //是否匹配平台规则
        List<PlatRuleEntity> deptList = platRule.queryDeptList(userEntity.getId());
        if (deptList == null || deptList.size() == 0) {
            csMap.put("deptUrlPath", city.getUrlPath());
            csMap.put("position", "直销主管");
            managers = iuser.queryManagers(csMap);
        } else {
            List<Integer> idList = new ArrayList<>();
            for (PlatRuleEntity pre : deptList) {
                idList.add(Integer.valueOf(pre.getSalesGroupIds()));
            }
            csMap.put("deptIds", idList);
            managers = iuser.queryRuleManagers(csMap);
        }


        model.addAttribute("managers", managers);
        //活动来源
        model.addAttribute("sources", cslrs.getObjectList());
        model.addAttribute("entity", vo.getEntity());
        return getAutoUrl("newCustomer");
    }


    /**
     * 平台客户-客户新增
     * 客户来源类型：8
     * 客户创建来源：PT
     * 安家顾问：平台指定安家顾问
     * 跟踪状态:有效
     *
     * @param model
     * @param request
     * @param vo
     * @return
     */
    @RequestMapping(value = "addNewCustomer", method = RequestMethod.POST)
    public String addNewCustomer(Model model, HttpServletRequest request, CustomerVo vo) {
        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();
        String selectedManager = request.getParameter("selectedManager");
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();
        CustomerEntity customerEntity = vo.getEntity();
        Date newdate = new Date();
        CustomerRequest cr = new CustomerRequest();
        customerEntity.setCreateTime(newdate);
        if (!Strings.isNullOrEmpty(customerEntity.getRemark())) {
            customerEntity.setLastCallTime(newdate);
        }
        customerEntity.setUpdateTime(newdate);
        customerEntity.setCreater(String.valueOf(userEntity.getId()));
//        customerEntity.setManagerId();
        customerEntity.setIsRecycled(0);
        customerEntity.setManagerName(selectedManager);
        customerEntity.setCityName(city.getName());
        customerEntity.setCityCode(city.getDescripition());
        customerEntity.setCrmSync("0");
        customerEntity.setTraceStatus(1);
        customerEntity.setIsDelete(0);
        customerEntity.setCreateSource("PT");
        //修改客户表默认值null改为11
        customerEntity.setStatus(Constant.statu);
        customerEntity.setBindTime(newdate);
        customerEntity.setCustomerSourceType(8);//8:平台导入类型
        CustomerSourceEntity cse = customerSource.getCustomerSourceById(customerEntity.getActSourceId()).getEntity();
        customerEntity.setActSource(cse == null ? "" : cse.getSourceName());
        cr.setEntity(customerEntity);
        CustomerResponse cret = customer.addCustomerNew(cr, userEntity.getId(), userEntity.getRealName());
        CustomerEntity newCustomerEntity = cret.getEntity();

        //合并之后的表:更新or新增
        CustomerEntity oldentity = customer.getCustomerMerge(customerEntity.getPhone(), customerEntity.getManagerId());
        if (oldentity == null) {
            //新旧表Id唯一
            customerEntity.setId(newCustomerEntity.getId());
            customer.saveCustomerMerge(customerEntity);
            //公海客户查询
            List<CustomerEntity> seaCustomers = customer.getSeaCustomerByPhone(customerEntity, userEntity);
            //去公海原顾问名下此客户同步更新
            if (CollectionUtils.isNotEmpty(seaCustomers)) {
                customer.updateSeaCustomerByPhone(customerEntity, userEntity);
            }
        } else {
            mergeCustomerUtil.checkMergeCustomer(customerEntity, oldentity, userEntity.getId(), userEntity.getRealName());
            // 意向等级、跟踪状态更新
            oldentity.setUpdateTime(newdate);
            oldentity.setCreateTime(newdate);
            oldentity.setBindTime(newdate);
            if (!Strings.isNullOrEmpty(customerEntity.getRemark())) {
                oldentity.setLastCallTime(newdate);
            }
            oldentity.setUpdater(String.valueOf(userEntity.getId()));
            customerEntity.setId(oldentity.getId());
            customer.updateCustomerMerge(oldentity);
        }
        if (!Strings.isNullOrEmpty(customerEntity.getRemark())) {
            addCallBack(userEntity, String.valueOf(newCustomerEntity.getId()), customerEntity.getRemark(), newdate);
        }

        model.addAttribute("vo", vo);
        return "redirect:/platformmanagement/customerInfo?&customerId=" + customerEntity.getId() + "&managerId=" + customerEntity.getManagerId() + "&phone=" + customerEntity.getPhone();
    }

    /**
     * 平台新增客户-添加回访记录
     *
     * @param userEntity
     * @param customerId
     * @param content
     * @param newdate
     * @return
     */
    private CustomerCallbackLogResponse addCallBack(UserEntity userEntity, String customerId, String content, Date newdate) {
        CustomerCallbackLogEntity customerCallbackLogEntity = new CustomerCallbackLogEntity();
        customerCallbackLogEntity.setCustomerId(Integer.valueOf(customerId));
        customerCallbackLogEntity.setContent(content);
        customerCallbackLogEntity.setCreater(userEntity.getName());
        customerCallbackLogEntity.setCreateTime(newdate);
        customerCallbackLogEntity.setManagerId(userEntity.getId());
        customerCallbackLogEntity.setManagerName(userEntity.getRealName());

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

    /**
     * 平台客户详情
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "customerInfo", method = RequestMethod.GET)
    public String customerInfo(Model model, 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();

        String customerId = request.getParameter("customerId");
        String managerId = request.getParameter("managerId");
        String phone = request.getParameter("phone");
        String action = request.getParameter("action");
        CustomerEntity customerEntity;
        if (StringUtils.isEmpty(managerId)) {//公海客户详情页
            CustomerResponse customerResponse = customer.getCustomerById(Integer.valueOf(customerId));
            customerEntity = customerResponse.getEntity();
        } else {
            Map<String, Object> map = new HashMap<>(10);
            map.put("managerId", managerId);
            map.put("phone", phone);
            customerEntity = customer.getMergeCustomerId(map);
        }


        userEntity.setCity(cityCode);
        //根据新的客户id获取旧表中的id
        Map<String, Object> idMap = new HashMap<>(10);
        idMap.put("phone", customerEntity.getPhone());
        idMap.put("managerId", customerEntity.getManagerId());
        idMap.put("cityCode", cityCode);
        List<CustomerEntity> oldList = new ArrayList<>();
        if (StringUtils.isNotEmpty(managerId)) {
            oldList = customer.queryCustomers(idMap);
        } else {
            customerEntity.setManagerName(customerEntity.getLastManager());
            oldList.add(customerEntity);
        }
        List<Integer> customerIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(oldList)) {
            for (CustomerEntity e : oldList) {
                customerIdList.add(e.getId());
            }
        }
        Map<String, Object> cpMap = new HashMap<>(10);
        cpMap.put("phone", customerEntity.getPhone());
        cpMap.put("managerId", customerEntity.getManagerId());
        if (StringUtils.isEmpty(String.valueOf(customerEntity.getManagerId()))) {
            customerEntity.setPlatCustomerStatus("回公海");
            //回公海创建时间、绑定时间、最近回访时间
        } else {//查询CustomerProject状态
            UserUtil.showPlatCustomerStatus(customerEntity, cpMap);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(customerEntity.getCreateSource())) {
            UserUtil.showCreateSource(customerEntity);
        }
        Map<String, Object> tmpMap = new HashMap<>(10);
        List<CustomerProjectEntity> cpList;
        List<CustomerCallbackLogEntity> backLogList;
        if (StringUtils.isNotEmpty(String.valueOf(customerEntity.getManagerId()))) {
            //约看项目
            cpList = doCustomerProject(userEntity, customerIdList);
            //回访记录
            tmpMap.put("idList", customerIdList);
            backLogList = customerCallbackLog.queryByConditions(tmpMap);
        } else {
            cpList = doCustomerProject(userEntity, customerEntity);
            tmpMap.put("customerId", customerEntity.getId());
            backLogList = customerCallbackLog.queryByConditions(tmpMap);
        }

        // 客户详情展示退回公海时间
        boolean displayBackToSeaDate = false;
        Calendar backToSeaCal = Calendar.getInstance();
        String backToSeaDate = "";
        int visitCount = 0;
        //判断回公海时间
        displayBackToSeaDate = DictUtil.getBackToSeaTime(customerEntity, userEntity, cpList, backToSeaCal, visitCount, backLogList, displayBackToSeaDate);
        if (displayBackToSeaDate) {
            backToSeaDate = new SimpleDateFormat("yyyy-MM-dd").format(backToSeaCal.getTime());
        }
        if (StringUtils.isNotEmpty(String.valueOf(customerEntity.getManagerId()))) {
            model.addAttribute("displayBackToSeaDate", displayBackToSeaDate);
        }
        userEntity.setCity(cityCode);
        model.addAttribute("action", action);
        model.addAttribute("callLogs", backLogList);
        model.addAttribute("customerProjects", cpList);
        model.addAttribute("entity", customerEntity);
        model.addAttribute("backToSeaDate", backToSeaDate);
        //查询客户日志
        Map<String, Object> map = new HashMap<>(10);
        List<CustomerLogEntity> list = new ArrayList<>();
        if (StringUtils.isEmpty(managerId)) {
            map.put("relateId", customerEntity.getId());
            list = logInterface.queryByConditions(map);
        } else {
            map.put("phone", phone);
            map.put("managerId", managerId);
            map.put("idList", customerIdList);
            list = logInterface.queryByConditions(map);
        }
        List<String> logShowList = new ArrayList<>(15);
        //新增操作日志
        UserUtil.addOperateLog(logShowList, list);
        //客户情况来源
        UserUtil.showCreateSource(oldList);
        for (CustomerEntity tempCe : oldList) {
            if ("8".equals(String.valueOf(tempCe.getCustomerSourceType()))) {
                UserEntity tue = iuser.getById(Integer.valueOf(tempCe.getCreater()));
                tempCe.setCreater(tue.getRealName());
            }
        }
        model.addAttribute("oldList", oldList);
        //客户日志列表
        model.addAttribute("logList", logShowList);
        model.addAttribute("customerId", customerId);
        return getAutoUrl("customerInfo");
    }


    private List<CustomerProjectEntity> doCustomerProject(UserEntity userEntity, List<Integer> customerIdList) {
        Map<String, Object> cpMap = new HashMap<>(10);
        cpMap.put("idList", customerIdList);
        List<CustomerProjectEntity> cpList = customerProject.queryList(cpMap);
        if (CollectionUtils.isNotEmpty(cpList)) {
            for (CustomerProjectEntity cp : cpList) {
                if (userEntity.getPreLoginTime() != null && cp.getLastChangeStatusTime() != null) {
                    if (userEntity.getPreLoginTime().before(cp.getLastChangeStatusTime())) {
                        cp.setRemark("New!");
                    } else {
                        cp.setRemark("");
                    }
                } else {
                    cp.setRemark("");
                }
            }
        }
        return cpList;
    }

    private List<CustomerProjectEntity> doCustomerProject(UserEntity userEntity, CustomerEntity customerEntity) {
        Map<String, Object> cpMap = new HashMap<>(10);
        cpMap.put("customerIdNew", customerEntity.getId());
        List<CustomerProjectEntity> cpList = customerProject.queryList(cpMap);
        if (CollectionUtils.isNotEmpty(cpList)) {
            for (CustomerProjectEntity cp : cpList) {
                if (userEntity.getPreLoginTime() != null && cp.getLastChangeStatusTime() != null) {
                    if (userEntity.getPreLoginTime().before(cp.getLastChangeStatusTime())) {
                        cp.setRemark("New!");
                    } else {
                        cp.setRemark("");
                    }
                } else {
                    cp.setRemark("");
                }
            }
        }
        return cpList;
    }

    /**
     * 平台客户规则
     *
     * @param number
     * @param pageSize
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "ruleList", method = RequestMethod.GET)
    public String ruleList(Integer number, Integer pageSize, Model model, HttpServletRequest request) {

        Page page = new Page(pageSize == null ? 100 : pageSize);
        if (null != number) {
            page.setCurrentPage(number);
        }
        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("cityCode", cityCode);
        map.put("startNum", page.getStartRecord());
        map.put("pageSize", page.getPageSize());
        List<PlatRuleEntity> prList = platRule.getPlatRuleList(map);
        Integer count = platRule.countPlatRule(map);
        if (prList != null) {
            page.setRecords(prList.size());
            page.setPages(count % page.getPageSize() == 0 ? count / page.getPageSize() : count / page.getPageSize() + 1);

        }
        model.addAttribute("page", page);
        model.addAttribute("prList", prList);
        return getAutoUrl();
    }

    /**
     * 删除规则
     *
     * @param id
     * @param httpResponse
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public void delRule(@PathVariable String id, HttpServletResponse httpResponse) {
        platRule.delRule(id);
    }


    /**
     * 新增规则
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "addRule", method = RequestMethod.GET)
    public String addRule(Model model, HttpServletRequest request) {
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>(10);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_REAL_DEPT_KEY);
        if (PathUtil.isAdminDept(departmentEntity)) {
            departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
        }
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        String urlPath = deptEntity.getEntity().getUrlPath();
        String[] arr = urlPath.split("/");
        String depth = "";
        if (urlPath != null && arr.length > 3) {
            depth = "/" + arr[1] + "/" + arr[2];
            map.put("REGEXP_urlPath", "^" + depth + "$|^" + depth + "/");
        } else {
            map.put("REGEXP_urlPath", "^" + urlPath + "$|^" + urlPath + "/");
        }

        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> models = resp.getObjectList();
        model.addAttribute("trees", models);
        return getAutoUrl("addRule");
    }


    /**
     * 编辑规则
     *
     * @return
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateRule(@PathVariable(value = "id") String id, Model model, HttpServletRequest request) {
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>(10);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_REAL_DEPT_KEY);
        if (PathUtil.isAdminDept(departmentEntity)) {
            departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
        }
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        String urlPath = deptEntity.getEntity().getUrlPath();
        String[] arr = urlPath.split("/");
        String depth = "";
        if (urlPath != null && arr.length > 3) {
            depth = "/" + arr[1] + "/" + arr[2];
            map.put("REGEXP_urlPath", "^" + depth + "$|^" + depth + "/");
        } else {
            map.put("REGEXP_urlPath", "^" + urlPath + "$|^" + urlPath + "/");
        }
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> models = resp.getObjectList();
        model.addAttribute("trees", models);
        //
        PlatRuleEntity pre = platRule.getRuleById(id);
        model.addAttribute("ruleId", id);
        model.addAttribute("platId", pre.getPlatGroupIds());
        model.addAttribute("saleId", pre.getSalesGroupIds());
        model.addAttribute("platDeptName", pre.getPlatGroupName());
        model.addAttribute("saleDeptName", pre.getSalesGroupName());
        return getAutoUrl("updateRule");
    }

    /**
     * 保存修改内容
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "modifyRule", method = RequestMethod.GET)
    @ResponseBody
    public String modifyRule(Model model, HttpServletRequest request) {
        String ruleId = request.getParameter("ruleId");
        String platDeptId = request.getParameter("platDeptId");
        String saleDeptId = request.getParameter("saleDeptId");
        String platDeptName = request.getParameter("platDeptName");
        String saleDeptName = request.getParameter("saleDeptName");
        Date newDate = new Date();
        PlatRuleEntity pre = new PlatRuleEntity();
        pre.setPlatGroupIds(platDeptId);
        pre.setPlatGroupName(platDeptName);
        pre.setSalesGroupIds(saleDeptId);
        pre.setSalesGroupName(saleDeptName);
        pre.setUpdateTime(newDate);
        pre.setId(Integer.valueOf(ruleId));
        platRule.modifyRule(pre);
        return "success";
    }


    /**
     * 保存添加平台规则
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "saveRule", method = RequestMethod.GET)
    @ResponseBody
    public String saveRule(Model model, 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));
        DepartmentEntity city = departmentResponse.getEntity();

        String platDeptId = request.getParameter("platDeptId");
        String saleDeptId = request.getParameter("saleDeptId");
        String platDeptName = request.getParameter("platDeptName");
        String saleDeptName = request.getParameter("saleDeptName");
        Date newDate = new Date();
        PlatRuleEntity pre = new PlatRuleEntity();
        pre.setCreaterId(String.valueOf(userEntity.getId()));
        pre.setCreaterName(userEntity.getRealName());
        pre.setPlatGroupIds(platDeptId);
        pre.setPlatGroupName(platDeptName);
        pre.setSalesGroupIds(saleDeptId);
        pre.setSalesGroupName(saleDeptName);
        pre.setCreateTime(newDate);
        pre.setUpdateTime(newDate);
        pre.setCityCode(city.getDescripition());
        platRule.saveRule(pre);
        return "success";
    }

}
