package com.house365.web.controller;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.house365.beans.common.HGSConstant;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CustomerVo;
import com.house365.beans.vo.MarketingActivityVo;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.cached.RedisUtilsInterface;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.web.util.ThreadPoolManager;
import com.house365.ws.beans.request.MarketBuildingRelRequest;
import com.house365.ws.beans.request.MarketingActivityRequest;
import com.house365.ws.beans.request.UserListRequest;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.beans.response.MarketCustomerListResponse;
import com.house365.ws.beans.response.UserListResponse;
import com.house365.ws.interfaces.server.ICustomer;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.IUser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

/**
 * 转移客户控制类
 */
@Controller
@RequestMapping("/transfercustomer")
public class TransferCustomerController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(TransferCustomerController.class);

    @Autowired
    private ICustomer customer;

    @Autowired
    private IDepartment department;
    @Autowired
    private IUser user;
    @Autowired
    private RedisUtilsInterface redisUtil;



    @RequestMapping(value = "", method = {RequestMethod.GET})
    public String showPage( Model model) {
        return getAutoUrl("form");
    }

    /**
     * 统计客户总数
     * @param request
     * @return
     */
    @RequestMapping(value = "count", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String countCustomer(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        Map<String, Object> map = new HashMap<>(5);
        String managerId = request.getParameter("managerId");
        String buyIntention = request.getParameter("buyIntention");
        String projectStatus = request.getParameter("projectStatus");
        String callbackLog = request.getParameter("callbackLog");
        String isStar = request.getParameter("isStar");
        map.put("managerId", managerId);
        if(StringUtils.isNotEmpty(buyIntention) && !"all".equals(buyIntention)){
            map.put("buyIntention", buyIntention);
        }else if("".equals(buyIntention)){
            map.put("buyIntention", "23");//统计购房意向:设置待定指定值
        }
        if(StringUtils.isNotEmpty(isStar)){
            map.put("isStar", isStar);
        }
        if(StringUtils.isNotEmpty(projectStatus)){
            map.put("projectStatus", projectStatus);
        }
        if(StringUtils.isNotEmpty(callbackLog)){
            map.put("callbackLog", callbackLog);
        }
        map.put("userId", userEntity.getId());
        Integer totalNum =0;

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        map.put("cityCode", cityCode);
        if(StringUtils.isEmpty(callbackLog)){
            totalNum = customer.countCustomer(map);
        }else{
            totalNum = customer.countCustomer4(map);
        }
        if(totalNum == null){
            totalNum = 0;
        }
        return totalNum.toString();
    }


    @RequestMapping(value = "assignManager", method = RequestMethod.GET)
    public String assignManager(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String customerCount = request.getParameter("customerCount") == null ? "0" : request.getParameter(
                "customerCount");
        String multyassign = request.getParameter("multyassign") == null ? "0" : request.getParameter("multyassign");
        //当前城市下所有员工
        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();

        Map<String, Object> searchParams = new HashMap<>(10);

        String urlPath = "";
        //是总部员工，选择当前城市和下属所有部门员工 ， 非管理员，选登录用户下属所有部门员工
        if (userEntity.getDeptId() == 1) {
            urlPath = city.getUrlPath();
        } else {
            urlPath = userEntity.getDeptUrlPath() + "/";
        }
        //非随意派工人员
        searchParams.put("LIKE_deptUrlPath", urlPath);
        searchParams.put("EQ_isFreeMan", "0");

        Page page = new Page(Integer.MAX_VALUE);
        UserListRequest listRequest = new UserListRequest();
        listRequest.setPaging(page);
        listRequest.setOrderColumn("name");
        listRequest.setOrderMode("asc");
        listRequest.setSearchParams(searchParams);
        UserListResponse response = user.getUserList(listRequest);
        List<UserEntity> userList = response.getObjectList();

        //可随意派工人员
        getFreeman(userEntity, page, userList);

        if (!userList.contains(userEntity)) {
            userList.add(0, userEntity);
        }

        model.addAttribute("users", userList);
        model.addAttribute("customerCount", customerCount);
        model.addAttribute("multyassign", multyassign);
        return getAutoUrl("assignManager");
    }

    private void getFreeman(UserEntity userEntity, Page page, List<UserEntity> userList) {
        //获取城市下，不限制转移的用户。
        Map<String, Object> freemanQuery = new HashMap<>();
        String str = userEntity.getDeptUrlPath();
        //总部算南京
        if ("/1".equalsIgnoreCase(userEntity.getDeptUrlPath())) {
            str = "/1/2/";
        }

        if (!str.endsWith("/")) {
            str += "/";
        }
        str = str.substring(0, str.indexOf("/", 4));
        freemanQuery.put("REGEXP_deptUrlPath", "^" + str + "$|^" + str + "/");
        freemanQuery.put("EQ_isFreeMan", "1");
        UserListRequest freemanListRequest = new UserListRequest();
        freemanListRequest.setPaging(page);
        freemanListRequest.setOrderColumn("name");
        freemanListRequest.setOrderMode("asc");
        freemanListRequest.setSearchParams(freemanQuery);
        UserListResponse freemanResponse = user.getUserList(freemanListRequest);
        List<UserEntity> freemanList = freemanResponse.getObjectList();

        userList.addAll(0, freemanList);
    }

    @RequestMapping(value = "getLoadData", method = RequestMethod.GET)
    @ResponseBody
    public Object getLoadData(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestObject restObject = new House365RestObject();
//        restResponse.setResult("1");
        String count = request.getParameter("count");
        Map<String, Object> map = new HashMap<>(5);
        String managerId = request.getParameter("managerId");
        int completed = 0;
        String completePercent = "0";
        logger.info("--------------------------:transfer:done:"+String.valueOf(userEntity.getId())+managerId);
        completed = redisUtil.hasKey("transfer:done:" + String.valueOf(userEntity.getId())+managerId) ? redisUtil.getIntegerByKey(
                "transfer:done:" + String.valueOf(userEntity.getId())+managerId) : 0;
        logger.info("--------------已完成------------:transfer:done:"+redisUtil.getIntegerByKey("transfer:done:" + String.valueOf(userEntity.getId())+managerId));
        logger.info("-----------总共客户数据----------:"+count);
        if(Integer.valueOf(count)>500){
            count = "500";
        }
        //私客转移
        if (redisUtil.hasKey("transfer:process:" + String.valueOf(userEntity.getId())+managerId) && 1 == redisUtil.getIntegerByKey(
                "transfer:process:" + String.valueOf(userEntity.getId())+managerId)) {
            completePercent = "100";
        } else {

            int percent = new BigDecimal(completed).divide(new BigDecimal(count), 2,
                    BigDecimal.ROUND_HALF_UP).multiply(
                    new BigDecimal(100)).intValue();
            completePercent = String.valueOf(percent);
        }

//        Map<String, String> pam = new HashMap<>(10);
        restObject.setTotal(String.valueOf(completed));
        restObject.setEntity(completePercent);
//        if (redisUtil.hasKey("transfer:process:" +userEntity.getId()+managerId)) {
//            redisUtil.deleteByKeyNew("transfer:process:" + userEntity.getId()+managerId);
//        }
        return restObject;
    }


    /**
     * 客户转移
     * @param vo
     * @param request
     * @return
     */
    @RequestMapping(value = "/turn", method = {RequestMethod.POST})
    @ResponseBody
    public Object turnData(MarketingActivityVo vo, HttpServletRequest request) {
        String result = "fail";
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        Map<String, Object> map = new HashMap<>(5);
        String userIds = request.getParameter("userIds");
        String managerId = request.getParameter("managerId");
        String count = request.getParameter("count");
        String[] userIdArray = userIds.split(",");

        String buyIntention = request.getParameter("buyIntention");
        String projectStatus = request.getParameter("projectStatus");
        String callbackLog = request.getParameter("callbackLog");
        String isStar = request.getParameter("isStar");
        map.put("managerId", managerId);
        if(StringUtils.isNotEmpty(buyIntention) && !"all".equals(buyIntention)){
            map.put("buyIntention", buyIntention);
        }else if("".equals(buyIntention)){
            map.put("buyIntention", "23");//统计购房意向:设置待定指定值
        }
        if(StringUtils.isNotEmpty(isStar)){
            map.put("isStar", isStar);
        }
        if(StringUtils.isNotEmpty(projectStatus)){
            map.put("projectStatus", projectStatus);
        }
        if(StringUtils.isNotEmpty(callbackLog)){
            map.put("callbackLog", callbackLog);
        }
        if(Integer.valueOf(count)>500){
            count = "500";
        }
        map.put("userId", userEntity.getId());
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        map.put("cityCode", cityCode);
        //私客数据
        List<CustomerEntity> list = new ArrayList<>();
        if(StringUtils.isEmpty(callbackLog)){
            list = customer.getAllCustomer(map);
        }else {
            list = customer.getAllCustomer4(map);
        }
        String[] customerIds = new String[list.size()];
        for(int i=0;i<list.size();i++){
            customerIds[i] = String.valueOf(list.get(i).getId());
        }
        for (String userId : userIdArray) {
            Integer uId = Integer.valueOf(userId);
            String key = "HGS_summary_mananger_" + userId;
            redisUtil.deleteByKeyNew(key);
        }
        List<String> useridSplit = Arrays.asList(userIdArray);
        int size = useridSplit.size();
        int i = 0;
        try {
            customer.transferUser(customerIds, userIdArray, userEntity.getId(), managerId, true, "handover", "", Integer.valueOf(count));
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 获取批量移入公海进程
     * @param request
     * @return
     */
    @RequestMapping(value = "getRemoveData", method = RequestMethod.GET)
    @ResponseBody
    public Object getRemoveData(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestObject restObject = new House365RestObject();
        String count = request.getParameter("count");
        String managerId = request.getParameter("managerId");
        int completed = 0;
        String completePercent = "0";
        logger.info("--------------------------:remove:done:"+String.valueOf(userEntity.getId())+managerId);
        completed = redisUtil.hasKey("remove:done:" + String.valueOf(userEntity.getId())+managerId) ? redisUtil.getIntegerByKey(
                "remove:done:" + String.valueOf(userEntity.getId())+managerId) : 0;
        logger.info("--------------查询移入公海已完成------------:remove:done:"+redisUtil.getIntegerByKey("remove:done:" + String.valueOf(userEntity.getId())+managerId));
        logger.info("-----------移入公海总共客户数据----------:"+count);
        if(Integer.valueOf(count)>500){
            count = "500";
        }
        //私客转移
        if (redisUtil.hasKey("remove:process:" + String.valueOf(userEntity.getId())+managerId) && 1 == redisUtil.getIntegerByKey(
                "remove:process:" + String.valueOf(userEntity.getId())+managerId)) {
            completePercent = "100";
        } else {
            int percent = new BigDecimal(completed).divide(new BigDecimal(count), 2,
                    BigDecimal.ROUND_HALF_UP).multiply(
                    new BigDecimal(100)).intValue();
            completePercent = String.valueOf(percent);
        }

//        Map<String, String> pam = new HashMap<>(10);
        restObject.setTotal(String.valueOf(completed));
        restObject.setEntity(completePercent);
        return restObject;
    }

    /**
     * 移公海
     * @param request
     * @return
     */
    @RequestMapping(value = "batchRemove", method = RequestMethod.POST)
    @ResponseBody
    public House365RestResponse batchRemove(HttpServletRequest request) {
//        String result = "fail";
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        Map<String, Object> map = new HashMap<>(5);
        String managerId = request.getParameter("managerId");
        String count = request.getParameter("count");

        String buyIntention = request.getParameter("buyIntention");
        String projectStatus = request.getParameter("projectStatus");
        String callbackLog = request.getParameter("callbackLog");
        String isStar = request.getParameter("isStar");
        map.put("managerId", managerId);
        if(StringUtils.isNotEmpty(buyIntention) && !"all".equals(buyIntention)){
            map.put("buyIntention", buyIntention);
        }else if("".equals(buyIntention)){
            map.put("buyIntention", "23");//统计购房意向:设置待定指定值
        }
        if(StringUtils.isNotEmpty(isStar)){
            map.put("isStar", isStar);
        }
        if(StringUtils.isNotEmpty(projectStatus)){
            map.put("projectStatus", projectStatus);
        }
        if(StringUtils.isNotEmpty(callbackLog)){
            map.put("callbackLog", callbackLog);
        }
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        String cityCode = departmentResponse.getEntity().getDescripition();
        map.put("cityCode", cityCode);
        //私客数据
        List<CustomerEntity> list = new ArrayList<>();
        if(StringUtils.isEmpty(projectStatus) && StringUtils.isEmpty(callbackLog)){
            list = customer.getAllCustomer(map);
        }else if(StringUtils.isNotEmpty(projectStatus) && StringUtils.isEmpty(callbackLog)){
            list = customer.getAllCustomer2(map);
        }else if(StringUtils.isNotEmpty(projectStatus) && StringUtils.isNotEmpty(callbackLog)){
            list = customer.getAllCustomer3(map);
        }else if(StringUtils.isEmpty(projectStatus) && StringUtils.isNotEmpty(callbackLog)){
            list = customer.getAllCustomer4(map);
        }
        String[] customerIds = new String[list.size()];
        for(int i=0;i<list.size();i++){
            customerIds[i] = String.valueOf(list.get(i).getId());
        }
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        try {
            customer.batch2Sea(customerIds, userEntity.getId(), managerId, Integer.valueOf(count), userEntity.getRealName());
        } catch (Exception e) {
            restResponse.setResult("0");
            restResponse.setMsg(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return restResponse;
    }
}
