package com.house365.web.controller;

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.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.ICloudActivityInterface;
import com.house365.ws.interfaces.server.ICloudRuleInterface;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.IProject;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
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.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.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);

    @Autowired
    private ICloudActivityInterface activityInterface;
    @Autowired
    private IProject project;
    @Autowired
    private IDepartment department;
    @Autowired
    private ICloudRuleInterface ruleInterface;

    /**
     * 云迹活动列表
     *
     * @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();
    }

    @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;
    }

}
