package com.house365.web.controller;

import com.beust.jcommander.internal.Lists;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.UserVo;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceException;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.*;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.*;
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.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.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

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

/**
 * 账户控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-14
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入账户WS实现
     */
    @Autowired
    private IUser user;
    @Autowired
    private IDepartment department;

    @Autowired
    private IRole role;

    @Autowired
    private IUserRole userRole;

    @Autowired
    private IAttachmentInterface attachmentInterface;

    @Autowired
    private ICustomer customer;

    /**
     * 去新增账户
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model, HttpServletRequest request) {

        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>();

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_REAL_DEPT_KEY);
        if (PathUtil.isAdminDept(departmentEntity)) {
            departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
        }
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        map.put("LIKE_urlPath", deptEntity.getEntity().getUrlPath());
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> models = resp.getObjectList();

        DepartmentResponse currentDept = department.getDepartmentById(departmentEntity.getId());
        model.addAttribute("departList", models);
        if (currentDept.getEntity() != null) {
            model.addAttribute("currentDept", currentDept.getEntity());
        }

        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增账户
     *
     * @param vo          账户页面表单对象
     * @param result      表单验证数据
     * @param httpRequest 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createUser(@Valid UserVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model,
                             HttpServletRequest httpRequest) {
        UserEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        if (checkDupName(entity.getName())) {
            model.addAttribute("action", "create");
            addErrorMessage(model, "用户名重名");
            return getAutoUrl("form");
        }

        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                UserRequest request = new UserRequest();
                Date date = new Date();
                entity.setCreateTime(date);
                entity.setUpdateTime(date);
                entity.setPassword(MD5Util.MD5("House365**"));
                DepartmentResponse dept = department.getDepartmentById(entity.getDeptId());
                entity.setDeptName(dept.getEntity().getName());
                entity.setDeptUrlPath(dept.getEntity().getUrlPath());
                UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
                entity.setCreateUserid(userEntity.getId());
                entity.setCreateUsername(userEntity.getName());
                entity.setUpdateUserid(userEntity.getId());
                entity.setUpdateUsername(userEntity.getName());
                entity.setEnabled(true);
                entity.setStatus(4);
                request.setEntity(entity);

                Map<String, Object> checkExsitSearchMap = new HashMap<>();
                checkExsitSearchMap.put("EQ_mobile", entity.getMobile());
                checkExsitSearchMap.put("NOTEQ_id", entity.getId());
                UserListRequest userListRequest = new UserListRequest();
                userListRequest.setSearchParams(checkExsitSearchMap);
                UserListResponse userListResponse = user.getUserList(userListRequest);
                if (null != userListResponse && CollectionUtils.isNotEmpty(userListResponse.getObjectList())) {
                    throw new IllegalServiceParameterException("手机号已经存在");
                }

                UserResponse response = user.addUser(request);
                Integer id = response.getEntity().getId();
                return "redirect:/user/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * IM身份信息保存更新
     *
     * @return 结果视图
     */
    @RequestMapping(value = "/saveIM", method = {RequestMethod.GET})
    public String saveIM(HttpServletRequest request, Model model) {
        String userId = request.getParameter("userId");
        String identityType = request.getParameter("identityType");
        String mobile = request.getParameter("mobile");
        if (!StringUtils.isEmpty(userId) && !StringUtils.isEmpty(identityType)) {
            UserEntity ue = user.getById(Integer.valueOf(userId));
            //平台人员不同步im
            if ("20".equals(identityType)) {
                ue.setId(Integer.valueOf(userId));
                ue.setIdentityType(identityType);
                ue.setAccId("");
                ue.setToken("");
                user.updateIM(ue);
            } else {
                String imUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("IM.SYNC.URL");
                String deciceId = com.house365.web.util.StringUtils.getRandomNumber(10);
                String randStr = com.house365.web.util.StringUtils.getRandomChars(13);
                String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
                String signature = HttpUtil.getSignature2(deciceId, randStr, timestamp);

                //城市
                UserEntity accountEntity = user.getUserById(Integer.valueOf(userId)).getEntity();
                logger.info("**********accountEntity:**********" + accountEntity);
                DepartmentResponse departmentResponse = department.getDepartmentById(accountEntity.getDeptId());
                DepartmentEntity dept = departmentResponse.getEntity();
                Integer realDept = PathUtil.extractDept(dept.getUrlPath());
                if (!accountEntity.getDeptId().equals(realDept)) {
                    dept = department.getDepartmentById(realDept).getEntity();
                }
                String cityId = dept.getCityID();
                DepartmentResponse departmentResponse2 = department.getDepartmentById(Integer.valueOf(cityId));
                String cityCode = departmentResponse2.getEntity().getDescripition();
                logger.info("**********cityCode:**********" + cityCode);
                //获取accesstoken
                HashMap<String, String> accesstokenMap = new HashMap<>(10);
                accesstokenMap.put("version", "v3.0");
                //获取acceToken接口URl
                String getAccessTokenUrl = imUrl + "/api/5b0cc34464a64";
                List<NameValuePair> tokenInParam = new ArrayList<>();
                tokenInParam.add(new BasicNameValuePair("app_id", "89962055"));
                tokenInParam.add(new BasicNameValuePair("app_secret", "pMHTUWAoOGSjaToIhHKwmQJKWZcAAvjN"));
                tokenInParam.add(new BasicNameValuePair("device_id", deciceId));
                tokenInParam.add(new BasicNameValuePair("rand_str", randStr));
                tokenInParam.add(new BasicNameValuePair("timestamp", timestamp));
                tokenInParam.add(new BasicNameValuePair("signature", signature));

                List<String> newTokenParams = new ArrayList<>();
                for (NameValuePair pair : tokenInParam) {
                    newTokenParams.add(pair.getName() + "=" + pair.getValue());
                }
                String newTokenUrl = getAccessTokenUrl + "?" + Joiner.on("&").join(newTokenParams);
                String tokenResult = "";
                try {
                    tokenResult = HttpUtil.getHttpRequest(newTokenUrl, accesstokenMap, 100000, "utf-8");
                    if (Strings.isNullOrEmpty(tokenResult)) {
                        throw new ServiceException("get token failed");
                    }
                    JSONObject json = JSONObject.fromObject(tokenResult);
                    JSONObject jo = json.getJSONObject("data");
                    String accessToken = jo.getString("access_token");
                    //2.获取accid
                    List<NameValuePair> cornetInParam = new ArrayList<>();
                    cornetInParam.add(new BasicNameValuePair("uid", userId));
                    cornetInParam.add(new BasicNameValuePair("phone", mobile));
                    String identity = "{\"identity\":" + identityType + ",\"city\":" + "\"" + cityCode + "\"" + "}";
                    logger.info("************identity:*******" + identity);
                    cornetInParam.add(new BasicNameValuePair("ex", JSONObject.fromObject(identity).toString()));
                    String resultUrl = imUrl + "/api/5b8763053720d";
                    String env = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.env");
                    if (!"production".equalsIgnoreCase(env)) {
                        return "redirect:/user";
                    }

                    String accIdResult = HttpUtil.doPostWithHeader(resultUrl, cornetInParam, accessToken, "");
                    if (Strings.isNullOrEmpty(accIdResult)) {
                        throw new ServiceException("get accid failed");
                    }
                    JSONObject accidJson = JSONObject.fromObject(accIdResult);
                    JSONObject accidJo = accidJson.getJSONObject("data");
                    String accid = accidJo.getString("accid");
                    String token = accidJo.getString("token");
                    ue.setId(Integer.valueOf(userId));
                    ue.setIdentityType(identityType);
                    ue.setAccId(accid);
                    ue.setToken(token);
                    user.updateIM(ue);
                    //回传IM更新用户身份信息
                    List<NameValuePair> updateParam = new ArrayList<>();
                    updateParam.add(new BasicNameValuePair("accid", accid));
                    updateParam.add(new BasicNameValuePair("ex", JSONObject.fromObject(identity).toString()));
                    String idUrl = imUrl + "/api/5b9235bea9f88";
                    String identityResult = HttpUtil.doPostWithHeader(idUrl, updateParam, accessToken, "");
                    logger.info("**********回传更新身份结果**********" + identityResult);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("同步云信失败", e);
                }
            }

        }
        return "redirect:/user";
    }

    private boolean checkDupName(String name) {
        UserListRequest request = new UserListRequest();
        HashMap<String, Object> paraMap = new HashMap<>(10);
        paraMap.put("EQ_name", name);
        request.setSearchParams(paraMap);
        request.setLimit(1);
        UserListResponse userList = user.getUserList(request);
        if (userList.getObjectList().size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 删除账户
     *
     * @param id      账户页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    UserEntity delUser = null;
                    UserResponse userResponse = user.getUserById(Integer.valueOf(ids[i]));
                    if (userResponse.getEntity() != null) {
                        delUser = userResponse.getEntity();
                        if (!Strings.isNullOrEmpty(delUser.getHotlinephone())) {
                            String unbindResult = user.unbindHotlinePhone(delUser);
                            //新增删除记录操作日志
                            if ("success".equals(unbindResult)) {
                                saveUnbindLog(userEntity, delUser);
                            }
                        }
                        user.deleteUserById(Integer.valueOf(ids[i]), userEntity.getId());
                    }
                }
            } else {
                UserEntity delUser = null;
                UserResponse userResponse = user.getUserById(Integer.valueOf(id));
                if (userResponse.getEntity() != null) {
                    delUser = userResponse.getEntity();
                    if (!Strings.isNullOrEmpty(delUser.getHotlinephone())) {
                        String unbindResult = user.unbindHotlinePhone(delUser);
                        //新增删除记录操作日志
                        if ("success".equals(unbindResult)) {
                            saveUnbindLog(userEntity, delUser);
                        }
                    }
                    user.deleteUserById(Integer.valueOf(id), userEntity.getId());
                }
            }
        }
    }

    /**
     * 记录解绑日志
     *
     * @param loginUserEntity
     * @param delUser
     */
    private void saveUnbindLog(UserEntity loginUserEntity, UserEntity delUser) {
        UserEntity entity = new UserEntity();
        entity.setName(delUser.getName());
        entity.setRealName(delUser.getRealName());
        entity.setMobile(delUser.getMobile());
        entity.setCornet(delUser.getCornet());
        entity.setHotlinephone(delUser.getHotlinephone());
        entity.setCreateTime(new Date());
        entity.setCreateUserid(loginUserEntity.getId());
        entity.setCreateUsername(loginUserEntity.getName());
        entity.setAccId(delUser.getAccId());
        entity.setIdentityType(delUser.getIdentityType());
        user.saveUnbindLog(entity);
    }

    /**
     * 去查看账户
     *
     * @param id      账户页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model, HttpServletRequest request) {
        UserResponse response = user.getUserById(id);
        UserEntity userEntity = response.getEntity();
        AttachmentListResponse headImgRes = attachmentInterface.queryByResourceIdAndResouceType(String.valueOf(id),
                "hgs_user_headImg");

        if (null != headImgRes.getObjectList() && !headImgRes.getObjectList().isEmpty()) {
            BaseAttachment attachment = (BaseAttachment) headImgRes.getObjectList().get(0);
            userEntity.setHeadImgURL(attachment.getRemotePath());
        } else {
            userEntity.setHeadImgURL("");
        }

        AttachmentListResponse fullImgRes = attachmentInterface.queryByResourceIdAndResouceType(String.valueOf(id),
                "hgs_user_fullImg");
        if (null != fullImgRes.getObjectList() && !fullImgRes.getObjectList().isEmpty()) {
            BaseAttachment attachment = (BaseAttachment) fullImgRes.getObjectList().get(0);
            userEntity.setFullImgURL(attachment.getRemotePath());
        } else {
            userEntity.setFullImgURL("");
        }
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>(10);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_REAL_DEPT_KEY);
        if (PathUtil.isAdminDept(departmentEntity)) {
            departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
        }
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        map.put("LIKE_urlPath", deptEntity.getEntity().getUrlPath());
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> models = resp.getObjectList();

        DepartmentResponse currentDept = department.getDepartmentById(response.getEntity().getDeptId());
        model.addAttribute("departList", models);
        if (currentDept.getEntity() != null) {
            model.addAttribute("currentDept", currentDept.getEntity());
        }
        model.addAttribute("action", "show");
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    @RequestMapping(value = "/detail/{id}", method = {RequestMethod.GET})
    public String showDeatilForm(@PathVariable(value = "id") Integer id, Model model, HttpServletRequest request) {
        UserResponse response = user.getUserById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改账户
     *
     * @param id      账户页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, HttpServletRequest request, Model model) {
        UserResponse response = user.getUserById(id);
        UserEntity userEntity = response.getEntity();
        AttachmentListResponse headImgRes = attachmentInterface.queryByResourceIdAndResouceType(String.valueOf(id), "hgs_user_headImg");
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>();

        if (null != headImgRes.getObjectList() && !headImgRes.getObjectList().isEmpty()) {
            BaseAttachment attachment = (BaseAttachment) headImgRes.getObjectList().get(0);
            userEntity.setHeadImgURL(attachment.getRemotePath());
        } else {
            userEntity.setHeadImgURL("");
        }

        AttachmentListResponse fullImgRes = attachmentInterface.queryByResourceIdAndResouceType(String.valueOf(id), "hgs_user_fullImg");
        if (null != fullImgRes.getObjectList() && !fullImgRes.getObjectList().isEmpty()) {
            BaseAttachment attachment = (BaseAttachment) fullImgRes.getObjectList().get(0);
            userEntity.setFullImgURL(attachment.getRemotePath());
        } else {
            userEntity.setFullImgURL("");
        }

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_REAL_DEPT_KEY);
        if (PathUtil.isAdminDept(departmentEntity)) {
            departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
        }
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        map.put("LIKE_urlPath", deptEntity.getEntity().getUrlPath());
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> models = resp.getObjectList();

        DepartmentResponse currentDept = department.getDepartmentById(response.getEntity().getDeptId());
        model.addAttribute("departList", models);
        if (currentDept.getEntity() != null) {
            model.addAttribute("currentDept", currentDept.getEntity());
        }

        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改账户
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateUser(
            @Valid UserVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
            Model model, HttpServletRequest httpRequest
    ) {
        UserEntity entity = vo.getEntity();
        if (entity.getLimitLogin() == null) {
            entity.setLimitLogin("0");
        }
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                UserRequest request = new UserRequest();
                UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
                //获取更新前用户信息
                UserEntity oldEntity = user.getById(entity.getId());
                oldEntity.setUpdateUserid(entity.getId());
                oldEntity.setUpdateUsername(entity.getName());
                oldEntity.setUpdateTime(new Date());

                if (!entity.getDeptId().equals(userEntity.getDeptId())) {
                    DepartmentResponse departmentEntity = department.getDepartmentById(entity.getDeptId());
                    oldEntity.setDeptUrlPath(departmentEntity.getEntity().getUrlPath());
                }
                oldEntity.setName(entity.getName());
                oldEntity.setRealName(entity.getRealName());
                oldEntity.setMobile(entity.getMobile());
                oldEntity.setPosition(entity.getPosition());
                oldEntity.setIsFreeMan(entity.getIsFreeMan());
                oldEntity.setLimitLogin(entity.getLimitLogin());
                request.setEntity(oldEntity);

                Map<String, Object> checkExsitSearchMap = new HashMap<>(10);
                checkExsitSearchMap.put("EQ_mobile", entity.getMobile());
                checkExsitSearchMap.put("NOTEQ_id", entity.getId());
                UserListRequest userListRequest = new UserListRequest();
                userListRequest.setSearchParams(checkExsitSearchMap);
                UserListResponse userListResponse = user.getUserList(userListRequest);
                if (null != userListResponse && CollectionUtils.isNotEmpty(userListResponse.getObjectList())) {
                    throw new IllegalServiceParameterException("手机号已经存在");
                }

                UserResponse userRsp = user.getUserById(entity.getId());
                UserEntity tmpEntity = userRsp.getEntity();
                if (tmpEntity != null && !StringUtils.isEmpty(tmpEntity.getRealName()) && !StringUtils.isEmpty(
                        entity.getRealName()) && !tmpEntity.getRealName().equals(entity.getRealName())) {
                    customer.updateManager(entity.getId(), entity.getRealName());
                }
                //改变用户名需要同步给im
                String env = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.env");
                if ("production".equalsIgnoreCase(env) && !oldEntity.getRealName().equals(entity.getRealName())) {
                    if(org.apache.commons.lang.StringUtils.isNotBlank(oldEntity.getAccId())){
                        String token = getImToken();
                        List<NameValuePair> cornetInParam = new ArrayList<>();
                        cornetInParam.add(new BasicNameValuePair("accid", oldEntity.getAccId()));
                        cornetInParam.add(new BasicNameValuePair("username", entity.getRealName()));
                        String updateResult = HttpUtil.doPostWithHeader("http://yunxinim.house365.com/api/5b9235bea9f88", cornetInParam, token, "");
                        logger.info("******SYNC_TO_CRM_RESULT*******" + updateResult);
                    }
                }

                user.updateUserAndSyncToWechat(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/user/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }


    /**
     * 查询账户
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        UserEntity ue = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        searchParams.put("EQ_deptUrlPath3", ue.getDeptUrlPath());
        searchParams.put("LIKE_deptUrlPath2", ue.getDeptUrlPath());

        UserListRequest listRequest = new UserListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        UserListResponse response = user.getUserList(listRequest);

        // 查询用户名下是否有客户
        List<UserVo> lstUserVo = null;
        if (response != null && CollectionUtils.isNotEmpty(response.getObjectList())) {
            lstUserVo = new ArrayList<>(response.getObjectList().size());
            for (UserEntity userEntity : response.getObjectList()) {

                UserVo userVo = new UserVo();
                userVo.setEntity(userEntity);

                Map<String, Object> searchMap = new HashMap<>(10);
                searchMap.put("managerId", userEntity.getId());
                searchMap.put("isPrivate", 1);
                searchMap.put("limit", 1);
                int count = customer.queryCount(searchMap);
                if (count > 0) {
                    userVo.setHasCustomers(true);
                }
                lstUserVo.add(userVo);
            }
        }
        //添加权限，同步im只在线上展示
        String env = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.env");
        if ("production".equals(env)) {
            model.addAttribute("showIm", 1);
        } else {
            model.addAttribute("showIm", 0);
        }
//        model.addAttribute("showIm", 1);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("users", lstUserVo);

        request.getSession().setAttribute(SessionConstants.THREAD_TREE_DEPT_KEY, searchParams.get("EQ_deptId"));
        return getAutoUrl();
    }

    @RequestMapping(value = "authorize/{userId}", method = RequestMethod.GET)
    public String authorize(@PathVariable Integer userId, HttpServletRequest httpRequest, Model model) {
        UserEntity userEntity = user.getUserById(userId).getEntity();

        RoleListRequest roleListRequest = new RoleListRequest();
        roleListRequest.setPaging(new Page(Integer.MAX_VALUE));
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("EQ_deptId", PathUtil.extractDept(userEntity.getDeptUrlPath()));
        roleListRequest.setSearchParams(searchMap);
        RoleListResponse roleListResponse = role.getRoleList(roleListRequest);

        UserRoleListRequest userRoleListRequest = new UserRoleListRequest();
        userRoleListRequest.setPaging(new Page(Integer.MAX_VALUE));
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("EQ_userId", userId);
        userRoleListRequest.setSearchParams(paraMap);
        UserRoleListResponse userRoleList = userRole.getUserRoleList(userRoleListRequest);

        List<RoleEntity> rolesList = roleListResponse.getObjectList();
        List<UserRoleEntity> userRolesList = userRoleList.getObjectList();

        for (RoleEntity roleEntity : rolesList) {
            roleEntity.setAuthorized(false);
            for (UserRoleEntity userRoleEntity : userRolesList) {
                if (userRoleEntity.getRoleId().intValue() == roleEntity.getId().intValue()) {
                    roleEntity.setAuthorized(true);
                }
            }
        }

        model.addAttribute("roles", rolesList);
        model.addAttribute("userId", userId);
        return getAutoUrl();
    }

    /**
     * 锁定用户
     *
     * @param id
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "lock/{id}", method = {RequestMethod.GET})
    public String lock(@PathVariable Integer id, Model model, HttpServletRequest request) {
        UserResponse rsp = user.getUserById(id);
        if (rsp.getEntity() != null) {
            UserEntity entity = rsp.getEntity();
            entity.setUpdateTime(new Date());
            entity.setEnabled(false);
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            entity.setUpdateUserid(userEntity.getId());
            entity.setUpdateUsername(userEntity.getName());
            UserRequest userRequest = new UserRequest();
            userRequest.setEntity(entity);
            user.updateUser(userRequest);
            //同步冻结状态至微信企业号
            user.updateUserAndSyncToWechat(userRequest);

            if (!Strings.isNullOrEmpty(entity.getHotlinephone())) {
                user.unbindHotlinePhone(entity);
            }

        }
        return "redirect:/user";
    }

    @RequestMapping(value = "unlock/{id}", method = {RequestMethod.GET})
    public String unlock(@PathVariable Integer id, Model model, HttpServletRequest request) {
        UserResponse rsp = user.getUserById(id);
        if (rsp.getEntity() != null) {
            UserEntity entity = rsp.getEntity();
            entity.setUpdateTime(new Date());
            entity.setEnabled(true);
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            entity.setUpdateUserid(userEntity.getId());
            entity.setUpdateUsername(userEntity.getName());
            UserRequest userRequest = new UserRequest();
            userRequest.setEntity(entity);
            user.updateUser(userRequest);
            //同步冻结状态至微信企业号
            user.updateUserAndSyncToWechat(userRequest);
        }
        return "redirect:/user";
    }


    @RequestMapping(value = "getManagerByPid", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String getManagerByPid(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String managername = request.getParameter("managername");
        List<UserEntity> list = user.getManagerByPid(userEntity.getId(), managername);
        JSONArray jarr = JSONArray.fromObject(list);
        JSONObject jo = new JSONObject();
        JSONObject jo2 = new JSONObject();
        jo.put("list", jarr);
        jo2.put("data", jo);
        return jo2.toString();
    }

    @RequestMapping(value = "getUserAjax", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Object getUserAjax(
            @RequestParam(value = "dept", required = false) String dept,
            @RequestParam(value = "queryUser", required = false) String queryUser
    ) {
        Set<String> deptIds = new HashSet<>();
        Set<UserEntity> userEntities = new HashSet<>();
        if (dept.contains(",")) {
            String[] depts = dept.split(",");
            deptIds.addAll(Lists.newArrayList(depts));
        } else {
            deptIds.add(dept);
        }

        Map<String, Object> map = new HashMap<>(10);
        for (String deptId : deptIds) {
            DepartmentResponse deptEntity = department.getDepartmentById(Integer.valueOf(deptId));
            UserListResponse ulr = user.getUserListByDept(deptEntity.getEntity(), map, new Page(Integer.MAX_VALUE));
            if (ulr.getObjectList() != null && !ulr.getObjectList().isEmpty()) {
                userEntities.addAll(ulr.getObjectList());
            }
        }

        queryUser = "," + queryUser + ",";

        for (UserEntity user : userEntities) {
            if (queryUser.contains("," + user.getId() + ",")) {
                user.setWeiXinId("1");
            }
        }

        return userEntities;
    }

    @RequestMapping(value = "/syncToWechat/{id}")
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public String syncToWechat(@PathVariable String id, HttpServletRequest request) {
        String result = "success";
        try {
            if (!StringUtils.isEmpty(id)) {
                UserRequest userRequest = new UserRequest();
                if (id.contains(",")) {
                    String[] ids = id.split(",");
                    for (int i = 0; i < ids.length; i++) {
                        UserResponse res = user.getUserById(Integer.valueOf(ids[i]));
                        if (res != null && res.getEntity() != null) {
                            userRequest.setEntity(res.getEntity());
                            user.syncToWechat(userRequest);
                        }
                    }
                } else {
                    UserResponse res = user.getUserById(Integer.valueOf(id));
                    if (res != null && res.getEntity() != null) {
                        userRequest.setEntity(res.getEntity());
                        user.syncToWechat(userRequest);
                    }
                }
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage());
            result = "fail";
        }

        return result;
    }

    /**
     * 去新增角色
     *
     * @return 结果视图
     */
    @RequestMapping(value = "revertPassword")
    @ResponseBody
    public void revertPassword(Integer userId) {
        UserEntity userEntity = user.getUserById(userId).getEntity();
        userEntity.setPassword("1c8a30d8287dc110640dcb5858290e22");
        UserRequest userRequest = new UserRequest();
        userRequest.setEntity(userEntity);
        user.updateUser(userRequest);
    }

    private final String CROP_ID = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.CROP_ID");
    private final String SECRET = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.IM.SECRET");

    /**
     * 新增微信用户同步到数据库
     *
     * @return 结果视图
     */
    @RequestMapping(value = "saveWxUser")
    @ResponseBody
    public HResult saveWxUser() {
        HResult response = new HResult();
        String token = getToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list";
        String result = "";
        try {
            Map<String, String> paramMap = new HashMap<>(5);
            List<String> paramList = new ArrayList<>();
            List<NameValuePair> directParams = new ArrayList<>();
            directParams.add(new BasicNameValuePair("access_token", token));
            directParams.add(new BasicNameValuePair("department_id", "687"));
            directParams.add(new BasicNameValuePair("fetch_child", "1"));
            for (NameValuePair pair : directParams) {
                paramList.add(pair.getName() + "=" + pair.getValue());
            }
            url = url + "?" + Joiner.on("&").join(paramList);
            result = HttpUtil.getHttpRequest(url, paramMap, 100000, "utf-8");
            ObjectMapper mapper = new ObjectMapper();
            if (result != null) {
                Map<String, Map> resultMap = mapper.readValue(result, Map.class);
                Number code = (Number) resultMap.get("errcode");
                if (code.intValue() == 0) {
                    if (resultMap.get("userlist") != null) {
                        List<Map<String, Object>> resultList = (List) resultMap.get("userlist");
                        WxUserEntity entity = new WxUserEntity();
                        if (CollectionUtils.isNotEmpty(resultList)) {
                            for (Map<String, Object> m : resultList) {
                                String wxId = m.get("userid").toString();
                                String userName = m.get("name").toString();
                                String position = m.get("position").toString();
                                String mobile = m.get("mobile").toString();
                                entity.setDepartment("0");
                                entity.setWxId(wxId);
                                entity.setUserName(userName);
                                entity.setPosition(position);
                                entity.setMobile(mobile);
                                entity.setIsDelete(0);
                                user.saveWxUser(entity);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            response.setStatus(500);
            response.setErrorMessage("新增微信用户失败");
            logger.error("新增微信用户失败");
        }
        return response;
    }

    private String getToken() {
        //获取acceToken接口URl
        String getAccessTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
        List<NameValuePair> tokenInParam = new ArrayList<>();

        tokenInParam.add(new BasicNameValuePair("corpid", CROP_ID));
        tokenInParam.add(new BasicNameValuePair("corpsecret", SECRET));
        List<String> newTokenParams = new ArrayList<>();
        Map<String, String> tokenMap = new HashMap<>(5);
        for (NameValuePair pair : tokenInParam) {
            newTokenParams.add(pair.getName() + "=" + pair.getValue());
        }
        String newTokenUrl = getAccessTokenUrl + "?" + Joiner.on("&").join(newTokenParams);
        String tokenResult = "";
        try {
            tokenResult = HttpUtil.getHttpRequest(newTokenUrl, tokenMap, 100000, "utf-8");
            if (Strings.isNullOrEmpty(tokenResult)) {
                throw new ServiceException("获取imtoken失败");
            }
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> map = mapper.readValue(tokenResult, Map.class);
            int code = Integer.parseInt(map.get("errcode").toString());
            if (code == 0) {
                String token = map.get("access_token").toString();
                return token;
            } else {
                logger.error("获取imtoken失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 根据标签名称获取标签信息select2
     *
     * @return 标签信息列表
     */
    @ResponseBody
    @RequestMapping(value = "/getByName")
    public HResult getByName(WxUserEntity entity) {
        HResult result = new HResult();
        try {
            Map<String, Object> map = new HashMap<>(5);
            map.put("userName", entity.getUserName());
            List<WxUserEntity> list = user.queryByCondition(map);
            if (CollectionUtils.isNotEmpty(list)) {
                result.setData(list);
            }
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("查询微信用户失败");
            logger.error("查询微信用户失败", e);
        }
        return result;
    }

    /**
     * 根据标签名称获取标签信息select2
     *
     * @return 标签信息列表
     */
    @ResponseBody
    @RequestMapping(value = "/saveRelation")
    public HResult saveRelation(@RequestBody UserWxRelation entity, HttpServletRequest httpRequest) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            Date date = new Date();
            entity.setIsDelete(0);
            entity.setCreateId(userEntity.getId());
            entity.setCreateName(userEntity.getRealName());
            entity.setUpdateId(userEntity.getId());
            entity.setUpdateName(userEntity.getRealName());
            entity.setCreateTime(date);
            entity.setUpdateTime(date);
            result = user.saveRelation(entity);
        } catch (Exception e) {
            result.setStatus(-1);
            result.setErrorMessage("绑定用户微信关系失败");
            logger.error("绑定用户微信关系失败", e);
        }
        return result;
    }

    /**
     * 根据标签名称获取标签信息select2
     *
     * @return 标签信息列表
     */
    @ResponseBody
    @RequestMapping(value = "/testSend/{userId}")
    public String testSend(@PathVariable int userId) {
        try {
            Map<String, Object> searchMap = new HashMap<>(5);
            searchMap.put("userId", userId);
            Map<String, Object> queryMap = new HashMap<>(5);
            queryMap.put("sender", "tf_3193827");
            queryMap.put("receiver", "qlt_509");
            queryMap.put("time", new Date());
            List<MessageLogEntity> logList = user.queryMsglogList(queryMap);
            if (CollectionUtils.isEmpty(logList)) {
                List<UserWxRelation> relationList = user.queryList(searchMap);
                if (CollectionUtils.isNotEmpty(relationList)) {
                    StringBuilder toUser = new StringBuilder();
                    for (UserWxRelation r : relationList) {
                        toUser.append(r.getWxId()).append("|");
                    }

                    String token = getToken();
                    String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?";
                    url += "access_token=" + token;
                    JSONObject jsonObject = new JSONObject();
                    JSONObject text = new JSONObject();
                    text.put("content", "您有一条新的用户咨询需要处理，请尽快回复客户。");
                    jsonObject.put("agentid", "1000011");
                    jsonObject.put("msgtype", "text");
                    jsonObject.put("touser", toUser.toString());
                    jsonObject.put("text", text);
                    jsonObject.put("safe", "0");
                    jsonObject.put("enable_id_trans", "0");
                    jsonObject.put("enable_duplicate_check", "0");

                    String result = HttpUtil.postWithJson(jsonObject, url, token);
                    if (Strings.isNullOrEmpty(result)) {
                        logger.info("发送企业微信信息失败");
                    } else {
                        logger.info(result);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("发送企业微信信息失败", e);
        }
        return "success";
    }

    @RequestMapping(value = "/syncUserList")
    @ResponseBody
    public HResult syncUserList() {
        HResult result = new HResult();
        user.syncUserList();
        System.out.println("----------syncUserList定时成功---------");
        return result;
    }

    @RequestMapping(value = "/judgeAdmin")
    @ResponseBody
    public HResult judgeAdmin(HttpServletRequest httpRequest) {
        UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        HResult result = new HResult();
        UserEntity entity = user.getById(userEntity.getId());
        if (entity.getDeptId() != 1) {
            result.setStatus(200);
        }
        return result;
    }

    private String getImToken() {
        String accessToken = "";
        try {
            String deciceId = com.house365.web.util.StringUtils.getRandomNumber(10);
            String randStr = com.house365.web.util.StringUtils.getRandomChars(13);
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String signature = HttpUtil.getSignature2(deciceId, randStr, timestamp);
            //获取accesstoken
            HashMap<String, String> accesstokenMap = new HashMap<>(5);
            accesstokenMap.put("version", "v3.0");
            //获取acceToken接口URl
            String getAccessTokenUrl = "http://yunxinim.house365.com/api/5b0cc34464a64";
            List<NameValuePair> tokenInParam = new ArrayList<>();
            tokenInParam.add(new BasicNameValuePair("app_id", "89962055"));
            tokenInParam.add(new BasicNameValuePair("app_secret", "pMHTUWAoOGSjaToIhHKwmQJKWZcAAvjN"));
            tokenInParam.add(new BasicNameValuePair("device_id", deciceId));
            tokenInParam.add(new BasicNameValuePair("rand_str", randStr));
            tokenInParam.add(new BasicNameValuePair("timestamp", timestamp));
            tokenInParam.add(new BasicNameValuePair("signature", signature));

            List<String> newTokenParams = new ArrayList<>();
            for (NameValuePair pair : tokenInParam) {
                newTokenParams.add(pair.getName() + "=" + pair.getValue());
            }
            String newTokenUrl = getAccessTokenUrl + "?" + Joiner.on("&").join(newTokenParams);
            String tokenResult = "";
            tokenResult = HttpUtil.getHttpRequest(newTokenUrl, accesstokenMap, 100000, "utf-8");
            if (Strings.isNullOrEmpty(tokenResult)) {
                throw new ServiceException("get token failed");
            }
            JSONObject json = JSONObject.fromObject(tokenResult);
            JSONObject jo = json.getJSONObject("data");
            accessToken = jo.getString("access_token");
            logger.info("******SYNC_TO_CRM_RESULT ACCESS_TOKEN*******" + accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

}
