package com.test;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.beans.vo.LocalReportFormVo;
import com.house365.beans.vo.MarketingActivityVo;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.web.util.SpringContextUtil;
import com.house365.web.util.ThreadPoolManager;
import com.house365.ws.beans.request.CustomerListRequest;
import com.house365.ws.beans.request.CustomerUserListRequest;
import com.house365.ws.beans.request.DepartmentListRequest;
import com.house365.ws.beans.request.UserSourceStatisticsListRequest;
import com.house365.ws.beans.response.CustomerUserListResponse;
import com.house365.ws.beans.response.DepartmentListResponse;
import com.house365.ws.beans.response.SourceStatisticsListResponse;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.interfaces.rest.ICustomerWechat;
import com.house365.ws.interfaces.rest.IGetRecommendList;
import com.house365.ws.interfaces.rest.IProjectWechat;
import com.house365.ws.interfaces.server.*;
import com.house365.ws.service.interfaces.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.net.URLEncoder;
import java.util.*;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Date: 16/8/8</p>
 *
 * @author XN
 * @version 1.0
 */
//@ContextConfiguration(locations = {"classpath*:unittest/application/applicationContext*.xml"})
@ContextConfiguration(locations = {"classpath*:application/applicationContext*.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class ServiceIT extends Assert {
    @Autowired
    IReportChannelDepartRelService<ReportChannelDepartRelEntity> reportChannelDepartRelService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ICustomerStatusLogService customerStatusLogService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IStatisticService statisticService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ICustomerProjectService customerProjectService;
    @Autowired
    private ICustomer customer;
    @Autowired
    private IUserSourceStatistics userSourceStatistics;
    @Autowired
    private IProjectSourceStatisticsService projectSourceStatisticsService;
    @Autowired
    private IProjectUserService projectUserService;
    @Autowired
    private ICustomerWechat customerWechat;
    @Autowired
    private IProjectWechat iProjectWechat;
    @Autowired
    private IUserService userService;
    @Autowired
    private ICustomerUserService customerUserService;
    @Autowired
    private ICustomerUser customerUser;
    @Autowired
    private IUser user;
    @Autowired
    private IDepartment department;
    @Autowired
    private ILocalReportService localReportService;
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private IBaseTreeService baseTreeService;
    @Autowired
    private ICrmSourceService crmSourceService;
    @Autowired
    private IBaseTree baseTree;
    @Autowired
    private IDictionary dictionary;
    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private IMarketingActivity marketingActivity;
    @Autowired
    private IMarketingActivityService marketingActivityService;
    @Autowired
    private RedisUtilsInterface redisUtils;
    @Autowired
    private IMarketCustomerService marketCustomerService;
    @Autowired
    private ICrmSource crmSource;
    @Autowired
    private IHouseInfoService houseInfoService;
    @Autowired
    private IMarketBuildingRelService marketBuildingRelService;
    @Value("${CRM.CUSTOMERQUERY.URL}")
    private String crmQueryURL;
    private String configStr = "{\"activity_type\":{\"1\":\"常规活动\",\"2\":\"营销活动\",\"3\":\"临时活动\"},\"phone_type\":{\"1\":\"手机\",\"2\":\"固话\"},\"visit_status\":{\"1\":\"未回访\",\"2\":\"回访中\",\"3\":\"已回访\",\"4\":\"不回访\"},\"visit_result\":{\"1\":\"A\",\"2\":\"B\",\"3\":\"C\",\"4\":\"D\",\"5\":\"E\",\"31\":\"暂无意向\",\"32\":\"暂无资格\",\"33\":\"已购无意向\",\"34\":\"酱油党\",\"41\":\"未接通\",\"42\":\"关机\",\"43\":\"停机\",\"44\":\"非明确拒访\"},\"hierarchical_sources\":[{\"category_id\":1,\"category_pid\":0,\"category_name\":\"新房\",\"category_portal\":1,\"category_is_web\":1,\"sub_categories\":[{\"category_id\":29,\"category_pid\":1,\"category_name\":\"400电话\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":43,\"name\":\"400电话\"},{\"id\":112,\"name\":\"400电话-免费通话\"},{\"id\":124,\"name\":\"400电话-海外地产\"},{\"id\":199,\"name\":\"400电话-淘房客户端\"},{\"id\":225,\"name\":\"400电话-淘房触屏版\"},{\"id\":311,\"name\":\"400电话-在线购房\"},{\"id\":312,\"name\":\"400电话-在线购房-淘房客户端\"},{\"id\":313,\"name\":\"400电话-在线购房-淘房触屏版\"},{\"id\":338,\"name\":\"测试来源\"}]},{\"category_id\":30,\"category_pid\":1,\"category_name\":\"短信订阅\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":34,\"name\":\"短信订阅\"},{\"id\":46,\"name\":\"发送信息至手机\"},{\"id\":53,\"name\":\"短信订阅-淘房客户端\"},{\"id\":54,\"name\":\"短信订阅-别墅频道\"},{\"id\":60,\"name\":\"订阅退订\"},{\"id\":110,\"name\":\"短信订阅-微家\"},{\"id\":152,\"name\":\"365淘房网-短信订阅\"},{\"id\":160,\"name\":\"短信订阅-区域优惠\"},{\"id\":161,\"name\":\"订阅退订-区域优惠\"},{\"id\":217,\"name\":\"订阅退订-淘房客户端\"}]},{\"category_id\":31,\"category_pid\":1,\"category_name\":\"看房团\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":68,\"name\":\"预约看铺\"},{\"id\":107,\"name\":\"看房团-淘房客户端\"},{\"id\":111,\"name\":\"看房团-微家\"},{\"id\":113,\"name\":\"看房团-自由组团\"},{\"id\":119,\"name\":\"预约看房\"},{\"id\":125,\"name\":\"看房团-频道\"},{\"id\":141,\"name\":\"预约看房-淘房客户端\"},{\"id\":145,\"name\":\"365淘房网-看房团-看房报名\"},{\"id\":146,\"name\":\"365淘房网-看房团-收藏\"},{\"id\":147,\"name\":\"365淘房网-看房团-自由组团\"},{\"id\":175,\"name\":\"预约到场\"},{\"id\":176,\"name\":\"预约到场-淘房客户端\"},{\"id\":222,\"name\":\"看房团-淘房触屏版\"},{\"id\":223,\"name\":\"预约看房-淘房触屏版\"},{\"id\":226,\"name\":\"预约到场-淘房触屏版\"},{\"id\":301,\"name\":\"看房团-快捷报名\"},{\"id\":314,\"name\":\"预约看房-在线购房\"},{\"id\":315,\"name\":\"预约看房-在线购房-淘房客户端\"},{\"id\":316,\"name\":\"预约看房-在线购房-淘房触屏版\"}]},{\"category_id\":32,\"category_pid\":1,\"category_name\":\"楼盘\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":42,\"name\":\"给开发商留言\"},{\"id\":45,\"name\":\"我要求购\"},{\"id\":52,\"name\":\"热门楼盘-淘房客户端\"},{\"id\":97,\"name\":\"网上房地产\"},{\"id\":121,\"name\":\"海外地产-问答\"},{\"id\":122,\"name\":\"海外地产-我要预约\"},{\"id\":208,\"name\":\"365淘房网-淘房拍\"},{\"id\":216,\"name\":\"淘房拍-淘房客户端\"},{\"id\":224,\"name\":\"淘房拍-淘房触屏版\"},{\"id\":237,\"name\":\"嘀嘀找房-淘房客户端\"},{\"id\":244,\"name\":\"新房纠错\"},{\"id\":245,\"name\":\"新房推广\"}]},{\"category_id\":33,\"category_pid\":1,\"category_name\":\"金融\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":108,\"name\":\"贷款产品-安家福贷\"},{\"id\":114,\"name\":\"金融超市-贷款人信息\"},{\"id\":115,\"name\":\"金融超市-贷款订单\"},{\"id\":148,\"name\":\"365淘房网-贷款\"},{\"id\":154,\"name\":\"金融超市-淘房客户端\"},{\"id\":248,\"name\":\"安家贷计算器-淘房触屏版\"},{\"id\":230,\"name\":\"安家贷计算器\"}]},{\"category_id\":34,\"category_pid\":1,\"category_name\":\"会员中心\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":4,\"name\":\"南京楼市会员\"},{\"id\":5,\"name\":\"商业地产投资者俱乐部\"},{\"id\":103,\"name\":\"登录-淘房客户端\"},{\"id\":143,\"name\":\"365淘房网-登陆\"},{\"id\":144,\"name\":\"365淘房网-注册\"},{\"id\":153,\"name\":\"注册-淘房客户端\"},{\"id\":167,\"name\":\"手机注册-商业地产\"},{\"id\":169,\"name\":\"打卡-淘房客户端\"},{\"id\":174,\"name\":\"注册-淘房客户端-移动推广\"},{\"id\":218,\"name\":\"登录-淘房触屏版\"},{\"id\":219,\"name\":\"注册-淘房触屏版\"},{\"id\":254,\"name\":\"积分兑换-淘房客户端\"}]},{\"category_id\":35,\"category_pid\":1,\"category_name\":\"活动\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":66,\"name\":\"优惠活动-淘房客户端\"},{\"id\":177,\"name\":\"品牌活动-线上\"},{\"id\":179,\"name\":\"品牌活动-游戏\"},{\"id\":247,\"name\":\"摇福利-淘房客户端\"},{\"id\":253,\"name\":\"活动-淘房触屏版\"},{\"id\":255,\"name\":\"大转盘-淘房客户端\"},{\"id\":261,\"name\":\"购房优惠券\"},{\"id\":262,\"name\":\"购房返现\"}]},{\"category_id\":36,\"category_pid\":1,\"category_name\":\"微信活动\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":137,\"name\":\"微信活动\"},{\"id\":234,\"name\":\"微信活动-新媒体\"},{\"id\":257,\"name\":\"微信活动-都市圈\"}]},{\"category_id\":37,\"category_pid\":1,\"category_name\":\"微信产品\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[]},{\"category_id\":38,\"category_pid\":1,\"category_name\":\"社群导入\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[]}]},{\"category_id\":2,\"category_pid\":0,\"category_name\":\"房博士\",\"category_portal\":1,\"category_is_web\":1,\"sub_categories\":[]},{\"category_id\":3,\"category_pid\":0,\"category_name\":\"电商\",\"category_portal\":1,\"category_is_web\":1,\"sub_categories\":[{\"category_id\":39,\"category_pid\":3,\"category_name\":\"团立方\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":30,\"name\":\"团立方-约惠团\"},{\"id\":44,\"name\":\"团立方-特价房\"},{\"id\":51,\"name\":\"特价房-淘房客户端\"},{\"id\":57,\"name\":\"团立方-特价房-我要求购\"},{\"id\":59,\"name\":\"特价房\"},{\"id\":61,\"name\":\"团立方-淘房汇\"},{\"id\":62,\"name\":\"团立方-淘房汇-我要求购\"},{\"id\":67,\"name\":\"团立方-约惠团-我要求购\"},{\"id\":69,\"name\":\"团立方-淘房支付\"},{\"id\":82,\"name\":\"团立方-商家加盟\"},{\"id\":149,\"name\":\"365淘房网-团立方-团购报名\"},{\"id\":150,\"name\":\"365淘房网-团立方-收藏\"},{\"id\":151,\"name\":\"365淘房网-团立方-赚取佣金\"},{\"id\":221,\"name\":\"特价房-淘房触屏版\"}]}]},{\"category_id\":4,\"category_pid\":0,\"category_name\":\"资讯\",\"category_portal\":1,\"category_is_web\":1,\"sub_categories\":[{\"category_id\":40,\"category_pid\":4,\"category_name\":\"专题\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":1,\"name\":\"看房团-专题\"},{\"id\":48,\"name\":\"新闻专题\"},{\"id\":228,\"name\":\"快速专题-淘房客户端\"},{\"id\":229,\"name\":\"快速专题-淘房触屏版\"}]},{\"category_id\":41,\"category_pid\":4,\"category_name\":\"活动\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":258,\"name\":\"资讯活动-淘房客户端\"}]},{\"category_id\":42,\"category_pid\":4,\"category_name\":\"微信活动\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":235,\"name\":\"微信活动-资讯\"}]},{\"category_id\":43,\"category_pid\":4,\"category_name\":\"微信产品\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[]}]},{\"category_id\":5,\"category_pid\":0,\"category_name\":\"社区\",\"category_portal\":1,\"category_is_web\":1,\"sub_categories\":[{\"category_id\":44,\"category_pid\":5,\"category_name\":\"BBS\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":7,\"name\":\"版主申请\"},{\"id\":37,\"name\":\"看房团-活动帖\"},{\"id\":40,\"name\":\"投票报名\"},{\"id\":83,\"name\":\"BBS报名帖\"},{\"id\":136,\"name\":\"新房团购-BBS\"}]},{\"category_id\":45,\"category_pid\":5,\"category_name\":\"社区活动\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":6,\"name\":\"业主聚会\"},{\"id\":8,\"name\":\"茶坊之夜\"},{\"id\":9,\"name\":\"K歌大赛\"},{\"id\":10,\"name\":\"一卡通\"},{\"id\":38,\"name\":\"版主聚会\"},{\"id\":39,\"name\":\"茶坊活动\"},{\"id\":41,\"name\":\"业主通讯录\"},{\"id\":49,\"name\":\"社区业主\"},{\"id\":55,\"name\":\"其他活动\"},{\"id\":56,\"name\":\"体育竞赛\"},{\"id\":58,\"name\":\"社区聚会\"},{\"id\":64,\"name\":\"鸠兹卡\"},{\"id\":65,\"name\":\"活动项目管理\"},{\"id\":170,\"name\":\"其他活动-淘房客户端\"}]},{\"category_id\":46,\"category_pid\":5,\"category_name\":\"微信活动\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":236,\"name\":\"微信活动-社区\"}]},{\"category_id\":47,\"category_pid\":5,\"category_name\":\"微信产品\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[]},{\"category_id\":48,\"category_pid\":5,\"category_name\":\"社群兴趣\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[]},{\"category_id\":49,\"category_pid\":5,\"category_name\":\"社群导入\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":263,\"name\":\"微信社群\"}]},{\"category_id\":50,\"category_pid\":5,\"category_name\":\"会员中心\",\"category_portal\":1,\"category_is_web\":1,\"sources\":[{\"id\":98,\"name\":\"手机注册\"}]}]},{\"category_id\":6,\"category_pid\":0,\"category_name\":\"电商平台\",\"category_portal\":1,\"category_is_web\":2,\"sub_categories\":[{\"category_id\":51,\"category_pid\":6,\"category_name\":\"电商客户\",\"category_portal\":1,\"category_is_web\":2,\"sources\":[{\"id\":198,\"name\":\"电商客户报备-拓客\"},{\"id\":201,\"name\":\"电商客户报备-驻场\"},{\"id\":202,\"name\":\"电商客户报备-渠道\"},{\"id\":231,\"name\":\"电商客户-自然\"}]}]},{\"category_id\":7,\"category_pid\":0,\"category_name\":\"采购渠道\",\"category_portal\":1,\"category_is_web\":2,\"sub_categories\":[{\"category_id\":52,\"category_pid\":7,\"category_name\":\"商业渠道\",\"category_portal\":1,\"category_is_web\":2,\"sources\":[{\"id\":2,\"name\":\"房展会\"},{\"id\":128,\"name\":\"展会\"},{\"id\":130,\"name\":\"驻场/巡展\"},{\"id\":131,\"name\":\"路演\"},{\"id\":132,\"name\":\"讲座\"},{\"id\":133,\"name\":\"放电影\"},{\"id\":135,\"name\":\"名录\"}]},{\"category_id\":53,\"category_pid\":7,\"category_name\":\"企业渠道\",\"category_portal\":1,\"category_is_web\":2,\"sources\":[]}]},{\"category_id\":8,\"category_pid\":0,\"category_name\":\"电销数据\",\"category_portal\":1,\"category_is_web\":2,\"sub_categories\":[{\"category_id\":54,\"category_pid\":8,\"category_name\":\"数据营销\",\"category_portal\":1,\"category_is_web\":2,\"sources\":[{\"id\":70,\"name\":\"自定义营销\"},{\"id\":200,\"name\":\"数据合作\"},{\"id\":300,\"name\":\"精拓系统\"},{\"id\":303,\"name\":\"自动匹配\"}]},{\"category_id\":55,\"category_pid\":8,\"category_name\":\"数据回访\",\"category_portal\":1,\"category_is_web\":2,\"sources\":[{\"id\":71,\"name\":\"指定回访\"},{\"id\":249,\"name\":\"跟进回访\"}]},{\"category_id\":56,\"category_pid\":8,\"category_name\":\"条口共建\",\"category_portal\":1,\"category_is_web\":2,\"sources\":[{\"id\":93,\"name\":\"手动报名\"},{\"id\":162,\"name\":\"数据流转\"}]}]},{\"category_id\":9,\"category_pid\":0,\"category_name\":\"活动问卷\",\"category_portal\":1,\"category_is_web\":2,\"sub_categories\":[{\"category_id\":57,\"category_pid\":9,\"category_name\":\"手机问卷\",\"category_portal\":1,\"category_is_web\":2,\"sources\":[{\"id\":184,\"name\":\"手机问卷-看房\"},{\"id\":185,\"name\":\"手机问卷-案场\"},{\"id\":186,\"name\":\"手机问卷-渠道\"},{\"id\":187,\"name\":\"手机问卷-刮刮乐\"}]},{\"category_id\":58,\"category_pid\":9,\"category_name\":\"现场问卷\",\"category_portal\":1,\"category_is_web\":2,\"sources\":[{\"id\":78,\"name\":\"批量导入\"},{\"id\":129,\"name\":\"派单\"},{\"id\":134,\"name\":\"其他活动\"},{\"id\":142,\"name\":\"看房团\"},{\"id\":178,\"name\":\"品牌活动-线下\"},{\"id\":304,\"name\":\"手动录入\"}]}]},{\"category_id\":10,\"category_pid\":0,\"category_name\":\"系统工具\",\"category_portal\":1,\"category_is_web\":2,\"sub_categories\":[{\"category_id\":59,\"category_pid\":10,\"category_name\":\"房管家\",\"category_portal\":1,\"category_is_web\":2,\"sources\":[{\"id\":126,\"name\":\"房管家客户端-置业顾问\"},{\"id\":127,\"name\":\"房管家客户端-经纪人\"}]}]}],\"target_sources\":[34,301]}";

    @Autowired
    private IGetRecommendList getRecommendList;

    @Test
    public void testGetRecommendList(){
        Map<String,Object> searchMap = new HashMap<>();
        searchMap.put("page","1");
        searchMap.put("pagesize","10");
        searchMap.put("city","nj");
        searchMap.put("userId","1");
        searchMap.put("evaluateTimeStart","2018-04-01");
        searchMap.put("evaluateTimeEnd","2018-06-01");
        searchMap.put("userName","1");
        searchMap.put("projectName","1");

        Parameter parameter = new Parameter();
        parameter.setArgs(searchMap);

        try {
            getRecommendList.exectue(parameter);
        } catch (ServiceRunException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testGetuserByProjectShort(){
        projectService.updateSaler();
//        Map<String,Object> queryMap = new HashMap<>();
//        queryMap.put("city","wh");
//        queryMap.put("short","195338");
//        List<UserEntity> userEntities = userService.getUserByPorjectShort(queryMap);
//        for(UserEntity user:userEntities){
//            logger.info("[{}]",user.getRealName());
//        }
    }

    @Test
    public void testGetCrm(){
        Map<String,String> map = new HashMap<>();
        map.put("state","1,2");
        map.put("month","2018-04");
        map.put("city","nj");
        customerService.crmVisitAndSignCustomer(map);
    }

    @Test
    public void testGetCount(){
        Date today = DateTimeUtils.getToday(new Date());
        Map<String, Object> callSearchParams = new HashMap<>();
        callSearchParams.put("EQ_cityCode","nj");
        callSearchParams.put("EQ_userId","1");
        callSearchParams.put("EQ_isDelete", "0");
//        callSearchParams.put("EQ_normalCall", "1");
//        callSearchParams.put("EQ_totalCall", "1");
        callSearchParams.put("EQ_allCall", "1");
        callSearchParams.put("GTE_callTimeStart", today);
        CustomerListRequest totalCount = new CustomerListRequest();
        totalCount.setPaging(new Page(Integer.MAX_VALUE));
        totalCount.setSearchParams(callSearchParams);
        totalCount.setPaging(new Page(Integer.MAX_VALUE));
        Integer cont = customer.getTotalCallOptimize(totalCount);

        System.out.println(cont);
    }

    @Test
    public void getListByCategory() {
        List<CrmSourceEntity> list = crmSourceService.getListByCategory("2");
        System.out.println("===" + list.size());

    }

    @Test
    public void testGetMarketInfo() {
        CustomerListRequest customerListRequest = new CustomerListRequest();
        List<Map<String, Object>> list = customer.getMarketInfo(customerListRequest);
        System.out.println(list.size());
    }

    @Test
    public void testCRMQueryURL() {
        Integer actId = 46;
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        String url = crmQueryURL + "?";

        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("EQ_activeId", actId);
        QueryParams queryParams = new QueryParams();
        queryParams.setSearchParams(searchMap);

        MarketingActivityEntity activity = (MarketingActivityEntity) marketingActivityService.getById(actId);
        List<MarketBuildingRelEntity> relList = marketBuildingRelService.queryAll(queryParams);
        List<String> buildIds = new ArrayList<>();
        for (MarketBuildingRelEntity entity : relList) {
            buildIds.add(String.valueOf(entity.getBuildingId()));
        }

        MarketingActivityVo vo = new MarketingActivityVo();
        vo.setEntity(activity);
        vo.setBuildingId(Joiner.on(",").join(buildIds));

        wrapNameValuePairList(vo, nameValuePairList, activity);

        List<String> params = new ArrayList<>();
        for (NameValuePair pair : nameValuePairList) {
            params.add(pair.getName() + "=" + pair.getValue());
        }

        url += Joiner.on("&").join(params);
        logger.info("URL===[{}]", url);
    }

    @Test
    public void testPutOverTimeToOcean() {
        marketingActivityService.putOvertimeToOcean();
    }

    @Test
    public void testUpdateHouseName() {
        houseInfoService.updateHouseNameByActiveId(11, "nj");
    }

    @Test
    public void testGetConfig() {
        crmSource.refreshCrmConfig();
    }

    @Test
    public void testImportActivity() {

        ThreadPoolManager.addExecuteTask(new Runnable() {
            @Override
            public void run() {
                RedisUtilsInterface redisUtil = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");
                for (int i = 0; i < 10000; i++) {
                    logger.info("========cache count :[{}]", redisUtil.getIntegerByKey("active:done:1"));
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        marketCustomerService.clean();
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("city", "nj");
        paraMap.put("project_ids[]", "1402");
        House365RestObject restObject = new House365RestObject();
        restObject.setTotal("25");
        restObject.setParaMap(paraMap);
        restObject.setEntity(1);
//        marketingActivity.importCustomers(restObject);

    }

    @Test
    public void testSetConfig() {
        JSONObject config = JSONObject.fromObject(configStr);
        Date createDate = new Date();

        if (config.containsKey("activity_type")) {
            JSONObject activityType = (JSONObject) config.get("activity_type");
            dictionaryService.deleteByKey("crm_activity_type");
            for (Object obj : activityType.entrySet()) {
                DictionaryEntity dictionaryEntity = new DictionaryEntity();
                dictionaryEntity.setDicKey("crm_activity_type");
                dictionaryEntity.setDicValue(String.valueOf(((ListOrderedMap.Entry) obj).getKey()));
                dictionaryEntity.setDicName((String) ((ListOrderedMap.Entry) obj).getValue());
                dictionaryEntity.setCity("nj");
                dictionaryService.save(dictionaryEntity);
            }
        }

        if (config.containsKey("phone_type")) {
            JSONObject phoneType = (JSONObject) config.get("phone_type");
            dictionaryService.deleteByKey("crm_phone_type");
            for (Object obj : phoneType.entrySet()) {
                DictionaryEntity dictionaryEntity = new DictionaryEntity();
                dictionaryEntity.setDicKey("crm_phone_type");
                dictionaryEntity.setDicValue(String.valueOf(((ListOrderedMap.Entry) obj).getKey()));
                dictionaryEntity.setDicName((String) ((ListOrderedMap.Entry) obj).getValue());
                dictionaryEntity.setCity("nj");
                dictionaryService.save(dictionaryEntity);
            }
        }

        if (config.containsKey("visit_status")) {
            JSONObject visitStatus = (JSONObject) config.get("visit_status");
            dictionaryService.deleteByKey("crm_visit_status");
            for (Object obj : visitStatus.entrySet()) {
                DictionaryEntity dictionaryEntity = new DictionaryEntity();
                dictionaryEntity.setDicKey("crm_visit_status");
                dictionaryEntity.setDicValue(String.valueOf(((ListOrderedMap.Entry) obj).getKey()));
                dictionaryEntity.setDicName((String) ((ListOrderedMap.Entry) obj).getValue());
                dictionaryEntity.setCity("nj");
                dictionaryService.save(dictionaryEntity);
            }
        }

        if (config.containsKey("visit_result")) {
            JSONObject visitStatus = (JSONObject) config.get("visit_result");
            dictionaryService.deleteByKey("crm_visit_result");
            for (Object obj : visitStatus.entrySet()) {
                DictionaryEntity dictionaryEntity = new DictionaryEntity();
                dictionaryEntity.setDicKey("crm_visit_result");
                dictionaryEntity.setDicValue(String.valueOf(((ListOrderedMap.Entry) obj).getKey()));
                dictionaryEntity.setDicName((String) ((ListOrderedMap.Entry) obj).getValue());
                dictionaryEntity.setCity("nj");
                dictionaryService.save(dictionaryEntity);
            }
        }

        if (config.containsKey("hierarchical_sources")) {
            baseTreeService.clean("crmSource");
            crmSourceService.truncateTable();
            JSONArray cates = (JSONArray) config.get("hierarchical_sources");
            for (Object obj : cates) {
                JSONObject cate = (JSONObject) obj;
                saveNode(createDate, cate);
                if (cate.containsKey("sub_categories")) {
                    JSONArray subCates = (JSONArray) cate.get("sub_categories");
                    for (Object source : subCates) {
                        JSONObject sourceCate = (JSONObject) source;
                        saveNode(createDate, sourceCate);
                        saveSource(createDate, sourceCate);
                    }
                }
            }
            baseTree.updateUrlPath(0);
        }

        logger.info("config size{}", config.size());
    }

    private void saveSource(Date createDate, JSONObject sourceCate) {
        if (sourceCate.containsKey("sources")) {
            JSONArray subCates = (JSONArray) sourceCate.get("sources");
            for (Object source : subCates) {
                CrmSourceEntity crmSourceEntity = new CrmSourceEntity();
                JSONObject sourceNode = (JSONObject) source;
                if (sourceNode.containsKey("id") && sourceNode.get("id") != null) {
                    crmSourceEntity.setSourceId((Integer) sourceNode.get("id"));
                }
                if (sourceCate.containsKey("category_id") && sourceCate.get("category_id") != null) {
                    crmSourceEntity.setCategoryId(Integer.valueOf((Integer) sourceCate.get("category_id")));
                }
                if (sourceNode.containsKey("name") && sourceNode.get("name") != null) {
                    crmSourceEntity.setSourceName(String.valueOf(sourceNode.get("name")));
                }
                crmSourceEntity.setCategoryPid((Integer) sourceCate.get("category_pid"));
                crmSourceEntity.setCategoryName((String) sourceCate.get("category_name"));
                crmSourceEntity.setCreateTime(createDate);
                crmSourceEntity.setCreater("system");
                crmSourceEntity.setStatus(1);
                crmSourceService.save(crmSourceEntity);
            }
        }

    }

    private void saveNode(Date createDate, JSONObject cate) {
        BaseTreeEntity baseTreeEntity = new BaseTreeEntity();
        baseTreeEntity.setParentId((Integer) cate.get("category_pid"));
        baseTreeEntity.setSourceId(String.valueOf(cate.get("category_id")));
        baseTreeEntity.setName((String) cate.get("category_name"));
        baseTreeEntity.setCreateTime(createDate);
        baseTreeEntity.setCreator("Admin");
        baseTreeEntity.setStatus("1");
        baseTreeEntity.setSourceType("crmSource");
        baseTreeService.save(baseTreeEntity);
    }

    @Test
    public void testLRStatistic() {

        Map<String, Object> map = new HashMap<>();
        map.put("EQ_projectId", "1,109");
        map.put("EQ_channelId", "3,4,6");
        map.put("EQ_departId", "2,69,70,72,73");
        map.put("EQ_groupby", "DATE_FORMAT(l.report_date, '%Y%u'),channel_id,departid");
        map.put("EQ_period", "DATE_FORMAT(l.report_date, '%Y%u') reportDate");

        QueryParams params = new QueryParams();
        params.setSearchParams(map);
        params.setPaging(new Page(1000));

        List<LocalReportFormVo> list = localReportService.statistic(params);
        logger.info("list size[{}]", list.size());
    }

    @Test
    public void testLR() {
        List<LocalReportFormVo> list = localReportService.queryFormVO("nj");
        logger.info("list size[{}]", list.size());
    }

    @Test
    public void testSendCardMessage() {
        String description = "<div class=\\\"gray\\\">2016年9月26日</div> <div class=\\\"normal\\\">恭喜你抽中iPhone 7一台，领奖码：xxxx</div><div class=\\\"highlight\\\">请于2016年10月10日前联系行政同事领取</div>";
        wechatService.sendCardTextMessage("264", "星辰大海", description, "http://www.baidu.com", "去看星星");
    }

    @Test
    public void del() {
        //        reportChannelDepartRelService.deleteByIds(1111, 2222);

        localReportService.cleanDayReportByProject("1", "2017-01-01");
    }

    @Test
    public void testGetChildDepartList() {
        List<DepartmentEntity> departmentEntities = user.getChildDepartList(1);
        logger.info("size {}", departmentEntities.size());
    }

    @Test
    public void testDept() {
        DepartmentListRequest de = new DepartmentListRequest();
        de.setPaging(new Page(1));

        DepartmentListResponse re = department.getDepartmentList(de);

        List<DepartmentEntity> ee = department.findChildrenListByPath(re.getObjectList());
        logger.info("list [{}]", ee.size());
    }

    @Test
    public void testGetUserListByDept() {
        //get user list
        Page page = new Page(20);

        // 获取查询条件
        Map<String, Object> searchParams = new HashMap<>();
        //        searchParams.put("LIKE_realName", "周");

        DepartmentEntity d = department.getDepartmentById(95).getEntity();

        List<UserEntity> departmentEntities = user.getUserListByDept(d, searchParams, page).getObjectList();
        logger.info("size {}", departmentEntities.size());
    }

    @Test
    public void testGetUserIdOnPath() {
        List<Integer> userIds = user.getUserIdOnPath(1);
        logger.info("size {}", userIds.size());
    }

    @Test
    public void getSummary() {
        Map<String, Object> map = user.getSummary("1");
        logger.info("size {}", map.size());
    }

    @Test
    public void removeStar() {
        customerUserService.removeStar(1, 1);
    }

    @Test
    public void testCustomerUserQuery() {
        Map<String, Object> search = new HashMap<>();
        search.put("IN_customerIds", Lists.newArrayList(1, 2, 3, 4, 5, 6, 7));
        search.put("EQ_userId", 1);
        CustomerUserListRequest cul = new CustomerUserListRequest();
        cul.setPaging(new Page(Integer.MAX_VALUE));
        cul.setSearchParams(search);
        CustomerUserListResponse res = customerUser.getCustomerUserList(cul);
    }

    @Test
    public void getMyCustomers() {
        Parameter parameter = new Parameter();
        Map<String, Object> map = new HashMap<>();

        String[] phones = {"13770685961"};
        map.put("pageNo", new String[] {"1"});
        map.put("pageSize", new String[] {"10"});
        map.put("phone", phones);
        map.put("queryType", new String[] {"4"});
        //        map.put("keyword", new String[]{"a"});
        //        map.put("buyIntention", new String[]{"1"});
        //        map.put("traceStatus", new String[]{"1"});
        map.put("customerStatus", new String[] {"1"});
        map.put("sign", new String[] {"unittest"});
        parameter.setArgs(map);
        try {
            String result = (String) customerWechat.getMyCustomerList(parameter);
            logger.info("result is [{}]", result);
        } catch (ServiceRunException e) {
            e.printStackTrace();
        }


    }

    @Test
    public void getWechatMyCucstomerUserSummary() {
        List<Map<String, Object>> res = customerService.getWechatMyCucstomerUserView("1", "0", "100");

        for (Map map : res) {
            for (Object entry : map.entrySet()) {
                Map.Entry entry1 = (Map.Entry) entry;
                logger.info("key :[{}], value :[{}]", entry1.getKey(), entry1.getValue());
            }
        }

    }

    @Test
    public void getUserIdOnPath() {
        List<Integer> ids = userService.getUserIdOnPath(1);
        logger.info("ids [{}]", ids.size());
    }

    @Test
    public void testGetMyCustomer() {
        Parameter parameter = new Parameter();
        try {
            String[] phones = {"13770685961"};
            Map<String, Object> map = new HashedMap();
            map.put("phone", phones);
            parameter.setArgs(map);
            String obj = (String) customerWechat.exectue(parameter);
            logger.info("testGetMyCustomer :{}", obj);

        } catch (ServiceRunException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testGetMyProject() {
        projectUserService.getProjectByUserId(1, null);
    }

    @Test
    public void testDel() {
        projectSourceStatisticsService.deleteByDate("2016-08-27 00:00:00");
    }

    @Test
    public void testUpdateSourceName() {
        customer.updateSourceName("75", "测试来源a本次1");
    }

    @Test
    public void testSaveLog() {
        CustomerStatusLogEntity customerStatusLogEntity = new CustomerStatusLogEntity();
        customerStatusLogEntity.setCreateTime(new Date());
        customerStatusLogEntity.setCreater("1");
        customerStatusLogEntity.setFromStatusName(null);
        customerStatusLogEntity.setFromStatusName(null);
        customerStatusLogEntity.setToStatusId(0);
        customerStatusLogEntity.setToStatusName("hello");
        customerStatusLogEntity.setCustomerId(1);
        customerStatusLogEntity.setRemark(null);

        customerStatusLogService.save(customerStatusLogEntity);
    }

    @Test
    public void testGetSummary() {
        Map<String, Object> s = customerService.getSummary("1");
        logger.info(s.toString());
    }

    @Test
    public void testGetDistinctReportName() {
        List map = (List) statisticService.getDistinctReportName("nj");
        for (Object entry : map) {
            logger.info("info [{}]", entry);
        }
    }

    @Test
    public void testQueryNotNull() {
        Set<Integer> ids = Sets.newHashSet(1, 2, 3, 4);
        Map<String, Object> searchMap = new HashedMap();
        QueryParams queryParams = new QueryParams();
        //        searchMap.put("ISNOTNULL_managerId","");
        //        searchMap.put("EQ_managerId","1");
        //        searchMap.put("GTE_createTimeStart", "2016-09-30");
        searchMap.put("IN_ids", Lists.newArrayList(ids));
        searchMap.put("EQ_recordedStatus", "1");
        queryParams.setSearchParams(searchMap);
        customerService.queryAll(queryParams);
    }

    @Test
    public void testGetMyCustomerList() {
        Map<String, Object> cpMap = new HashMap<>();
        //        cpMap.put("LIKE_houseName", "houseName");
        //        cpMap.put("EQ_recordedStatus", "recordedStatus");
        //        cpMap.put("EQ_status", "status");
        //        cpMap.put("EQ_loanStatus", "loanStatus");
        //        cpMap.put("EQ_urlPath", "1");
        cpMap.put("IN_customerPhones", Lists.newArrayList("137", "138"));
        QueryParams searchParams = new QueryParams(cpMap);
        customerProjectService.queryAll(searchParams);
    }

    @Test
    public void testGetCRMURL() {
//        customer.getCRMCustomerURL(73);
    }

    @Test
    public void testAddCustomerCRM() {

        String crmUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("CRM.CUSTOMER.ADD.URL");
        crmUrl += "mobile=13778787878";
        crmUrl += "&city=nj";
        crmUrl += "&activename=活动来源";
        crmUrl += "&activefrom=335";

        try {
            URLEncoder.encode(crmUrl, "gbk");
            String result = HttpClientUtil.getJsonData(crmUrl);
            logger.info("result :{}", result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testStatistic() {
        customerService.statisticTask();
    }

    @Test
    public void testUpdateName() {
        customerService.updateName();
    }

    @Test
    public void testUpdateProjectName() {
        customerProjectService.updateName(31, "33");
    }

    @Test
    public void testUserStatistic() {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("EQ_dayBaseRatio", "1");
        Page queryPage = new Page(20);

        UserSourceStatisticsListRequest pssl = new UserSourceStatisticsListRequest();
        pssl.setPaging(queryPage);
        pssl.setSearchParams(queryMap);
        pssl.setOrderColumn("createTime desc");
        pssl.setOrderMode(" ,customerStatus asc");
        SourceStatisticsListResponse pssr = userSourceStatistics.statisticCustomer(pssl, "1");

        logger.info("list size {}", pssr.getObjectList().size());
    }

    @Test
    public void updateCustomerActSource() {
        customer.updateSourceName("haha", "new");
    }

    @Test
    public void testSummary() {
        List<Map<String, Object>> list = new ArrayList<>();
        list = customerService.getNewCustomerIds("1");
        for (Map<String, Object> map : list) {
            logger.info("id[{}]", map.get("id"));
        }
        list = customerService.getTodayUpdateIds("1");
        for (Map<String, Object> map : list) {
            logger.info("id[{}]", map.get("id"));
        }
        list = customerService.getNocallSevenDayIds("1");
        for (Map<String, Object> map : list) {
            logger.info("id[{}]", map.get("id"));
        }
        list = customerService.getNocallThreeDayIds("1");
        for (Map<String, Object> map : list) {
            logger.info("id[{}]", map.get("id"));
        }
        list = customerService.getNoStatusUpdateIds("1");
        for (Map<String, Object> map : list) {
            logger.info("id[{}]", map.get("id"));
        }

    }

    @Test
    public void testSyncCRM() {
        customerService.sendCustomerToCRMJOB();


    }

    @Test
    public void testBackToSeaByStatusOverDaysTask() {
        customerService.backToSeaByStatusOverDaysTask();
    }

    @Test
    public void removeFromOcean() {
        customerService.removeFromOcean();
    }

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

        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 (!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(",");
            for (String source : sources) {
                if (!Strings.isNullOrEmpty(source)) {
                    nameValuePairList.add(new BasicNameValuePair("target_source[]", source));
                }
            }
        }

        //报名时间
        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 (entity.getReturnVisitResult() != null) {
            nameValuePairList.add(
                new BasicNameValuePair("visit_result", String.valueOf(entity.getReturnVisitResult())));
        }
    }
}
