package com.house365.web.controller;

import com.google.common.base.Joiner;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CloudRuleVo;
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.SessionConstants;
import com.house365.ws.beans.request.MapListRequest;
import com.house365.ws.beans.request.ProjectListRequest;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.beans.response.MapListResponse;
import com.house365.ws.beans.response.ProjectListResponse;
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.map.ListOrderedMap;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.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.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.web.Servlets;

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

/**
 * 云迹客户controller
 *
 * @author Created by Administrator on 2020/3/26.
 */
@Controller
@RequestMapping("/cloudactivity")
public class CloudActivityController extends BaseController {

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

    @Value("${CRM.TRANSLATE.URL}")
    private String crmTranslateUrl;
    @Value("${CLOUD.PULL.URL}")
    private String cloudPullUrl;


    @Autowired
    private RedisUtilsInterface redisUtil;
    @Autowired
    private ICloudActivityInterface activityInterface;
    @Autowired
    private IProject project;
    @Autowired
    private IDepartment department;
    @Autowired
    private ICloudRuleInterface ruleInterface;
    @Autowired
    private IUser iUser;

    /**
     * 云迹活动列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(Integer number, Model model, HttpServletRequest request) {
        try {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            String city = dept.getDescripition();
            searchParams.put("city", city);
            searchParams.put("userId", userEntity.getId());
            Page page = new Page(50);
            if (null != number) {
                page.setCurrentPage(number);
            }
            MapListRequest listRequest = new MapListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            MapListResponse response = activityInterface.list(listRequest);
            model.addAttribute("page", response.getPaging());
            model.addAttribute("dataList", response.getObjectList());
        } catch (Exception e) {
            logger.error("查询云迹活动列表失败", e);
        }
        return getAutoUrl();
    }

    /**
     * 云迹主动拉取数据列表
     *
     * @param number
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/pullList")
    public String pullList(Integer number, Model model, HttpServletRequest request) {
        try {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            String city = dept.getDescripition();
            searchParams.put("city", city);
            searchParams.put("userId", userEntity.getId());
            Page page = new Page(50);
            if (null != number) {
                page.setCurrentPage(number);
            }
            MapListRequest listRequest = new MapListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            MapListResponse response = activityInterface.pullList(listRequest);
            model.addAttribute("page", response.getPaging());
            model.addAttribute("dataList", response.getObjectList());
        } catch (Exception e) {
            logger.error("查询云迹拉取列表失败", e);
        }
        return getAutoUrl();
    }

    @RequestMapping(value = "/setCloudCount")
    @ResponseBody
    public String setCloudCount() {
        activityInterface.setCloudCount();
        System.out.println("----------设置云迹redis成功---------");
        return "----------set cloud redis success---------";
    }

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

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

    @RequestMapping(value = "/setCloudReportCount/{type}")
    @ResponseBody
    public String setCloudReportCount(@PathVariable int type) {
        activityInterface.setCloudReportCount(type);
        System.out.println("----------设置云迹报表redis成功---------");
        return "----------set cloudReport redis success---------";
    }

    @RequestMapping(value = "/addCloudActivityNew")
    @ResponseBody
    public String addCloudActivityNew() {
        activityInterface.addCloudActivityNew();
        System.out.println("----------添加定制云迹活动成功---------");
        return "----------addCloudActivityNew success---------";
    }

    @RequestMapping(value = "/updateStatus")
    @ResponseBody
    public String updateStatus() {
        activityInterface.updateStatus();
        System.out.println("----------定时更新经管状态成功---------");
        return "----------updateStatus success---------";
    }

    @RequestMapping(value = "/updateDutyStaff")
    @ResponseBody
    public String updateDutyStaff() {
        activityInterface.updateDutyStaff();
        System.out.println("----------updateDutyStaff成功---------");
        return "----------updateDutyStaff success---------";
    }

    @RequestMapping(value = "/addMarketActivity")
    @ResponseBody
    public String addMarketActivity() {
        activityInterface.addMarketActivity();
        System.out.println("----------addMarketActivity成功---------");
        return "----------addMarketActivity success---------";
    }


    /**
     * 云迹报表详情列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/cloudCusList/{id}/{status}/{countId}")
    public String cloudCusList(Integer number, Model model, HttpServletRequest request, @PathVariable int id, @PathVariable int status, @PathVariable int countId) {
        try {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            String city = dept.getDescripition();
            searchParams.put("city", city);
            searchParams.put("createId", id);
            searchParams.put("status", status);
            Page page = new Page(50);
            if (null != number) {
                page.setCurrentPage(number);
            }
            MapListRequest listRequest = new MapListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            MapListResponse response = activityInterface.reportDetailList(listRequest, countId);
            if (status == 2) {
                model.addAttribute("timeType", "到访时间");
            } else if (status == 4) {
                model.addAttribute("timeType", "认购时间");
            } else {
                model.addAttribute("timeType", "签约时间");
            }
            model.addAttribute("id", id);
            model.addAttribute("status", status);
            model.addAttribute("page", response.getPaging());
            model.addAttribute("dataList", response.getObjectList());
        } catch (Exception e) {
            logger.error("查询云迹报表详情列表失败", e);
        }
        return getAutoUrl();
    }

    /**
     * 添加定制云迹规则
     *
     * @return
     */
    @RequestMapping(value = "/addRule", method = RequestMethod.POST)
    @ResponseBody
    public HResult addRule(HttpServletRequest request, @RequestBody CloudRuleVo vo) {
        HResult result = new HResult();
        try {
            DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            String cityId = departmentEntity.getCityID();
            DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
            DepartmentEntity city = departmentResponse.getEntity();
            List<CloudRuleEntity> list = vo.getList();
            list = removeDuplicateList(list);
            if (CollectionUtils.isNotEmpty(list)) {
                if (list.size() > 10) {
                    result.setStatus(500);
                    result.setErrorMessage("最多订阅10个楼盘");
                    return result;
                }
                result = ruleInterface.save(list, userEntity, city.getDescripition());
            } else {
                ruleInterface.deleteByUserId(userEntity.getId());
            }
        } catch (Exception e) {
            result.setStatus(500);
            result.setErrorMessage("添加云迹定制规则失败");
            logger.error("添加云迹定制规则失败");
        }
        return result;
    }

    /**
     * 定制云迹弹框
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/assignProject", method = RequestMethod.GET)
    public String assignProject(Model model, HttpServletRequest request) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();

        Map<String, Object> searchParams = new HashMap<>(10);
        Page page = new Page(Integer.MAX_VALUE);
        ProjectListRequest listRequest = new ProjectListRequest();
        listRequest.setPaging(page);
        searchParams.put("EQ_showStatus", "0");
        searchParams.put("EQ_city", city.getDescripition());
        int userId = userEntity.getId();
        listRequest.setSearchParams(searchParams);
        ProjectListResponse response = project.getProjectList(listRequest);

        Map<String, Object> map = new HashMap<>(10);
        map.put("userId", userId);
        List<CloudRuleEntity> ruleList = ruleInterface.queryByConditions(map);
        model.addAttribute("addList", ruleList);

        model.addAttribute("departments", response.getObjectList());
        return getAutoUrl("assignProject");
    }

    private static ArrayList<CloudRuleEntity> removeDuplicateList(List<CloudRuleEntity> list) {
        Set<CloudRuleEntity> set = new TreeSet<>(new Comparator<CloudRuleEntity>() {
            @Override
            public int compare(CloudRuleEntity o1, CloudRuleEntity o2) {
                return String.valueOf(o1.getProjectId()).compareTo(String.valueOf(o2.getProjectId()));
            }
        });
        set.addAll(list);
        return new ArrayList<>(set);
    }

    /**
     * 查询已有的定制规则
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getList")
    @ResponseBody
    public HResult getList(HttpServletRequest request) {
        HResult result = new HResult();
        try {
            List<Map<String, Object>> list = new ArrayList<>();
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            Map<String, Object> map = new HashMap<>(10);
            map.put("userId", userEntity.getId());
            List<CloudRuleEntity> ruleList = ruleInterface.queryByConditions(map);
            if (CollectionUtils.isNotEmpty(ruleList)) {
                for (CloudRuleEntity c : ruleList) {
                    Map<String, Object> putMap = new HashMap<>(10);
                    String houseName = c.getProjectName() + "-" + c.getChannelName() + "-" + c.getProjectId() + "-" + c.getChannel();
                    putMap.put("houseName", houseName);
                    putMap.put("projectId", c.getProjectId());
                    putMap.put("channel", c.getChannel());
                    list.add(putMap);
                }
            }
            result.setData(list);
        } catch (Exception e) {
            result.setStatus(500);
            result.setErrorMessage("查询定制云迹规则失败");
            logger.error("查询定制云迹规则失败", e);
        }
        return result;
    }

    /**
     * 调用新房接口查询楼盘数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/searchHouse")
    @ResponseBody
    public HResult searchHouse(HttpServletRequest request, @RequestBody PropertyReportEntity entity) {
        HResult result = new HResult();
        try {
            List<Map<String, Object>> list = new ArrayList<>();
            String city = (String) request.getSession().getAttribute("city");
            String url = "http://newapi.house365.com/projects/name";
            List<NameValuePair> queryParams = new ArrayList<>(10);
            queryParams.add(new BasicNameValuePair("limit", "10"));
            queryParams.add(new BasicNameValuePair("name", entity.getCustomerName()));
            queryParams.add(new BasicNameValuePair("city", city));
            queryParams.add(new BasicNameValuePair("like", "1"));

            String data = HttpClientUtil.doGet(url, queryParams);
            if (data != null) {
                JSONObject json = JSONObject.fromObject(data);
                JSONObject jsonObject1 = (JSONObject) json.get("data");
                JSONArray array = (JSONArray) jsonObject1.get("list");
                for (int i = 0; i < array.size(); i++) {
                    JSONObject object = array.getJSONObject(i);
                    Map<String, Object> putMap = new HashMap<>(10);
                    String houseName = object.get("itemname").toString();
                    String channelName = object.get("channel_name").toString();
                    String projectId = object.get("listid").toString();
                    String channel = object.get("channel").toString();
                    houseName = houseName + "-" + channelName + "-" + projectId + "-" + channel;
                    putMap.put("houseName", houseName);
                    putMap.put("projectId", projectId);
                    putMap.put("channel", channel);
                    list.add(putMap);
                }
                //过滤全链条已开启的项目
                Iterator<Map<String, Object>> iterator = list.iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> projectMap = iterator.next();
                    String projectId = projectMap.get("projectId").toString();
                    Map<String, Object> searchMap = new HashMap<>(10);
                    searchMap.put("buildingId", Integer.parseInt(projectId));
                    searchMap.put("city", city);
                    searchMap.put("showStatus", 1);
                    List<ProjectEntity> prList = project.queryByCondition(searchMap);
                    if (CollectionUtils.isNotEmpty(prList)) {
                        iterator.remove();
                    }
                }
                result.setData(list);
            } else {
                result.setStatus(500);
                result.setErrorMessage("调用新房接口查询楼盘数据失败");
                return result;
            }
        } catch (Exception e) {
            result.setStatus(500);
            result.setErrorMessage("查询定制云迹规则失败");
            logger.error("查询定制云迹规则失败", e);
        }
        return result;
    }

    /**
     * 跳转新增云迹活动
     *
     * @return 结果视图
     */
    @RequestMapping(value = "toAdd")
    public String toAdd(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();
        String cityCode = "zb".equalsIgnoreCase(city.getDescripition()) ? "nj" : city.getDescripition();
        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);
            }
            blockParam.remove(new BasicNameValuePair("type", "block"));
            blockParam.add(new BasicNameValuePair("type", "district"));
            String districtResult = HttpClientUtil.doGet(crmTranslateUrl, blockParam);
            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();
            logger.error("获取crm板块接口失败");
        }
        List<DutyStaffEntity> dutyList = iUser.getOndutyById(userEntity.getId());
        model.addAttribute("limitDate", "0");
        if (CollectionUtils.isNotEmpty(dutyList)) {
            if ("0".equals(dutyList.get(0).getOnduty())) {
                //名单内:值班不限制时间选择范围
                model.addAttribute("limitDate", "1");
            }
        }
        model.addAttribute("districts", districts);
        model.addAttribute("blocks", blocks);
        return getAutoUrl("addcloud");
    }

    /**
     * 新增云迹活动
     *
     * @return
     */
    @RequestMapping(value = "/addCloud", method = RequestMethod.POST)
    @ResponseBody
    public HResult addCloud(HttpServletRequest request, @RequestBody CloudActivityEntity entity) {
        HResult result = new HResult();
        try {
            DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            String cityId = departmentEntity.getCityID();
            DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
            DepartmentEntity city = departmentResponse.getEntity();
            String cityCode = city.getDescripition();
            //调取云迹接口
            List<NameValuePair> pairList = new ArrayList<>();
            Map<String, String> dataMap = wrapMap(entity, pairList, city.getName());

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String startTime = entity.getStartTime();
            String endTime = entity.getEndTime();
            long time1 = System.currentTimeMillis();
            String seeResult = HttpClientUtil.doPost(cloudPullUrl, pairList);
            long time2 = System.currentTimeMillis();
            logger.info("----------云迹拉取接口程序运行时间----------： " + (time2 - time1) + "ms");
            System.out.println("----------云迹拉取接口程序运行时间----------： " + (time2 - time1) + "ms");
            int count = 0;
            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");
                    count = array.size();
                } else {
                    List<String> params = new ArrayList<>();
                    for (NameValuePair pair : pairList) {
                        params.add(pair.getName() + "=" + pair.getValue());
                    }
                    logger.error("浏览云迹接口URL:[{}] ", cloudPullUrl + Joiner.on("&").join(params));
                    result.setErrorMessage("调用云迹查询接口出错！请稍后再试！");
                    result.setStatus(-1);
                    return result;
                }
                logger.info("浏览云迹接口返回数据：", seeResult);
            }

            Date now = new Date();
            entity.setCity(cityCode);
            entity.setCreateId(userEntity.getId());
            entity.setCreateName(userEntity.getName());
            entity.setCustomerCount(0);
            entity.setWaitCount(0);
            entity.setSentCount(0);
            //先设为无效，导入数据成功后置为有效
            entity.setIsDelete(1);
            //新增字段赋值
            entity.setBlock(dataMap.get("block"));
            entity.setDistrict(dataMap.get("district"));
            entity.setSeeStartTime(formatter.parse(startTime));
            entity.setSeeEndTime(formatter.parse(endTime));
            entity.setCreateTime(now);
            entity.setSeeProjectName(entity.getProjectName());
            entity.setType(1);
            int id = activityInterface.save(entity);

            Map<String, Object> map = new HashMap<>(10);
            map.put("id", id);
            map.put("total", count);
            result.setData(map);
        } catch (Exception e) {
            result.setStatus(500);
            result.setErrorMessage("新增云迹活动失败");
            logger.error("新增云迹活动失败");
        }
        return result;
    }

    @RequestMapping(value = "/import/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public Object importData(HttpServletRequest request, @PathVariable int id) {
        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 {
            activityInterface.importCustomers(id, city);
            result = "success";
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导入云迹客户失败", e);
        }
        return result;
    }

    @RequestMapping(value = "/getLoad/{activeId}/{total}", method = {RequestMethod.GET})
    @ResponseBody
    public Object getLoad(@PathVariable(value = "activeId") String activeId, @PathVariable(value = "total") String total) {

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

            if (redisUtil.hasKey("cloud:process:" + activeId) && 1 == redisUtil.getIntegerByKey("cloud:process:" + activeId)) {
                completePercent = "100";
                protect = redisUtil.hasKey("cloud:protect:" + activeId) ? redisUtil.getIntegerByKey("cloud:protect:" + activeId) : 0;
                done = redisUtil.hasKey("cloud:done:" + activeId) ? redisUtil.getIntegerByKey("cloud:done:" + activeId) : 0;
                System.out.println("activeId===" + activeId + "---protect---" + protect + "----done-----" + done);
            } 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;
    }

    /**
     * 填充接口参数
     *
     * @param entity
     * @param pairList
     */
    private Map<String, String> wrapMap(CloudActivityEntity entity, List<NameValuePair> pairList, String cityName) {
        Map<String, String> map = new HashMap<>(10);
        String projectName = entity.getProjectName();
        pairList.add(new BasicNameValuePair("project_name_array", projectName));
        String startTime = entity.getStartTime();
        String endTime = entity.getEndTime();
        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 (StringUtils.isNotBlank(entity.getChannel())) {
            pairList.add(new BasicNameValuePair("info_type", entity.getChannel()));
        }
        map.put("block", blockBuilder.toString());
        map.put("district", districtBuilder.toString());
        return map;
    }

}
