/**
 * Description: 营销活动控制器
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-12-05 下午 19:20:59
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-12-05   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.house365.beans.common.HGSConstant;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.MarketingActivityVo;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.parameter.House365RestObject;
import com.house365.web.cached.RedisUtilsInterface;
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.beans.util.HResult;
import com.house365.ws.interfaces.server.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 营销活动控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-12-05
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/marketingactivity")
public class MarketingActivityController extends BaseController {

    private static final Logger activityLogger = LoggerFactory.getLogger(MarketingActivityController.class);

    @Value("${CRM.CUSTOMERQUERY.URL}")
    private String crmQueryURL;
    @Value("${CRM.TRANSLATE.URL}")
    private String crmTranslateURL;
    @Value("${CRM.SEEQUERY.URL}")
    private String crmSeeUrl;

    /**
     * 自动注入营销活动WS实现
     */
    @Autowired
    private IMarketingActivity marketingActivity;
    @Autowired
    private RedisUtilsInterface redisUtil;
    @Autowired
    private IDepartment department;
    @Autowired
    private IMarketBuildingRel marketBuildingRel;
    @Autowired
    private IHouseInfo houseInfo;
    @Autowired
    private IMarketCustomer marketCustomer;
    @Autowired
    private IDictionary dictionary;
    @Autowired
    private IUser iuser;
    @Autowired
    private ICustomerSource customerSource;
    @Autowired
    private ICustomer customer;
    @Autowired
    private ICrmSource crmSourceService;


    /**
     * 去新增营销活动
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model) {
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增营销活动
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createMarketingActivity(
            @Valid MarketingActivityVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        MarketingActivityEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                MarketingActivityRequest request = new MarketingActivityRequest();
                request.setEntity(entity);
                MarketingActivityResponse response = marketingActivity.addMarketingActivity(request);
                Integer id = response.getEntity().getId();
                return "redirect:/marketingactivity/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除营销活动
     *
     * @param id 营销活动页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/delete/{id}")
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id, HttpServletRequest request) {
        String userId = request.getSession().getAttribute(SessionConstants.THREAD_USERID_KEY).toString();
        String userName = request.getSession().getAttribute(SessionConstants.THREAD_USERNAME_KEY).toString();
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    MarketingActivityResponse response = marketingActivity.deleteMarketingActivityById(Integer.valueOf(ids[i]));
                    MarketingActivityEntity activityEntity = response.getEntity();
                    if (activityEntity.getFinishTime().after(new Date())) {
                        putToOcean(ids[i], Integer.parseInt(userId), userName);
                    }
                }
            } else {
                MarketingActivityResponse response = marketingActivity.deleteMarketingActivityById(Integer.valueOf(id));
                MarketingActivityEntity activityEntity = response.getEntity();
                if (activityEntity.getFinishTime().after(new Date())) {
                    putToOcean(id, Integer.parseInt(userId), userName);
                }
            }
        }
    }

    /**
     * 营销活动列表删除活动时，会往客户表中插入数据
     *
     * @param id
     */
    private void putToOcean(String id, int userId, String userName) {
        MarketCustomerListResponse customerListResponse = getnotassignList(Integer.valueOf(id), Integer.MAX_VALUE);
        //营销活动删除 ，把status 变为2，但是不把客户移入公海(),
        // customerListResponse.getObjectList()返回始终为null，不走下面循环
        for (MarketCustomerEntity mcustomer : customerListResponse.getObjectList()) {
            CustomerRequest customerRequest = new CustomerRequest();
            CustomerEntity customerEntity = mcustomer.convertCustomer();
            Date curDate = new Date();
            //更新来源
            Integer sourceId = customerSource.updateSource(mcustomer.getCityCode(), mcustomer.getActSource(),
                    mcustomer.getCreateSource(), "CRM");
            customerEntity.setActSourceId(sourceId);
            customerEntity.setCustomerSourceType(HGSConstant.CustomerSourceType.MARKET.getType());
            customerEntity.setManagerId(null);
            customerEntity.setManagerName("");
            customerEntity.setUpdateTime(curDate);
            customerEntity.setUpdater("SYSTEM");
            customerEntity.setCreateTime(curDate);
            customerEntity.setCreater("SYSTEM");
            //数据公海中客户购房意向为“无效”的客户，如果被派工后，统一提升客户的“购房意向”为：待定
            customerEntity.setBuyIntention("");
            customerEntity.setOceanDate(curDate);
            customerRequest.setEntity(customerEntity);
            CustomerResponse customerResponse = customer.addCustomerNew(customerRequest, userId, userName);
            mcustomer.setCustomerId(customerResponse.getEntity().getId());
            mcustomer.setUpdateTime(new Date());
            mcustomer.setUpdater("SYSTEM");
            MarketCustomerRequest mar = new MarketCustomerRequest();
            mar.setEntity(mcustomer);
            marketCustomer.updateMarketCustomer(mar);
        }
    }

    /**
     * 去查看营销活动
     *
     * @param id 营销活动页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        MarketingActivityResponse response = marketingActivity.getMarketingActivityById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    //goto create page
    @RequestMapping(value = "/step1", method = {RequestMethod.GET}, params = "action=create")
    public String step1(Model model) {
        model.addAttribute("action", "create");
        return getAutoUrl();
    }

    @RequestMapping(value = "/step1/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String step1View(@PathVariable(value = "id") Integer id, Model model) {
        model.addAttribute("action", "edit");
        MarketingActivityResponse mar = marketingActivity.getMarketingActivityById(id);
        model.addAttribute("entity", mar.getEntity());
        return getAutoUrl("step1");
    }

    /**
     * 加载前复制营销活动查询条件
     *
     * @param id
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/copyStep2/{id}")
    public String copyStep2(@PathVariable(value = "id") Integer id, Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        MarketingActivityResponse mar = marketingActivity.getMarketingActivityById(id);
        MarketingActivityEntity mae = mar.getEntity();
        //是否当日值班人员
        Integer uid = userEntity.getId();
        List<DutyStaffEntity> dutylist = iuser.getOndutyById(uid);
        if (dutylist != null && dutylist.size() > 0) {
            if ("1".equals(dutylist.get(0).getOnduty())) {
                model.addAttribute("limitDate", "0");//名单内:值班不限制时间选择范围
            }
            if ("0".equals(dutylist.get(0).getOnduty())) {
                model.addAttribute("limitDate", "1");//名单内:非值班限制时间选择范围
            }
        } else {
            model.addAttribute("limitDate", "0");//名单外不限制时间选择范围
        }
        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 cityCode = "zb".equalsIgnoreCase(city.getDescripition()) ? "nj" : city.getDescripition();

        MarketingActivityEntity marketingactivityentity = new MarketingActivityEntity();
        marketingactivityentity.setMobileType(0);
        marketingactivityentity.setCycle(20);
        MarketingActivityRequest addRequest = new MarketingActivityRequest();
        Date currentDate = new Date();
        marketingactivityentity.setStatus(HGSConstant.ActivityStatus.DRAFT.getStatus());
        marketingactivityentity.setFinishTime(DateTimeUtils.getTimeAfterDays(currentDate, 20));
        marketingactivityentity.setCreateBy(userEntity.getId());
        marketingactivityentity.setCreateTime(new Date());
        marketingactivityentity.setCreateName(userEntity.getRealName());
        marketingactivityentity.setCity(city.getDescripition());
        addRequest.setEntity(marketingactivityentity);
        MarketingActivityResponse response = marketingActivity.addMarketingActivity(addRequest);//创建新的营销活动
        model.addAttribute("entity", response.getEntity());
        //查询条件
        MarketingActivityEntity querycondResult = marketingActivity.getQueryCondByActiveId(id);//旧营销活动数据
        //复制旧营销活动数据到新创建的营销活动中去


        model.addAttribute("querycondResult", querycondResult);
        model.addAttribute("activityName", querycondResult.getName());
        model.addAttribute("activityType", querycondResult.getType());
        //区域、板块
        List<DictionaryEntity> blocks = new ArrayList<>();
        List<DictionaryEntity> districts = new ArrayList<>();
        try {
            //板块
            List<NameValuePair> blockParam = new ArrayList<>();
            blockParam.add(new BasicNameValuePair("city", cityCode));
            blockParam.add(new BasicNameValuePair("type", "block"));
            String blockResult = HttpClientUtil.doGet(crmTranslateURL, blockParam);
            JSONObject block = JSONObject.fromObject(blockResult);
            for (Object obj : block.entrySet()) {
                DictionaryEntity dictionaryEntity = new DictionaryEntity();
                dictionaryEntity.setDicKey("block");
                dictionaryEntity.setDicValue(String.valueOf(((ListOrderedMap.Entry) obj).getKey()));
                dictionaryEntity.setDicName((String) ((ListOrderedMap.Entry) obj).getValue());
                dictionaryEntity.setCity(cityCode);
                blocks.add(dictionaryEntity);
            }
            //区域
            List<NameValuePair> districtParam = new ArrayList<>();
            districtParam.add(new BasicNameValuePair("city", cityCode));
            districtParam.add(new BasicNameValuePair("type", "district"));
            String districtResult = HttpClientUtil.doGet(crmTranslateURL, districtParam);
            JSONObject district = JSONObject.fromObject(districtResult);
            for (Object obj : district.entrySet()) {
                DictionaryEntity dictionaryEntity = new DictionaryEntity();
                dictionaryEntity.setDicKey("district");
                dictionaryEntity.setDicValue(String.valueOf(((ListOrderedMap.Entry) obj).getKey()));
                dictionaryEntity.setDicName((String) ((ListOrderedMap.Entry) obj).getValue());
                dictionaryEntity.setCity(cityCode);
                districts.add(dictionaryEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //处理区域板块选值回显
        String bs = querycondResult.getBlock();
        String ds = querycondResult.getDistrict();
        String[] blockArr = {};
        String[] districtsArr = {};
        if (!StringUtils.isEmpty(bs)) {
            blockArr = bs.split(",");
        }
        if (!StringUtils.isEmpty(ds)) {
            districtsArr = ds.split(",");
        }
        for (DictionaryEntity block : blocks) {//板块
            String dicValue = block.getDicValue();
            for (String arr : blockArr) {
                if (dicValue.equals(arr)) {
                    block.setSeleted("1");//选中
                }
            }
        }
        for (DictionaryEntity district : districts) {//区域
            String dicValue = district.getDicValue();
            for (String arr : districtsArr) {
                if (dicValue.equals(arr)) {
                    district.setSeleted("1");
                }
            }
        }
        model.addAttribute("districts", districts);
        model.addAttribute("blocks", blocks);
        return getAutoUrl();
    }

    //create active
    @RequestMapping(value = "/step1", method = {RequestMethod.POST})
    public String step1(MarketingActivityVo vo, Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String action = request.getParameter("action") == null ? "" : request.getParameter("action");
        String url = "";

        if ("edit".equalsIgnoreCase(action) && vo.getEntity().getId() != null) {
            MarketingActivityResponse mar = marketingActivity.getMarketingActivityById(vo.getEntity().getId());
            MarketingActivityEntity mae = mar.getEntity();
            if (mae != null) {
                MarketingActivityRequest activityRequest = new MarketingActivityRequest();
                mae.setName(vo.getEntity().getName());
                mae.setType(vo.getEntity().getType());
                mae.setExpectExtractCount(vo.getEntity().getExpectExtractCount());
                mae.setUpdateBy(userEntity.getId());
                mae.setUpdateTime(new Date());
                activityRequest.setEntity(mae);
                marketingActivity.updateMarketingActivity(activityRequest);
                url = "redirect:/marketingactivity/step1/" + mae.getId() + "?action=" + action;
            }
        } else {

            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();
            vo.getEntity().setCycle(20);

            vo.getEntity().setMobileType(0);
            MarketingActivityRequest addRequest = new MarketingActivityRequest();
            Date currentDate = new Date();
            vo.getEntity().setStatus(HGSConstant.ActivityStatus.DRAFT.getStatus());
            vo.getEntity().setFinishTime(DateTimeUtils.getTimeAfterDays(currentDate, vo.getEntity().getCycle()));
            vo.getEntity().setCreateBy(userEntity.getId());
            vo.getEntity().setCreateTime(new Date());
            vo.getEntity().setCreateName(userEntity.getRealName());
            vo.getEntity().setCity(city.getDescripition());
            addRequest.setEntity(vo.getEntity());
            MarketingActivityResponse response = marketingActivity.addMarketingActivity(addRequest);
            model.addAttribute("entity", response.getEntity());
            url = "redirect:/marketingactivity/step2/" + response.getEntity().getId();
        }
        return url;
    }

    //goto step2 page
    @RequestMapping(value = "/step2/{activeId}", method = {RequestMethod.GET})
    public String step2(Model model, @PathVariable(value = "activeId") String activeId, HttpServletRequest request) {
        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 cityCode = "zb".equalsIgnoreCase(city.getDescripition()) ? "nj" : city.getDescripition();
        //是否当日值班人员
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        Integer uid = userEntity.getId();
        List<DutyStaffEntity> dutylist = iuser.getOndutyById(uid);
        if (dutylist != null && dutylist.size() > 0) {
            if ("1".equals(dutylist.get(0).getOnduty())) {
                //名单内:值班不限制时间选择范围
                model.addAttribute("limitDate", "0");
            }
            if ("0".equals(dutylist.get(0).getOnduty())) {
                //名单内:非值班限制时间选择范围
                model.addAttribute("limitDate", "1");
            }
        } else {
            //名单外不限制时间选择范围
            model.addAttribute("limitDate", "0");
        }

        List<DictionaryEntity> blocks = new ArrayList<>();
        List<DictionaryEntity> districts = new ArrayList<>();

        MarketingActivityResponse response = marketingActivity.getMarketingActivityById(Integer.valueOf(activeId));

        try {
            if (request.getSession().getAttribute("blocks") != null && ((List<DictionaryEntity>) request.getSession().getAttribute("blocks")).size() > 0) {
                blocks = (List<DictionaryEntity>) request.getSession().getAttribute("blocks");
            } else {
                List<NameValuePair> blockParam = new ArrayList<>();
                blockParam.add(new BasicNameValuePair("city", cityCode));
                blockParam.add(new BasicNameValuePair("type", "block"));
                String blockResult = HttpClientUtil.doGet(crmTranslateURL, blockParam);
                JSONObject block = JSONObject.fromObject(blockResult);
                for (Object obj : block.entrySet()) {
                    DictionaryEntity dictionaryEntity = new DictionaryEntity();
                    dictionaryEntity.setDicKey("block");
                    dictionaryEntity.setDicValue(String.valueOf(((ListOrderedMap.Entry) obj).getKey()));
                    dictionaryEntity.setDicName((String) ((ListOrderedMap.Entry) obj).getValue());
                    dictionaryEntity.setCity(cityCode);
                    blocks.add(dictionaryEntity);
                }
                request.getSession().setAttribute("blocks", blocks);
            }

            if (request.getSession().getAttribute(
                    "districts") != null && ((List<DictionaryEntity>) request.getSession().getAttribute(
                    "districts")).size() > 0) {
                districts = (List<DictionaryEntity>) request.getSession().getAttribute("districts");
            } else {
                List<NameValuePair> districtParam = new ArrayList<>();
                districtParam.add(new BasicNameValuePair("city", cityCode));
                districtParam.add(new BasicNameValuePair("type", "district"));
                String districtResult = HttpClientUtil.doGet(crmTranslateURL, districtParam);
                JSONObject district = JSONObject.fromObject(districtResult);
                for (Object obj : district.entrySet()) {
                    DictionaryEntity dictionaryEntity = new DictionaryEntity();
                    dictionaryEntity.setDicKey("district");
                    dictionaryEntity.setDicValue(String.valueOf(((ListOrderedMap.Entry) obj).getKey()));
                    dictionaryEntity.setDicName((String) ((ListOrderedMap.Entry) obj).getValue());
                    dictionaryEntity.setCity(cityCode);
                    districts.add(dictionaryEntity);
                }
                request.getSession().setAttribute("districts", districts);
            }

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        model.addAttribute("districts", districts);
        model.addAttribute("blocks", blocks);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl();
    }

    @RequestMapping(value = "/step2", method = {RequestMethod.POST})
    @ResponseBody
    public HResult step2(MarketingActivityVo vo, HttpServletRequest request) {
        HResult result = new HResult();
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        String cityCode = departmentEntity.getDescripition();
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        String total = "0";
        House365RestObject restObject = new House365RestObject();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();
        nameValuePairList.add(new BasicNameValuePair("city", city.getDescripition()));

        try {
            MarketingActivityEntity entity = vo.getEntity();
            Integer customerCount = marketingActivity.queryCustomerCountByActive(entity.getId());
            if (customerCount > 0) {
                result.setErrorMessage("此活动已经导入过客户信息！");
                result.setStatus(-1);
                return result;
            }

            if (entity.getApplyStartTime() != null && entity.getApplyEndTime() != null) {
                if (vo.getSeeStartTime() != null && vo.getSeeEndTime() != null) {
                    nameValuePairList.add(new BasicNameValuePair("page", "1"));
                    nameValuePairList.add(new BasicNameValuePair("limit", "1000"));
                }
                setApplySource(request, entity, cityCode);
                wrapNameValuePairList(vo, nameValuePairList, entity);

                String preResult = HttpClientUtil.doGet(crmQueryURL, nameValuePairList);
                JSONObject jsonObject = JSONObject.fromObject(preResult);
                if (jsonObject.containsKey("total")) {
                    total = String.valueOf(jsonObject.get("total"));
                } else {
                    List<String> params = new ArrayList<>();
                    for (NameValuePair pair : nameValuePairList) {
                        params.add(pair.getName() + "=" + pair.getValue());
                    }
                    activityLogger.error("CRM接口返回错误数据!URL:[{}]", crmQueryURL + Joiner.on("&").join(params));
                    activityLogger.error("CRM接口返回错误数据!total不存在！[{}]", preResult);
                    result.setErrorMessage("调用crm查询接口出错！请稍后再试！");
                    result.setStatus(-1);
                    return result;
                }
            }
            Map<String, Integer> map = new HashMap<>(10);
            map.put("activeId", entity.getId());
            restObject.setTotal(String.valueOf(total));
            restObject.setParaMap(map);
            result.setData(restObject);

        } catch (IOException e) {
            e.printStackTrace();
            activityLogger.error("营销活动拉取数据报错", e);
            result.setStatus(-1);
            result.setErrorMessage("调取数据接口失败");
        }
        return result;
    }

    private void setApplySource(HttpServletRequest request, MarketingActivityEntity entity, String cityCode) {
        Set<String> crmSourceSet = new HashSet<>();
        //根据快捷来源选择所有下级CRM来源 v3.2.0
        String quickSources = request.getParameter("quickSource");
        if (!Strings.isNullOrEmpty(quickSources)) {
            for (String source : quickSources.split(",")) {
                List<CrmSourceEntity> sourceList = crmSourceService.getListByCategory(source);
                if (sourceList != null && !sourceList.isEmpty()) {
                    for (CrmSourceEntity sourceEntity : sourceList) {
                        //南京站新需求 过滤400来电562 和房博士im咨询99
                        if ("nj".equals(cityCode)) {
                            if (sourceEntity.getSourceId() != 99 && sourceEntity.getSourceId() != 562) {
                                crmSourceSet.add(String.valueOf(sourceEntity.getSourceId()));
                            }
                        } else {
                            crmSourceSet.add(String.valueOf(sourceEntity.getSourceId()));
                        }
                    }
                }
            }
            if (!crmSourceSet.isEmpty()) {
                String source = Joiner.on(",").join(crmSourceSet);
                entity.setApplySource(source);
                entity.setApplySourceName("电商、房博士、400电话、楼盘订阅、看房团");
            }
        }
    }

    //get load percent
    @RequestMapping(value = "/getLoad/{activeId}/{total}", method = {RequestMethod.GET})
    @ResponseBody
    public Object getLoad(
            @PathVariable(value = "activeId") String activeId, @PathVariable(value = "total") String total, Model model,
            HttpServletRequest request
    ) {

        House365RestObject restObject = new House365RestObject();
        //active:process 是否执行完毕 1 是 0 否
        //active:done 完成多少条
        //active:protect 保护条数
        String completePercent = "0";
        int completed = 0;
        int done = 0;
        int protect = 0;
        if (!Strings.isNullOrEmpty(activeId)) {
            protect = redisUtil.hasKey("active:protect:" + activeId) ? redisUtil.getIntegerByKey(
                    "active:protect:" + activeId) : 0;
            done = redisUtil.hasKey("active:done:" + activeId) ? redisUtil.getIntegerByKey(
                    "active:done:" + activeId) : 0;
            completed = done + protect;
            activityLogger.warn("redis log : [" + "active:process:" + activeId + "_" + redisUtil.hasKey(
                    "active:process:" + activeId) + "_" + redisUtil.getValByKey("active:process:" + activeId) + "]");
            activityLogger.warn("redis log : [" + "active:done:" + activeId + "_" + redisUtil.hasKey(
                    "active:done:" + activeId) + "_" + redisUtil.getValByKey("active:done:" + activeId) + "]");
            activityLogger.warn("redis log : [" + "active:protect:" + activeId + "_" + redisUtil.hasKey(
                    "active:protect:" + activeId) + "_" + redisUtil.getValByKey("active:protect:" + activeId) + "]");

            if (redisUtil.hasKey("active:process:" + activeId) && 1 == redisUtil.getIntegerByKey(
                    "active:process:" + activeId)) {
                completePercent = "100";
            } else {
                int totalNum = Integer.parseInt(total);
                int percent = new BigDecimal(completed).divide(new BigDecimal(totalNum), 2,
                        BigDecimal.ROUND_HALF_UP).multiply(
                        new BigDecimal(100)).intValue();
                completePercent = String.valueOf(percent);
            }
        }
        Map<String, String> pam = new HashMap<>(10);
        pam.put("protectCount", "" + protect);
        restObject.setTotal(String.valueOf(done));
        restObject.setEntity(completePercent);
        restObject.setParaMap(pam);

        return restObject;
    }


    @RequestMapping(value = "/import", method = {RequestMethod.POST})
    @ResponseBody
    public Object importData(MarketingActivityVo vo, HttpServletRequest request) {
        String result = "fail";
        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();
        try {
            MarketingActivityEntity entity = vo.getEntity();
            Map<String, Object> paraMap = new HashMap<>(10);
            paraMap.put("city", city.getDescripition());

            entity.setCity(city.getDescripition());
            marketBuildingRel.deleteByActiveId(entity.getId());
            entity.setStatus(HGSConstant.ActivityStatus.NORMAL.getStatus());

            // 楼盘ID
            String[] builds = vo.getBuildingId().split(",");
            int i = 0;
            for (String build : builds) {
                if (!Strings.isNullOrEmpty(build)) {
                    paraMap.put("project_ids[" + i + "]", build);
                    MarketBuildingRelRequest relRequest = new MarketBuildingRelRequest();
                    MarketBuildingRelEntity marketBuildingRelEntity = new MarketBuildingRelEntity();
                    marketBuildingRelEntity.setActiveId(entity.getId());
                    marketBuildingRelEntity.setBuildingId(Integer.valueOf(build));
                    relRequest.setEntity(marketBuildingRelEntity);
                    marketBuildingRel.addMarketBuildingRel(relRequest);
                    i++;
                }
            }

            String projectId = vo.getBuildingId();//项目id
            String seeProjectId = vo.getProjectId();//浏览项目id
            entity.setBrowseProjectId(seeProjectId);
            entity.setBuildingId(projectId);

            setApplySource(request, entity, city.getDescripition());

            wrapMap(entity, paraMap);

            MarketingActivityRequest marketingActivityRequest = new MarketingActivityRequest();
            String[] projectNames = vo.getProjectName().split(",");
            StringBuilder name = new StringBuilder();
            for (int j = 0; j < projectNames.length; j++) {
                name.append(projectNames[j].split("\\(")[0]).append(",");
            }
            String seeProjectName = name.toString();
            if (seeProjectName.contains(",")) {
                seeProjectName = seeProjectName.substring(0, seeProjectName.length() - 1);
            }
            entity.setSeeProjectName(seeProjectName);
            entity.setSeeCount(vo.getSeeCount());
            entity.setSeeStartTime(vo.getSeeStartTime());
            entity.setSeeEndTime(vo.getSeeEndTime());
            if (!StringUtils.isEmpty(vo.getActivityName())) {
                entity.setName(vo.getActivityName());
            }
            if (!StringUtils.isEmpty(vo.getActivityType())) {
                entity.setType(Integer.valueOf(vo.getActivityType()));
            }
            marketingActivityRequest.setEntity(entity);

            marketingActivity.updateMarketingActivity(marketingActivityRequest);

            if (vo.getSeeStartTime() == null && vo.getSeeEndTime() == null) {
                House365RestObject restObject = new House365RestObject();
                restObject.setParaMap(paraMap);
                restObject.setTotal(String.valueOf(vo.getEntity().getExpectExtractCount()));
                restObject.setEntity(vo.getEntity().getId());
                marketingActivity.importCustomers(restObject, city);
            }

            final Integer acid = entity.getId();
            final String cityKey = entity.getCity();
            ThreadPoolManager.putThread(new Runnable() {
                @Override
                public void run() {
                    houseInfo.updateHouseNameByActiveId(acid, cityKey);
                }
            });
            result = "success";
        } catch (Exception e) {
            e.printStackTrace();
            activityLogger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 去修改营销活动
     *
     * @param id 营销活动页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        MarketingActivityResponse response = marketingActivity.getMarketingActivityById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改营销活动
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateMarketingActivity(
            @Valid MarketingActivityVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, Model model
    ) {
        MarketingActivityEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                MarketingActivityRequest request = new MarketingActivityRequest();
                request.setEntity(entity);
                marketingActivity.updateMarketingActivity(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/marketingactivity/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询营销活动
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, 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();

        //get total count from customer
        MarketCustomerListRequest customerListRequest = new MarketCustomerListRequest();
        Map<String, Object> customerSearchMap = new HashMap<>(10);
        customerSearchMap.put("EQ_notassign", "1");
        customerListRequest.setSearchParams(customerSearchMap);
        MarketCustomerListResponse clr = marketCustomer.getTotalCount(customerListRequest);
        Integer totalNotAssign = clr.getPaging().getRecords();
        model.addAttribute("totalNotAssign", totalNotAssign);

        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(50);
        if (null != number) {
            page.setCurrentPage(number);
        }
        searchParams.put("EQ_status", 1);
        searchParams.put("EQ_city", city.getDescripition());
        //自己和子部门数据
        searchParams.put("EQ_userId", userEntity.getId());
        MarketingActivityListRequest listRequest = new MarketingActivityListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);

        Date cur = new Date();
        MarketingActivityListResponse response = marketingActivity.getMarketingActivityList(listRequest);

        MarketingActivityListResponse pullCountResponse = marketingActivity.queryAllPullCount(listRequest);
        model.addAttribute("pullCountResponse", pullCountResponse.getPaging().getRecords());

        for (MarketingActivityEntity act : response.getObjectList()) {
            if (cur.after(act.getFinishTime())) {
                act.setName(act.getName() + "(已结束)");
            } else {
                long left = (act.getFinishTime().getTime() - cur.getTime()) / 1000 / 60 / 60 / 24;
                if (left < 1) {
                    act.setName(act.getName() + "(不足1天)");
                } else {
                    act.setName(act.getName() + "(剩余" + left + "天)");
                }
            }

            //放弃客户数，包括直接放弃和回访并放弃
            MarketCustomerListResponse abandonList = getAbandonList(act.getId(), 1);
            int abandon = abandonList.getPaging().getRecords();
            act.setAbandon(abandon);

            //回访数据=回访-回访过并被放弃的
            MarketCustomerListResponse callAndAbandon = callAndAbandon(act.getId(), 1);
            int callAndAbandonCount = callAndAbandon.getPaging().getRecords();
            act.setCallAbandon(callAndAbandonCount);

            MarketCustomerListResponse customerList = getnotassignList(act.getId(), 1);
            int notAssign = customerList.getPaging().getRecords();
            act.setNotAssign(notAssign);

            MarketCustomerListResponse assignList = getAssignedList(act.getId(), 1);
            int assign = assignList.getPaging().getRecords();
            act.setAssign(assign);

            String descStr = getDescString(act);
            act.setDesc(descStr);
            String[] arrays;
            if (org.apache.commons.lang3.StringUtils.isNotBlank(descStr) && descStr.length() > 16) {
                arrays = descStr.split("<br>");
                if (arrays.length > 0) {
                    descStr = arrays[0];
                    if (descStr.length() > 16) {
                        act.setDescSub(descStr.substring(0, 16));
                    } else {
                        act.setDescSub(descStr);
                    }
                } else {
                    act.setDescSub("");
                }
            } else {
                act.setDescSub("");
            }
        }

        model.addAttribute("page", response.getPaging());
        model.addAttribute("marketingActivitys", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 查询营销活动
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/exportData", method = RequestMethod.GET)
    public void exportData(HttpServletRequest request, HttpServletResponse response) {
        try {
            //id	活动名称	来源条件	创建人	待派	已派	超时	放弃  回访	创建时间
            final String[] excelTitles = {"id", "活动名称", "来源条件", "创建人", "待派", "已派", "超时", "放弃", "回访", "创建时间"};
            List<List<Object>> recordList = new ArrayList<>();

            // 获取查询条件
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            Page page = new Page(10000);
            searchParams.put("EQ_status", 1);
            searchParams.put("EQ_city", "nj");

            MarketingActivityListRequest listRequest = new MarketingActivityListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);

            Date cur = new Date();
            MarketingActivityListResponse listResponse = marketingActivity.getMarketingActivityList(listRequest);


            for (MarketingActivityEntity act : listResponse.getObjectList()) {
                if (cur.after(act.getFinishTime())) {
                    act.setName(act.getName() + "(已结束)");
                } else {
                    long left = (act.getFinishTime().getTime() - cur.getTime()) / 1000 / 60 / 60 / 24;
                    if (left < 1) {
                        act.setName(act.getName() + "(不足1天)");
                    } else {
                        act.setName(act.getName() + "(剩余" + left + "天)");
                    }
                }

                //放弃客户数，包括直接放弃和回访并放弃
                MarketCustomerListResponse abandonList = getAbandonList(act.getId(), 1);
                int abandon = abandonList.getPaging().getRecords();
                act.setAbandon(abandon);

                //回访数据=回访-回访过并被放弃的
                MarketCustomerListResponse callAndAbandon = callAndAbandon(act.getId(), 1);
                int callAndAbandonCount = callAndAbandon.getPaging().getRecords();
                act.setCallAbandon(callAndAbandonCount);

                MarketCustomerListResponse customerList = getnotassignList(act.getId(), 1);
                int notAssign = customerList.getPaging().getRecords();
                act.setNotAssign(notAssign);

                MarketCustomerListResponse assignList = getAssignedList(act.getId(), 1);
                int assign = assignList.getPaging().getRecords();
                act.setAssign(assign);

                String descStr = getDescString(act);
                act.setDesc(descStr);
                String[] arrays;
                if (org.apache.commons.lang3.StringUtils.isNotBlank(descStr) && descStr.length() > 16) {
                    arrays = descStr.split("<br>");
                    if (arrays.length > 0) {
                        descStr = arrays[0];
                        if (descStr.length() > 16) {
                            act.setDescSub(descStr.substring(0, 16));
                        } else {
                            act.setDescSub(descStr);
                        }
                    } else {
                        act.setDescSub("");
                    }
                } else {
                    act.setDescSub("");
                }
            }
            if (CollectionUtils.isNotEmpty(listResponse.getObjectList())) {
                for (MarketingActivityEntity p : listResponse.getObjectList()) {
                    List<Object> record = new ArrayList<>();
                    record.add(p.getId());
                    record.add(p.getName());
                    record.add(p.getDescSub());

                    record.add(p.getCreateName());
                    record.add(p.getNotAssign());
                    record.add(p.getAssign());
                    record.add(p.getOverTimeCount());
                    record.add(p.getAbandon());
                    record.add(p.getVisitBackCount());
                    record.add(p.getCreateTime());
                    recordList.add(record);
                }
            }
            ExcelUtil.exportExcel("营销活动数据导出.xlsx", "营销数据", excelTitles, recordList, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getDescString(MarketingActivityEntity act) {
        List<String> descList = new ArrayList<>();
        if (!Strings.isNullOrEmpty(act.getProjectName())) {
            descList.add("项目(" + act.getProjectName() + ")");
        }
        if (null != act.getMobileType()) {
            descList.add("电话类型(" + ("1".equalsIgnoreCase(String.valueOf(act.getMobileType())) ? "手机" : "固话") + ")");
        }
        if (null != act.getApplyStartTime() && null != act.getApplyEndTime()) {
            descList.add("报名时间(" + DateTimeUtils.parseDate(act.getApplyStartTime(),
                    DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT) + "-" + DateTimeUtils.parseDate(
                    act.getApplyEndTime(), DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT) + ")");
        }
        if (!Strings.isNullOrEmpty(act.getApplySourceName())) {
            descList.add("报名来源(" + act.getApplySourceName() + ")");
        }
        if (null != act.getActiveType()) {
            Map<String, Object> searchMap = new HashMap<>();
            searchMap.put("EQ_dicKey", "crm_activity_type");
            searchMap.put("EQ_dicValue", act.getActiveType());
            DictionaryListRequest dl = new DictionaryListRequest();
            dl.setPaging(new Page(1));
            dl.setSearchParams(searchMap);
            DictionaryListResponse dls = dictionary.getDictionaryList(dl);
            if (null != dls.getObjectList() && !dls.getObjectList().isEmpty()) {
                descList.add("活动类型(" + dls.getObjectList().get(0).getDicName() + ")");
            }
        }
        if (null != act.getTotalPriceLower() || null != act.getTotalPriceHigher()) {
            String priceStr = "总价(";
            if (null != act.getTotalPriceLower()) {
                priceStr += act.getTotalPriceLower() + "-";
            }
            if (null != act.getTotalPriceHigher()) {
                priceStr += act.getTotalPriceHigher();
            }
            descList.add(priceStr);
        }
        if (!Strings.isNullOrEmpty(act.getActName())) {
            String actName = "活动名称(" + act.getActName() + ")";
            descList.add(actName);
        }
        if (!Strings.isNullOrEmpty(act.getChannelName())) {
            String channelName = "物业类型(" + act.getChannelName() + ")";
            descList.add(channelName);
        }
        if (!Strings.isNullOrEmpty(act.getMobile())) {
            String mobile = "客户电话(" + act.getMobile() + ")";
            descList.add(mobile);
        }
        if (!Strings.isNullOrEmpty(act.getBlockName())) {
            String blockName = "区属(" + act.getBlockName() + ")";
            descList.add(blockName);
        }
        if (!Strings.isNullOrEmpty(act.getDistrictName())) {
            String districtName = "板块(" + act.getDistrictName() + ")";
            descList.add(districtName);
        }
        if (null != act.getAreaLower() || null != act.getAreaHigher()) {
            String areaStr = "面积(";
            if (null != act.getAreaLower()) {
                areaStr += act.getAreaLower() + "-";
            }
            if (null != act.getAreaHigher()) {
                areaStr += act.getAreaHigher();
            }
            descList.add(areaStr);
        }
        if (null != act.getReturnVisitTimeStart() && null != act.getReturnVisitTimeEnd()) {
            descList.add("回访时间(" + DateTimeUtils.parseDate(act.getReturnVisitTimeStart(),
                    DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT) + "-" + DateTimeUtils.parseDate(
                    act.getReturnVisitTimeEnd(), DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT) + ")");
        }
        if (null != act.getReturnVisitStatus()) {
            Map<String, Object> searchMap = new HashMap<>();
            searchMap.put("EQ_dicKey", "crm_visit_status");
            searchMap.put("EQ_dicValue", act.getReturnVisitStatus());
            DictionaryListRequest dl = new DictionaryListRequest();
            dl.setPaging(new Page(1));
            dl.setSearchParams(searchMap);
            DictionaryListResponse dls = dictionary.getDictionaryList(dl);
            if (null != dls.getObjectList() && !dls.getObjectList().isEmpty()) {
                descList.add("回访状态(" + dls.getObjectList().get(0).getDicName() + ")");
            }
        }
        if (null != act.getReturnVisitResult()) {
            Map<String, Object> searchMap = new HashMap<>();
            searchMap.put("EQ_dicKey", "crm_visit_result");
            searchMap.put("EQ_dicValue", act.getReturnVisitResult());
            DictionaryListRequest dl = new DictionaryListRequest();
            dl.setPaging(new Page(1));
            dl.setSearchParams(searchMap);
            DictionaryListResponse dls = dictionary.getDictionaryList(dl);
            if (null != dls.getObjectList() && !dls.getObjectList().isEmpty()) {
                descList.add("回访结果(" + dls.getObjectList().get(0).getDicName() + ")");
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(act.getSeeProjectName())) {
            descList.add("浏览项目(" + act.getSeeProjectName() + ")");
        }
        if (null != act.getSeeStartTime() && null != act.getSeeEndTime()) {
            descList.add("访问时间(" + DateTimeUtils.parseDate(act.getSeeStartTime(),
                    DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT) + "-" + DateTimeUtils.parseDate(
                    act.getSeeEndTime(), DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT) + ")");
        }
        if (act.getSeeCount() > 0) {
            descList.add("浏览次数(" + act.getSeeCount() + ")");
        }

        return Joiner.on("<br>").join(descList);
    }

    private MarketCustomerListResponse getAbandonList(Integer activeId, Integer limit) {
        Page page = new Page(limit);
        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("EQ_isabandon", "1");
        searchParams.put("EQ_activeId", activeId);
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getTotalCount(listRequest);
    }

    private MarketCustomerListResponse callAndAbandon(Integer activeId, Integer limit) {
        Page page = new Page(limit);
        Map<String, Object> searchParams = new HashMap<>(10);
        searchParams.put("EQ_callAndAbandon", "1");
        searchParams.put("EQ_activeId", activeId);
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getTotalCount(listRequest);
    }

    private MarketCustomerListResponse getnotassignList(Integer activeId, Integer limit) {
        Page page = new Page(limit);
        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("EQ_notassign", "1");
        searchParams.put("EQ_activeId", activeId);
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getTotalCount(listRequest);
    }

    private MarketCustomerListResponse getAssignedList(Integer activeId, Integer limit) {
        Page page = new Page(limit);
        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("EQ_assigned", "1");
        searchParams.put("EQ_activeId", activeId);
        searchParams.put("NOTEQ_status", "3");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getMarketCustomerList(listRequest);
    }

    private void wrapNameValuePairList(MarketingActivityVo vo, List<NameValuePair> nameValuePairList, MarketingActivityEntity entity) {
        // 楼盘ID
        String[] builds = vo.getBuildingId().split(",");
        int j = 0;
        for (String build : builds) {
            if (!Strings.isNullOrEmpty(build)) {
                nameValuePairList.add(new BasicNameValuePair("project_ids[" + j + "]", build));
                j++;
            }
        }

        if (!Strings.isNullOrEmpty(entity.getBlock())) {
            nameValuePairList.add(new BasicNameValuePair("target_block[]", entity.getBlock()));
        }

        if (!Strings.isNullOrEmpty(entity.getDistrict())) {
            nameValuePairList.add(new BasicNameValuePair("target_district[]", entity.getDistrict()));
        }

        if (!Strings.isNullOrEmpty(entity.getChannel())) {
            nameValuePairList.add(new BasicNameValuePair("target_property", entity.getChannel()));
        }

        if (!Strings.isNullOrEmpty(entity.getActName())) {
            nameValuePairList.add(new BasicNameValuePair("activity_name", entity.getActName()));
        }

        if (!Strings.isNullOrEmpty(entity.getMobile())) {
            nameValuePairList.add(new BasicNameValuePair("phone_number", entity.getMobile()));
        }

        if (!Strings.isNullOrEmpty(vo.getBuildingName())) {
            entity.setProjectName(vo.getBuildingName());
        }

        //电话类型
        if (entity.getMobileType() != null && !Strings.isNullOrEmpty(String.valueOf(entity.getMobileType()))) {
            nameValuePairList.add(new BasicNameValuePair("phone_type", String.valueOf(entity.getMobileType())));
        }

        //报名来源
        if (!Strings.isNullOrEmpty(String.valueOf(entity.getApplySource()))) {
            String[] sources = entity.getApplySource().split(",");
            int i = 0;
            for (String source : sources) {
                if (!Strings.isNullOrEmpty(source)) {
                    nameValuePairList.add(new BasicNameValuePair("target_source[" + i + "]", source));
                    i++;
                }
            }
        }

        //报名时间
        if (entity.getApplyStartTime() != null && entity.getApplyEndTime() != null) {
            nameValuePairList.add(new BasicNameValuePair("join_time[0]",
                    DateTimeUtils.parseDate(entity.getApplyStartTime(),
                            DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT)));
            nameValuePairList.add(new BasicNameValuePair("join_time[1]",
                    DateTimeUtils.parseDate(entity.getApplyEndTime(),
                            DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT)));
        }

        //活动类型
        if (entity.getActiveType() != null) {
            nameValuePairList.add(new BasicNameValuePair("activity_type", String.valueOf(entity.getActiveType())));
        }

        if (entity.getTotalPriceLower() != null && entity.getTotalPriceLower() != null) {
            nameValuePairList.add(
                    new BasicNameValuePair("total_price[0]", String.valueOf(entity.getTotalPriceLower())));
            nameValuePairList.add(
                    new BasicNameValuePair("total_price[1]", String.valueOf(entity.getTotalPriceHigher())));
        }

        if (entity.getAreaLower() != null && entity.getAreaHigher() != null) {
            nameValuePairList.add(new BasicNameValuePair("total_area[0]", String.valueOf(entity.getAreaLower())));
            nameValuePairList.add(new BasicNameValuePair("total_area[1]", String.valueOf(entity.getAreaHigher())));
        }

        if (entity.getReturnVisitTimeStart() != null && entity.getReturnVisitTimeEnd() != null) {
            nameValuePairList.add(
                    new BasicNameValuePair("visit_time[0]", String.valueOf(entity.getReturnVisitTimeStart())));
            nameValuePairList.add(
                    new BasicNameValuePair("visit_time[1]", String.valueOf(entity.getReturnVisitTimeEnd())));
        }

        if (entity.getReturnVisitStatus() != null) {
            nameValuePairList.add(
                    new BasicNameValuePair("visit_status", String.valueOf(entity.getReturnVisitStatus())));
        }

        if (!Strings.isNullOrEmpty(entity.getReturnVisitResult())) {
            nameValuePairList.add(new BasicNameValuePair("visit_result[]", String.valueOf(entity.getReturnVisitResult())));
        }


    }

    private void wrapMap(MarketingActivityEntity entity, Map<String, Object> paraMap) {
        //电话类型
        if (entity.getMobileType() != null && !Strings.isNullOrEmpty(String.valueOf(entity.getMobileType()))) {
            paraMap.put("phone_type", String.valueOf(entity.getMobileType()));
        }

        //报名来源
        if (!Strings.isNullOrEmpty(String.valueOf(entity.getApplySource()))) {
            String[] sources = entity.getApplySource().split(",");
            int i = 0;
            for (String source : sources) {
                if (!Strings.isNullOrEmpty(source)) {
                    paraMap.put("target_source[" + i + "]", source);
                    i++;
                }
            }
        }

        //报名时间
        if (entity.getApplyStartTime() != null && entity.getApplyEndTime() != null) {
            paraMap.put("join_time[0]", DateTimeUtils.parseDate(entity.getApplyStartTime(),
                    DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT));
            paraMap.put("join_time[1]", DateTimeUtils.parseDate(entity.getApplyEndTime(),
                    DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT));
        }

        if (!Strings.isNullOrEmpty(entity.getBlock())) {
            paraMap.put("target_block[]", entity.getBlock());
        }

        if (!Strings.isNullOrEmpty(entity.getDistrict())) {
            paraMap.put("target_district[]", entity.getDistrict());
        }

        if (!Strings.isNullOrEmpty(entity.getChannel())) {
            paraMap.put("target_property", entity.getChannel());
        }

        if (!Strings.isNullOrEmpty(entity.getActName())) {
            paraMap.put("activity_name", entity.getActName());
        }

        if (!Strings.isNullOrEmpty(entity.getMobile())) {
            paraMap.put("phone_number", entity.getMobile());
        }

        //活动类型
        if (entity.getActiveType() != null) {
            paraMap.put("activity_type", String.valueOf(entity.getActiveType()));
        }

        if (entity.getTotalPriceLower() != null && entity.getTotalPriceLower() != null) {
            paraMap.put("total_price[0]", String.valueOf(entity.getTotalPriceLower()));
            paraMap.put("total_price[1]", String.valueOf(entity.getTotalPriceHigher()));
        }

        if (entity.getAreaLower() != null && entity.getAreaHigher() != null) {
            paraMap.put("total_area[0]", String.valueOf(entity.getAreaLower()));
            paraMap.put("total_area[1]", String.valueOf(entity.getAreaHigher()));
        }

        if (entity.getReturnVisitTimeStart() != null && entity.getReturnVisitTimeEnd() != null) {
            paraMap.put("visit_time[0]", String.valueOf(entity.getReturnVisitTimeStart()));
            paraMap.put("visit_time[1]", String.valueOf(entity.getReturnVisitTimeEnd()));
        }

        if (entity.getReturnVisitStatus() != null) {
            paraMap.put("visit_status", String.valueOf(entity.getReturnVisitStatus()));
        }

        if (entity.getReturnVisitResult() != null) {
            paraMap.put("visit_result", String.valueOf(entity.getReturnVisitResult()));
        }
    }

    @RequestMapping(value = "/putOvertimeWaitCallToOcean")
    @ResponseBody
    public String putOvertimeWaitCallToOcean() {
        marketingActivity.putOvertimeWaitCallToOcean();
        System.out.println("----------定时putOvertimeWaitCallToOcean成功---------");
        return "----------putOvertimeWaitCallToOcean success---------";
    }
}
