package com.house365.ws.interfaces.impl;

import com.google.common.base.Joiner;
import com.house365.beans.entity.*;
import com.house365.commons.system.HttpClientUtil;
import com.house365.web.util.DateTimeUtils;
import com.house365.ws.beans.request.MapListRequest;
import com.house365.ws.beans.response.MapListResponse;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.dao.mapper.*;
import com.house365.ws.interfaces.server.ICloudActivityInterface;
import com.house365.ws.service.interfaces.ICheckNoCallCustomerNoLimit;
import com.house365.ws.service.interfaces.IStaffDuty;
import com.house365.ws.system.ReturnResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
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.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.house365.ws.service.impl.StaffDuty.getMonthDate;

/**
 * @author Created by Administrator on 2020/3/26.
 */
@Service("CloudActivity")
public class CloudActivityImpl implements ICloudActivityInterface {

    private static final Logger logger = LoggerFactory.getLogger(CloudActivityImpl.class);

    @Autowired
    private CloudActivityMapper mapper;
    @Autowired
    private CloudCustomerMapper cloudCustomerMapper;
    @Autowired
    private RedisUtilsInterface redisUtil;
    @Autowired
    private IStaffDuty staffDuty;
    @Autowired
    private ICheckNoCallCustomerNoLimit checkNoCallCustomerNoLimit;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CloudCountMapper cloudCountMapper;
    @Autowired
    private CustomerMergeMapper mergeMapper;
    @Value("${CLOUD.PULL.URL}")
    private String cloudPullUrl;

    @Override
    public int save(CloudActivityEntity entity) {
        mapper.save(entity);
        int id = entity.getId();
        return id;
    }

    @Override
    public MapListResponse list(MapListRequest request) {
        MapListResponse response = new MapListResponse();
        try {
            Map<String, Object> map = new HashMap<>(10);
            Map<String, Object> searchParams = request.getSearchParams();
            int start = 50 * (request.getPaging().getCurrentPage() - 1);
            map.put("city", searchParams.get("city"));
            map.put("start", start);
            map.put("limit", 50);
            map.put("name", searchParams.get("name"));
            int userId = Integer.parseInt(searchParams.get("userId").toString());
            if (userId != 1) {
                map.put("createId", userId);
            }
            map.put("type", 0);
            List<Map<String, Object>> list = mapper.queryList(map);
            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> m : list) {
                    int activeId = Integer.parseInt(m.get("id").toString());
                    Map<String, Object> searchMap = new HashMap<>(10);
                    searchMap.put("activeId", activeId);
                    List<CloudCustomerEntity> count = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("customerCount", count.size());
                    searchMap.put("type", 1);
                    List<CloudCustomerEntity> waitCountList = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("waitCount", waitCountList.size());
                    searchMap.put("type", 2);
                    List<CloudCustomerEntity> sentCountList = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("sentCount", sentCountList.size());
                    //置业顾问为空，则为公海客户
                    searchMap.put("isSea", 1);
                    List<CloudCustomerEntity> seaList = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("seaCount", seaList.size());

                    if (CollectionUtils.isNotEmpty(sentCountList)) {
                        //设置统计数目 已跟进  回公海  A/B意向数 约看数 到访数 认购数 签约数
                        String backKey = "cloud_back_count" + activeId;
                        String abKey = "cloud_ab_count" + activeId;
                        String seeKey = "cloud_see_count" + activeId;
                        String daoKey = "cloud_dao_count" + activeId;
                        String buyKey = "cloud_buy_count" + activeId;
                        String signKey = "cloud_sign_count" + activeId;
                        int backCount;
                        int abCount;
                        int seeCount;
                        int daoCount;
                        int buyCount;
                        int signCount;
                        if (!"null".equals(redisUtil.getValByKeyNew(backKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(backKey))) {
                            backCount = Integer.valueOf(redisUtil.getValByKeyNew(backKey));
                        } else {
                            backCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(abKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(abKey))) {
                            abCount = Integer.valueOf(redisUtil.getValByKeyNew(abKey));
                        } else {
                            abCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(seeKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(seeKey))) {
                            seeCount = Integer.valueOf(redisUtil.getValByKeyNew(seeKey));
                        } else {
                            seeCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(daoKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(daoKey))) {
                            daoCount = Integer.valueOf(redisUtil.getValByKeyNew(daoKey));
                        } else {
                            daoCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(buyKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(buyKey))) {
                            buyCount = Integer.valueOf(redisUtil.getValByKeyNew(buyKey));
                        } else {
                            buyCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(signKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(signKey))) {
                            signCount = Integer.valueOf(redisUtil.getValByKeyNew(signKey));
                        } else {
                            signCount = 0;
                        }
                        m.put("backCount", backCount);
                        m.put("abCount", abCount);
                        m.put("seeCount", seeCount);
                        m.put("daoCount", daoCount);
                        m.put("buyCount", buyCount);
                        m.put("signCount", signCount);
                    } else {
                        m.put("backCount", "0");
                        m.put("abCount", "0");
                        m.put("seeCount", "0");
                        m.put("daoCount", "0");
                        m.put("buyCount", "0");
                        m.put("signCount", "0");
                    }
                }
            }

            int count = mapper.queryCount(map);
            request.getPaging().setRecords(count);
            response.setPaging(request.getPaging());
            response.setObjectList(list);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(e.getMessage());
        }
        return response;
    }

    @Override
    public MapListResponse pullList(MapListRequest request) {
        MapListResponse response = new MapListResponse();
        try {
            Map<String, Object> map = new HashMap<>(10);
            Map<String, Object> searchParams = request.getSearchParams();
            int start = 50 * (request.getPaging().getCurrentPage() - 1);
            map.put("city", searchParams.get("city"));
            map.put("start", start);
            map.put("limit", 50);
            map.put("name", searchParams.get("name"));
            int userId = Integer.parseInt(searchParams.get("userId").toString());
            if (userId != 1) {
                map.put("createId", userId);
            }
            map.put("type", 1);
            List<Map<String, Object>> list = mapper.queryList(map);
            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> m : list) {
                    int activeId = Integer.parseInt(m.get("id").toString());
                    Map<String, Object> searchMap = new HashMap<>(10);
                    searchMap.put("activeId", activeId);
                    List<CloudCustomerEntity> count = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("customerCount", count.size());
                    searchMap.put("type", 1);
                    List<CloudCustomerEntity> waitCountList = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("waitCount", waitCountList.size());
                    searchMap.put("type", 2);
                    List<CloudCustomerEntity> sentCountList = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("sentCount", sentCountList.size());
                }
            }

            int count = mapper.queryCount(map);
            request.getPaging().setRecords(count);
            response.setPaging(request.getPaging());
            response.setObjectList(list);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(e.getMessage());
        }
        return response;
    }

//    @Override
//    public List<CloudCountEntity> reportList(Map<String, Object> searchParams) {
//        List<CloudCountEntity> list = new ArrayList<>();
//        try {
//            Date date = new Date();
//            String startTime = "";
//            String endTime = "";
//            String timeStart = "";
//            if(null != searchParams.get("startTime")){
//                timeStart = searchParams.get("startTime").toString();
//            }
//            if (StringUtils.isNotBlank(timeStart)) {
//                StringBuilder str = new StringBuilder().append(timeStart).append("-15").append(" 00:00:00");
//                String time = str.toString();
//                Date newDate = DateTimeUtils.getDateByString(time);
//                newDate =  DateTimeUtils.getUpdateDateTime(newDate,Calendar.MONTH,1);
//                Map<String, String> monthMap = getMonthDate(newDate);
//                startTime = monthMap.get("first");
//                endTime = monthMap.get("last");
//            } else {
//                Map<String, String> monthMap = getMonthDate(date);
//                startTime = monthMap.get("first");
//                endTime = monthMap.get("last");
//            }
//            Map<String, Object> map = new HashMap<>(10);
//            map.put("city", searchParams.get("city"));
//            map.put("name", searchParams.get("name"));
//            map.put("startTime", startTime);
//            map.put("endTime", endTime);
//            list = cloudCountMapper.queryByConditions(map);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return list;
//    }

    @Override
    public List<CloudCountEntity> reportList(Map<String, Object> searchParams) {
        List<CloudCountEntity> list = new ArrayList<>();
        try {
            Date date = new Date();
            String startTime = "";
            String endTime = "";
            if (null != searchParams.get("time")) {
                String time = searchParams.get("time").toString();
                startTime = time.split(",")[0];
                endTime = time.split(",")[1];
            }
            if (StringUtils.isBlank(startTime)) {
                return list;
            }
            Map<String, Object> map = new HashMap<>(10);
            if (null != searchParams.get("degree")) {
                String degree = searchParams.get("degree").toString();
                if ("y".equals(degree)) {
                    map.put("type", 3);
                } else if ("bn".equals(degree)) {
                    map.put("type", 2);
                } else if ("s".equals(degree)) {
                    map.put("type", 1);
                } else if ("m".equals(degree)) {
                    map.put("type", 0);
                }
            }
            map.put("city", searchParams.get("city"));
            map.put("name", searchParams.get("name"));
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            list = cloudCountMapper.queryByConditions(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public MapListResponse reportDetailList(MapListRequest request, int countId) {
        CloudCountEntity cloudCountEntity = cloudCountMapper.getById(countId);
        int type = cloudCountEntity.getType();
        MapListResponse response = new MapListResponse();
        Map<String, Object> map = new HashMap<>(10);
        Date date = cloudCountEntity.getCreateTime();
        date = DateTimeUtils.getUpdateDateTime(date, Calendar.MONTH, 1);
        Map<String, String> monthMap = getMonthDate(date);
        String startTime = "";
        String endTime = "";
        Date endDate;
        if (type == 0) {
            startTime = monthMap.get("first");
            endTime = monthMap.get("last");
        } else {
            Date createTime = cloudCountEntity.getCreateTime();
            createTime = DateTimeUtils.getUpdateDateTime(createTime, Calendar.DAY_OF_MONTH, -1);
            if (type == 1) {
                endDate = DateTimeUtils.getUpdateDateTime(createTime, Calendar.MONTH, 3);
            } else if (type == 2) {
                endDate = DateTimeUtils.getUpdateDateTime(createTime, Calendar.MONTH, 6);
            } else {
                endDate = DateTimeUtils.getUpdateDateTime(createTime, Calendar.MONTH, 12);
            }
            startTime = DateTimeUtils.getDateString(createTime, DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_FULL);
            endTime = DateTimeUtils.getDateString(endDate, DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_FULL);
        }
        Map<String, Object> searchParams = request.getSearchParams();
        map.put("city", searchParams.get("city"));
        int status = Integer.parseInt(searchParams.get("status").toString());
        int createId = Integer.parseInt(searchParams.get("createId").toString());
        map.put("createId", createId);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        List<CloudActivityEntity> activeListNew = mapper.queryByConditions(map);
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> subList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(activeListNew)) {
            List<Integer> actIdList = new ArrayList<>();
            for (CloudActivityEntity l : activeListNew) {
                actIdList.add(l.getId());
            }

            Map<String, Object> searchMap = new HashMap<>(10);
            searchMap.put("actIdList", actIdList);
            searchMap.put("type", 2);
            List<CloudCustomerEntity> sendList = cloudCustomerMapper.queryByConditions(searchMap);

            if (CollectionUtils.isNotEmpty(sendList)) {
                Map<String, Object> queryMap = new HashMap<>(10);
                queryMap.put("status", status);
                queryMap.put("createId", createId);
                queryMap.put("startTime", startTime);
                queryMap.put("endTime", endTime);
                list = staffDuty.queryListByStatus(sendList, queryMap);
                int total = list.size();

                //手动分页，需要先查出全部然后筛选重新分页
                for (int i = 0; i <= total; i++) {
                    // 开始索引
                    int currentPage = request.getPaging().getCurrentPage();
                    int fromIndex = (currentPage - 1) * request.getPaging().getPageSize();
                    // 结束索引
                    int toIndex = fromIndex + request.getPaging().getPageSize();
                    // 如果结束索引大于集合的最大索引，那么规定结束索引=集合大小
                    if (toIndex > total) {
                        toIndex = total;
                    }
                    if (fromIndex <= total) {
                        subList = list.subList(fromIndex, toIndex);
                        if (toIndex >= fromIndex) {
                            break;
                        }
                    }
                }
            }
        }
        int count = list.size();
        request.getPaging().setRecords(count);
        response.setPaging(request.getPaging());
        response.setObjectList(subList);
        response.setResultCode(ReturnResult.SUCCESS.getResultCode());
        response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        return response;
    }

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

    @Override
    public void importCustomers(int activeId, DepartmentEntity city) {
        try {
            CloudActivityEntity activityEntity = mapper.getByIdAndDel(activeId);
            List<NameValuePair> pairList = new ArrayList<>();
            wrapMap(activityEntity, pairList, city.getName());
            String seeResult = HttpClientUtil.doPost(cloudPullUrl, pairList);
            if (seeResult != null) {
                JSONObject json = JSONObject.fromObject(seeResult);
                Number code = (Number) json.get("retCode");
                if (code.intValue() == 0) {
                    JSONObject dataJson = (JSONObject) json.get("data");
                    JSONArray array = (JSONArray) dataJson.get("userVisitInfo");
                    List<Map<String, Object>> seeList = (List) JSONArray.toCollection(array, Map.class);
                    //mark assess is end
                    redisUtil.setValueExpireNew("cloud:process:" + activeId, "0", 1, TimeUnit.HOURS);
                    redisUtil.addKeyVal("cloud:total:" + activeId, String.valueOf(seeList.size()));

                    if (redisUtil.hasKey("cloud:protect:" + activeId)) {
                        redisUtil.deleteByKeyNew("cloud:protect:" + activeId);
                    }
                    if (redisUtil.hasKey("cloud:done:" + activeId)) {
                        redisUtil.deleteByKeyNew("cloud:done:" + activeId);
                    }
                    //调取接口获取数据
                    if (CollectionUtils.isNotEmpty(seeList)) {
                        int total = seeList.size();
                        int count1 = 0;
                        int count2 = 0;
                        for (int i = 0; i < seeList.size(); i++) {
                            Map<String, Object> s = seeList.get(i);
                            //数据保护机制 1、过滤私客存在的客户 2、过滤已拉取的客户
                            String phone = s.get("loginAccount").toString();
                            String houseName = s.get("projectName").toString();
                            Map<String, Object> queryMap = new HashMap<>(5);
                            queryMap.put("phone", phone);
                            List<CustomerEntity> cusList = mergeMapper.queryByConditions(queryMap);
                            queryMap.put("mobile", phone);
                            List<CloudCustomerEntity> cloudList = cloudCustomerMapper.queryByConditions(queryMap);

                            if (CollectionUtils.isNotEmpty(cusList) || CollectionUtils.isNotEmpty(cloudList)) {
                                Long count = increaseProtectKey(activeId);
                                logger.warn("cloud protect " + phone + " count :" + count + " total:" + getFinishCount(activeId));
                                count1++;
                                continue;
                            } else {
                                count2++;
                                Long count = increaseDoneKey(activeId);
                                logger.warn("cloud线程:" + "-" + total + " done count:" + count + " total:" + getFinishCount(activeId));
                                CloudCustomerEntity entity = getCloudCustomer(phone, houseName, city);
                                entity.setActiveId(activeId);
                                entity.setIsOvertime(0);
                                cloudCustomerMapper.save(entity);
                            }
                            decreaseKey(activeId);
                        }
                        redisUtil.addKeyVal("cloud:process:" + activeId, "1");
                        System.out.println("cloudPull数目 : " + activeId + "--------count1---------" + count1 + " ---------count2--------" + count2);
                    }

                    //更新云迹活动字段
                    Map<String, Object> updateMap = new HashMap<>(5);
                    updateMap.put("id", activityEntity.getId());
                    updateMap.put("isDelete", 0);
                    mapper.updateStatus(updateMap);
                } else {
                    List<String> params = new ArrayList<>();
                    for (NameValuePair pair : pairList) {
                        params.add(pair.getName() + "=" + pair.getValue());
                    }
                    logger.error("浏览云迹接口URL:[{}] ", cloudPullUrl + Joiner.on("&").join(params));
                }
                logger.info("浏览云迹接口返回数据：", seeResult);
            }

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

    private synchronized Integer getFinishCount(Integer activeId) {
        return redisUtil.getIntegerByKey("cloud:done:" + activeId) + redisUtil.getIntegerByKey(
                "cloud:protect:" + activeId);
    }

    private synchronized Long increaseProtectKey(Integer activeId) {
        return redisUtil.increaseByKey("cloud:protect:" + activeId);
    }

    private synchronized void decreaseKey(Integer activeId) {
        redisUtil.decreaseByKey("cloud:total:" + activeId);
    }

    private synchronized Long increaseDoneKey(Integer activeId) {
        return redisUtil.increaseByKey("cloud:done:" + activeId);
    }

    @Override
    public void setCloudCount() {
        staffDuty.setCloudCount();
    }

    @Override
    public void startBackNoVisitToSea() {
        checkNoCallCustomerNoLimit.backNoVisitToSea();
    }

    @Override
    public void putExterCusToCrm() {
        staffDuty.putExterCusToCrm();
    }

    @Override
    public void setCloudReportCount(int type) {
        if (type == 0) {
            staffDuty.setCloudReportCount();
        } else if (type == 1) {
            staffDuty.setCloudReportCountJi();
        } else if (type == 2) {
            staffDuty.setCloudReportCountBn();
        } else if (type == 3) {
            staffDuty.setCloudReportCountYear();
        }
    }

    @Override
    public void addCloudActivityNew() {
        staffDuty.addCloudActivityNew();
    }

    @Override
    public void addCloudActivity() {
        staffDuty.addCloudActivity();
    }

    @Override
    public void updateStatus() {
        staffDuty.updateJgStatus();
    }

    @Override
    public void updateDutyStaff() {
        staffDuty.updateDutyStaff();
    }

    @Override
    public void addMarketActivity() {
        staffDuty.addMarketActivity();
    }

    private String dealRate(int count1, int count2) {
        String rate = "";
        if (count1 > 0 && count2 > 0) {
            double d = (double) count1 / count2;
            DecimalFormat df = new DecimalFormat("0.00%");
            rate = df.format(d);
        }
        return rate;
    }

    private void setPutMap(Map<String, Object> putMap) {
        putMap.put("backCount", 0);
        putMap.put("backRate", "");
        putMap.put("abCount", 0);
        putMap.put("abRate", "");
        putMap.put("seeCount", 0);
        putMap.put("seeRate", "");
        putMap.put("daoCount", 0);
        putMap.put("daoRate", "");
        putMap.put("buyCount", 0);
        putMap.put("signCount", 0);
        putMap.put("successCount", 0);
        putMap.put("successRate", "");
    }

    private List<Map<String, Object>> dealList(List<CustomerEntity> list, List<Map<String, Object>> listNew) {
        if (CollectionUtils.isNotEmpty(list)) {
            for (CustomerEntity c : list) {
                Iterator<Map<String, Object>> iterator = listNew.iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> iterMap = iterator.next();
                    if (iterMap.get("login_account").toString().equals(c.getPhone())) {
                        iterator.remove();
                    }
                }
            }
        }
        return listNew;
    }

    private synchronized CloudCustomerEntity getCloudCustomer(String phone, String houseName, DepartmentEntity city) {

        CloudCustomerEntity entity = new CloudCustomerEntity();

        entity.setName("");
        entity.setPhone(phone);
        entity.setBakPhone1("");
        entity.setBakPhone2("");
        entity.setBakPhone3("");
        entity.setSex(2);
        entity.setCustomerType(1);
        entity.setActSource("");
        entity.setFirstSource("");
        entity.setLatestSource("");
        entity.setCrmLatestCall("");
        entity.setCrmLatestCallResult("");
        entity.setStatus(0);
        entity.setCreateTime(new Date());
        entity.setCreater("云迹拉取");
        entity.setUpdater("云迹拉取");
        entity.setUpdateTime(new Date());
        entity.setBuyIntention("");

        entity.setLastCallTime(null);
        entity.setManagerId(0);
        entity.setManagerName("");
        entity.setCityCode(city.getDescripition());
        entity.setCityName(city.getName());
        entity.setBizPort("");
        entity.setCrmId("");
        entity.setActSourceId(0);
        entity.setRemark("");
        entity.setTraceStatus(1);
        entity.setCrmSync("1");
        entity.setHotlineCallTime(null);
        entity.setHotlineCallSpend("");
        entity.setOceanDate(null);
        entity.setIsDelete(0);
        entity.setLastManager("");
        entity.setBindTime(null);
        entity.setCustomerId(0);
        entity.setSignupTime("");

        entity.setSignupHouseId("");
        entity.setSignupHouseName(houseName);
        entity.setSignupSourceId("");
        entity.setSignupSourceName("");
        entity.setOverTimeCount(0);
        entity.setVisitBackCount(0);
        entity.setWaitVisitCount(0);
        entity.setBoughtCount(0);
        entity.setIsabandon(0);
        entity.setAbandonLogId(0);
        entity.setAbandonTime(null);
        entity.setCreateSource("云迹拉取");
        return entity;
    }

    private void wrapMap(CloudActivityEntity entity, List<NameValuePair> pairList, String cityName) {
        String projectName = entity.getSeeProjectName();
        pairList.add(new BasicNameValuePair("project_name_array", projectName));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String startTime = formatter.format(entity.getSeeStartTime());
        String endTime = formatter.format(entity.getSeeEndTime());
        pairList.add(new BasicNameValuePair("city_name", cityName));
        pairList.add(new BasicNameValuePair("start_date", startTime));
        pairList.add(new BasicNameValuePair("end_date", endTime));
        pairList.add(new BasicNameValuePair("visit_count", String.valueOf(entity.getSeeCount())));
        if (entity.getTotalPriceMin() > 0 && entity.getTotalPriceMax() > 0) {
            pairList.add(new BasicNameValuePair("total_price_from", String.valueOf(entity.getTotalPriceMin())));
            pairList.add(new BasicNameValuePair("total_price_to", String.valueOf(entity.getTotalPriceMax())));
        }
        if (entity.getAreaMin() > 0 && entity.getAreaMax() > 0) {
            pairList.add(new BasicNameValuePair("area_from", String.valueOf(entity.getAreaMin())));
            pairList.add(new BasicNameValuePair("area_to", String.valueOf(entity.getAreaMax())));
        }
        StringBuilder blockBuilder = new StringBuilder();
        StringBuilder districtBuilder = new StringBuilder();
        if (CollectionUtils.isNotEmpty(entity.getBlockList())) {
            entity.getBlockList().forEach(e -> blockBuilder.append(e).append(","));
            String blocks = blockBuilder.toString();
//            pairList.add(new BasicNameValuePair("plate_id_array", blocks));
            pairList.add(new BasicNameValuePair("plate_name_array", blocks));
        }
        if (CollectionUtils.isNotEmpty(entity.getDistrictList())) {
            entity.getDistrictList().forEach(e -> districtBuilder.append(e).append(","));
            String districts = districtBuilder.toString();
//            pairList.add(new BasicNameValuePair("district_id_array", districts));
            pairList.add(new BasicNameValuePair("district_name_array", districts));
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(entity.getChannel())) {
            pairList.add(new BasicNameValuePair("info_type", entity.getChannel()));
        }
    }

}
