package com.jeeplus.modules.API.easemob;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.iim.dao.LayGroupUserDao;
import com.jeeplus.modules.iim.entity.ChatHistory;
import com.jeeplus.modules.iim.entity.LayGroup;
import com.jeeplus.modules.iim.entity.LayGroupUser;
import com.jeeplus.modules.iim.service.ChatHistoryService;
import com.jeeplus.modules.iim.service.LayGroupService;
import com.jeeplus.modules.oa.entity.OaNotify;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.utils.ErrorCode;
import io.swagger.client.model.*;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLDecoder;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.security.shiro.session.SessionDAO;
import com.jeeplus.common.utils.RequestUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 环信Controller
 *
 * @author mengxy
 * @version 2017-6-5
 */
@Controller

@RequestMapping(value = "${frontPath}/easemob")
public class EasemobController extends BaseController {

    @Autowired
    private UserDao userDao;
    @Autowired
    private SystemService systemService;
    @Autowired
    private LayGroupService layGroupService;
    @Autowired
    private ChatHistoryService chatHistoryService;


	/**
	 * 新增好友
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "addFriend", method = RequestMethod.POST)
	public AjaxJson addFriend(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
		try {
            String userId = requestMap.get("userId");
            User currentUser = UserUtils.getUser();
            User user = UserUtils.get(userId);
            if (userDao.findFriendByStatus(currentUser.getId(), user.getId()) == null) {

                userDao.insertFriend(IdGen.uuid(), currentUser.getId(), user.getId(),"0","0");// 添加对方为好友
                 userDao.insertFriend(IdGen.uuid(), user.getId(),
                 currentUser.getId(),"0","1");//同时把自己添加为对方的好友
                j.setMsg("已发送申请！");
            }else {
                j.setMsg("已添加对方为好友！");
                j.setSuccess(true);
                j.setErrorCode(ErrorCode.code_1009);
            }
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
		    logger.error("-----------------------");
		    logger.error("Exception e"+e);
            logger.error("-----------------------");
            j.setSuccess(false);
            j.setMsg("新增好友失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;

	}
	/**
	 * 通讯录展示提示
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "contactFriendTip", method = RequestMethod.GET)
	public AjaxJson contactFriendTip(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
		try {
            Map<String, Object> map = new HashMap<>();
            String userId = requestMap.get("userId");
            User user = null;
            if (StringUtils.isNotBlank(userId)){
                user = UserUtils.get(userId);
            }else {
                user = UserUtils.getUser();
            }
            List<User> users = userDao.findUserByStatus(user);
            List<User> userAudits = userDao.findUserByStatusAudit(user);
            if((users==null || users.size()==0) && (userAudits == null || userAudits.size() == 0)){
                map.put("isApply",0);
                map.put("number",0);
            }else {
                map.put("isApply",1);
                map.put("number",users.size()+userAudits.size());
            }
            j.setMsg("通讯录提示成功！");
            j.put("data",map);
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("通讯录提示失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;
	}
	/**
	 * 通讯录展示提示
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "friendApplyList", method = RequestMethod.GET)
	public AjaxJson friendApplyList (HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
		try {
		    List<Map<String,Object>> ApplyList = new ArrayList<>();
            String userId = requestMap.get("userId");

            if (StringUtils.isBlank(userId)){
                userId = UserUtils.getUser().getId();
            }
            User user = new User(userId);
            List<User> users = userDao.findFriendAll(user);
            if(users!=null && users.size()!=0){
                for (User u:users) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("compnayName", u.getCompany().getName());
                    map.put("department", u.getOffice().getName());
                    map.put("userName", u.getName());
                    map.put("userPhone", u.getLoginName());
                    map.put("isAgreed", u.getAuditStatus());
                    map.put("Id", u.getId());
                    ApplyList.add(map);
                }
            }
            j.setMsg("好友申请列表获取成功！");
            j.put("data",ApplyList);
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("好友申请列表获取失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;
	}
	/**
	 * 通讯录展示提示
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "friendSearch", method = RequestMethod.GET)
	public AjaxJson friendSearch (HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
		try {
		    List<Map<String,Object>> ApplyList = new ArrayList<>();
            String userId = requestMap.get("userId");
            String userName = requestMap.get("userName");
            String phone = requestMap.get("phone");

            if (StringUtils.isBlank(userId)){
                userId = UserUtils.getUser().getId();
            }
            User user = new User(userId);
            List<User> users = userDao.findFriendAll(user);
            if(users!=null && users.size()!=0){
                for (User u:users) {
                    if (StringUtils.isNotBlank(phone)){
                        if (u.getLoginName().equals(phone)){
                            if (StringUtils.isNotBlank(userName)){
                                if (u.getName().contains(userName)){
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("compnayName", u.getCompany().getName());
                                    map.put("department", u.getOffice().getName());
                                    map.put("userName", u.getName());
                                    map.put("userPhone", u.getLoginName());
                                    map.put("isAgreed", u.getAuditStatus());
                                    map.put("photo", u.getPhoto());
                                    map.put("Id", u.getId());
                                    ApplyList.add(map);
                                }
                            }else {
                                Map<String, Object> map = new HashMap<>();
                                map.put("compnayName", u.getCompany().getName());
                                map.put("department", u.getOffice().getName());
                                map.put("userName", u.getName());
                                map.put("userPhone", u.getLoginName());
                                map.put("isAgreed", u.getAuditStatus());
                                map.put("Id", u.getId());
                                map.put("photo", u.getPhoto());
                                ApplyList.add(map);
                            }
                        }
                    }else {
                        if (StringUtils.isNotBlank(userName)){
                            if (u.getName().contains(userName)){
                                Map<String, Object> map = new HashMap<>();
                                map.put("compnayName", u.getCompany().getName());
                                map.put("department", u.getOffice().getName());
                                map.put("userName", u.getName());
                                map.put("userPhone", u.getLoginName());
                                map.put("Id", u.getId());
                                map.put("isAgreed", u.getAuditStatus());
                                map.put("photo", u.getPhoto());
                                ApplyList.add(map);
                            }
                        }else {
                            Map<String, Object> map = new HashMap<>();
                            map.put("compnayName", u.getCompany().getName());
                            map.put("department", u.getOffice().getName());
                            map.put("userName", u.getName());
                            map.put("photo", u.getPhoto());
                            map.put("userPhone", u.getPhone());
                            map.put("isAgreed", u.getAuditStatus());
                            map.put("Id", u.getId());
                            ApplyList.add(map);
                        }
                    }

                }
            }
            j.setMsg("好友申请列表获取成功！");
            j.put("data",ApplyList);
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("好友申请列表获取失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;
	}

    /**
     * 通讯录展示提示
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "applyDetail", method = RequestMethod.GET)
    public AjaxJson applyDetail (HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
        try {
            String userId = requestMap.get("userId");
            if (StringUtils.isBlank(userId)){
                j.setMsg("获取好友详情失败,参数不能为空！");
                return j;
            }
            User u = userDao.findFriendInfo(UserUtils.getUser().getId(),userId);
            if (u==null || StringUtils.isBlank(u.getId())){
                j.setMsg("获取好友详情失败,无当前好友信息！");
                return j;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("compnayName", u.getCompany().getName());
            map.put("department", u.getOffice().getName());
            map.put("userName", u.getName());
            map.put("userPhone", u.getLoginName());
            map.put("isAgreed", u.getAuditStatus());
            map.put("Id", u.getId());
            j.setMsg("获取好友详情成功！");
            j.put("data",map);
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("获取好友详情失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
        return j;
    }
	/**
	 * 我的好友提示     展示数字提示和提示信息
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "mytFriendTip", method = RequestMethod.GET)
	public AjaxJson mytFriendTip(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
		try {
            Map<String, Object> map = new HashMap<>();
            String userId = requestMap.get("userId");
            User user;
            if (StringUtils.isNotBlank(userId)){
                user = UserUtils.get(userId);
            }else {
                user = UserUtils.getUser();
            }
            List<User> users = userDao.findUserByStatus(user);
            List<User> userAudits = userDao.findUserByStatusAudit(user);
            if(users==null || users.size()==0){
                map.put("isApply",0);
                map.put("applyNumber",0);
            }else {
                map.put("isApply",1);
                map.put("applyNumber",users.size());
            }
            if(userAudits == null || userAudits.size() == 0){
                map.put("isTip",0);
                map.put("tipNumber",0);
            }else {
                map.put("isTip",1);
                map.put("tipNumber",userAudits.size());
            }
            j.put("data",map);
            j.setMsg("展示数字提示和提示信息成功！");
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("展示数字提示和提示信息失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;
	}
	/**
	 * 点击查看提示个人
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "solveApply", method = RequestMethod.GET)
	public AjaxJson solveApply (HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
		try {
            Map<String, Object> map = new HashMap<>();
            String userId = requestMap.get("userId");
            User user;
            if (StringUtils.isNotBlank(userId)){
                user = UserUtils.get(userId);
            }else {
                user = UserUtils.getUser();
            }
            List<User> userAudits = userDao.findUserByStatusAudit(user);
            if(userAudits == null || userAudits.size() == 0){
                j.setMsg("查看好友审批信息失败,未读取到数据！");
            }else {
                User user1 = userAudits.get(0);
                map.put("id",user1.getId());
                map.put("userName",user1.getName());
                map.put("status",user1.getAuditStatus());
                userDao.updateUserRead(user.getId(),user1.getId());
            }
            j.put("data",map);
            j.setMsg("查看好友审批信息成功！");
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("查看好友审批信息失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;
	}
	/**
	 * 我的好友提示     展示数字提示和提示信息
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "solveAllApply", method = RequestMethod.GET)
	public AjaxJson solveAllApply (HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
		try {
            Map<String, Object> map = new HashMap<>();
            String userId = requestMap.get("userId");
            User user;
            if (StringUtils.isNotBlank(userId)){
                user = UserUtils.get(userId);
            }else {
                user = UserUtils.getUser();
            }
            List<User> userAudits = userDao.findUserByStatusAudit(user);
            j.put("data",map);
            if(userAudits == null || userAudits.size() == 0){
                j.setMsg("查看好友审批信息,未读取到数据！");
                return j;
            }else {
                for (User user1:userAudits){
                    userDao.updateUserRead(user.getId(),user1.getId());
                }
            }
            j.setMsg("查看好友审批信息成功！");
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("查看好友审批信息失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;
	}
	/**
	 * 搜索好友
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "searchFriend", method = RequestMethod.GET)
	public AjaxJson searchFriend(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
		try {
            String userName = requestMap.get("userName");
            String Phone = requestMap.get("Phone");
            User user = new User();
            if (StringUtils.isNotBlank(userName)){
                user.setName(userName);
            }
            if (StringUtils.isNotBlank(Phone)){
                user.setMobile(Phone);
            }
            user.setId(UserUtils.getUser().getId());
            List<User> users = userDao.findUserByMobileOrName(user);
            List<Map<String,Object>> maps = new ArrayList<>();
            if (users!=null && users.size()!=0){
                for (User user1:users){
                    Map<String,Object> map = new HashMap<>();
                    map.put("compnayName",user1.getCompany().getName());
                    map.put("department",user1.getOffice().getName());
                    map.put("userName",user1.getName());
                    map.put("userPhone",user1.getMobile());
                    map.put("imageURl",user1.getPhoto());
                    map.put("id",user1.getId());
                    maps.add(map);
                }
            }
            j.put("data",maps);
            j.setMsg("搜索好友成功！");
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("搜索好友失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;

	}

    /**
     * 搜索用户
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "searchUser", method = RequestMethod.GET)
    public AjaxJson searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
        try {
            String userName = requestMap.get("userName");
            String Phone = requestMap.get("Phone");
            User user = new User();
            if (StringUtils.isNotBlank(userName)){
                user.setName(userName);
            }
            if (StringUtils.isNotBlank(Phone)){
                user.setMobile(Phone);
            }
            List<User> users = userDao.findFriendByMobileOrUserName(user);
            List<Map<String,Object>> maps = new ArrayList<>();
            if (users!=null && users.size()!=0){
                for (User user1:users){
                    Map<String,Object> map = new HashMap<>();
                    map.put("compnayName",user1.getCompany().getName());
                    map.put("department",user1.getOffice().getName());
                    map.put("userName",user1.getName());
                    map.put("userPhone",user1.getMobile());
                    map.put("id",user1.getId());
                    maps.add(map);
                }
            }
            j.put("data",maps);
            j.setMsg("搜索好友成功！");
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("搜索好友失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
        return j;

    }

	/**
	 * 删除好友
	 *
	 * @throws IOException
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "deleteFriend", method = RequestMethod.POST)
	public AjaxJson deleteFriend(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
		String friendId = requestMap.get("friendId");
		String userId = requestMap.get("userId");
        AjaxJson j = new AjaxJson();
        try {
            User user = UserUtils.get(friendId);
            User currentUser = new User();
            if (StringUtils.isBlank(userId)){
                currentUser = UserUtils.getUser();
            }else {
                currentUser = UserUtils.get(userId);
            }
            if (userDao.findFriend(currentUser.getId(), user.getId()) != null) {
                userDao.deleteFriend(currentUser.getId(), user.getId());// 删除好友
                 userDao.deleteFriend(user.getId(),
                 currentUser.getId());//同时把自己从对方的好友列表删除
                j.setSuccess(true);
                j.setMsg("删除好友成功");
                j.setErrorCode(ErrorCode.code_1004);
            }else {
                j.setSuccess(true);
                j.setMsg("删除好友失败，无当前好友！");
                j.setErrorCode(ErrorCode.code_1009);
            }
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("删除好友失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;

	}
	/**
	 * 删除好友
	 *
	 * @throws IOException
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "AgreedFriend", method = RequestMethod.POST)
	public AjaxJson AgreedFriend(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
		String friendId = requestMap.get("friendId");
		String userId = requestMap.get("userId");
		String agreed = requestMap.get("agreed");
        AjaxJson j = new AjaxJson();
        try {
            User friend = UserUtils.get(friendId);
            User currentUser = new User();
            if (StringUtils.isBlank(userId)){
                currentUser = UserUtils.getUser();
            }else {
                currentUser = UserUtils.get(userId);
            }
            boolean b = false;
            if (agreed.equals("1")){
                if (friend != null && userDao.findFriend(currentUser.getId(), friend.getId()) == null) {
                    userDao.friendAudit(currentUser.getId(), friend.getId());// 确认通过好友
                    userDao.friendAudit(friend.getId(),
                            currentUser.getId());//同时把自己从对方的好友列表确认通过好友
                    b= true;
                }
            }else if (agreed.equals("2")){
                if (friend != null && userDao.findFriend(currentUser.getId(), friend.getId()) == null) {
                    userDao.friendAuditNo(currentUser.getId(), friend.getId());// 确认通过好友
                    userDao.friendAuditNo(friend.getId(),
                            currentUser.getId());//同时把自己从对方的好友列表确认通过好友
                    b= true;
                }
            }
            if (b){
                j.setMsg("好友申请已处理！");
            }else {
                j.setMsg("好友申请处理失败！");
            }
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("删除好友失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
		return j;

	}

	/**
	 * 获取好友
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "getFriend", method = RequestMethod.POST)
	public AjaxJson getFriend(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Principal principal = UserUtils.getPrincipal();
		AjaxJson j = new AjaxJson();
        try {
            // 我的好友--->常用联系人
            User currentUser = UserUtils.getUser();
            List<User> users = userDao.findFriends(currentUser);
            List<Map<String,Object>> maps = new ArrayList<>();
            if (users!=null && users.size()!=0){
                for (User user1:users){
                    Map<String,Object> map = new HashMap<>();
                    map.put("compnayName",user1.getCompany().getName());
                    map.put("department",user1.getOffice().getName());
                    map.put("userName",user1.getName());
                    map.put("userPhone",user1.getMobile());
                    map.put("imageURl",user1.getPhoto());
                    map.put("userId",user1.getId());
                    maps.add(map);
                }
            }
            j.put("data",maps);
            j.setSuccess(true);
            j.setMsg("获取好友成功！");
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("获取好友失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }
        return j;


    }

	/**
	 * 获取群组
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "getGroups", method = RequestMethod.GET)
	public AjaxJson getGroups(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson j = new AjaxJson();
        try {
            HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            String pageSize = requestMap.get("pageSize");
            String pageNo = requestMap.get("pageNo");
            String userId = requestMap.get("userId");
            if(userId == null ){
                userId = UserUtils.getUser().getId();
            }
            LayGroup layGroup =new LayGroup();
            layGroup.setCreateBy(new User(userId));
            Page<LayGroup> page = layGroupService.findPage(new Page<LayGroup>(request, response),layGroup );
            j.setSuccess(true);
            j.setMsg("获取群组成功");
            if (page.getList() == null) {
                j.setSuccess(false);
                j.setErrorCode(ErrorCode.code_2005);
                j.setMsg("获取群组失败");
                j.put("group", page.getList());
            } else {
                j.put("maxNum", page.getCount());
                List<Map<String,Object>> maps = new ArrayList<>();
                if (Integer.parseInt(pageNo) <= page.getTotalPage()) {
                    if (page.getList()!=null && page.getList().size()!=0){
                        for (LayGroup layGroup1 :page.getList()){
                            Map<String,Object> map= new HashMap<>();
                            map.put("name",layGroup1.getGroupname());
                            map.put("groupid",layGroup1.getId());
                            map.put("groupImage",layGroup1.getAvatar());
                            maps.add(map);
                        }
                    }
                }
                j.put("data", maps);
                j.setMsg("获取群组成功");
                j.setErrorCode(ErrorCode.code_1004);
            }
        }catch (Exception e){
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_3001);
            j.setMsg("获取群组失败");
            return j;
        }
		return j;
	}

	/**
	 * 获取群组详情
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "getGroupsInfo", method = RequestMethod.GET)
	public AjaxJson getGroupsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
           /* HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            String groups = requestMap.get("groups");
            AjaxJson j = new AjaxJson();
        try {
            String[] grousIds= groups.split(",");
            List<LayGroup> layGroups = new ArrayList<>();
            for (String grousId:grousIds){
                LayGroup layGroup = layGroupService.get(grousId);
                if (layGroup!=null && StringUtils.isNotBlank(layGroup.getId())){
                    layGroups.add(layGroup);
                }
            }
            j.put("group", layGroups);
            j.setErrorCode(ErrorCode.code_1004);
            return j;
        }catch (Exception e){
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_3001);
            j.setMsg("获取群组详情失败");
            return j;
        }*/
        HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        String groupId = requestMap.get("groupId");
        AjaxJson j = new AjaxJson();
        try {
            LayGroup layGroup = layGroupService.get(groupId);
            if (layGroup!=null && StringUtils.isNotBlank(layGroup.getId())){
                List<LayGroupUser> layGroupUsers = layGroup.getLayGroupUserList();
                Map<String,Object> map = new HashMap<>();
                map.put("groupName",layGroup.getGroupname());
                map.put("id",layGroup.getId());
                map.put("descriptionq",layGroup.getRemarks());
                map.put("groupImage",layGroup.getAvatar());
                map.put("username",UserUtils.get(layGroup.getCreateBy().getId()).getName());
                map.put("status",UserUtils.getUser().getId().equals(layGroup.getCreateBy().getId())?true:false);
                List<Map<String,Object>> list = new ArrayList<>();
                if (layGroupUsers!=null && layGroupUsers.size()!=0){
                    for (LayGroupUser layGroupUser:layGroupUsers){
                        User user = layGroupUser.getUser();
                        String name = "";
                        String photo = "";
                        if (user != null && StringUtils.isNotBlank(user.getName())) {
                            Map<String,Object> mapUser = new HashMap<>();
                            name = user.getName();
                            photo = user.getPhoto();
                            mapUser.put("name", name);
                            mapUser.put("imageURl", photo);
                            mapUser.put("member", user.getId());
                            if (!user.getId().equals(layGroup.getCreateBy().getId())){
                                mapUser.put("type","2");
                            }else {
                                mapUser.put("type","1");
                            }
                            list.add(mapUser);
                        }

                    }
                }
                map.put("users",list);
                j.put("data", map);
                j.setErrorCode(ErrorCode.code_1004);
            }else {
                j.setErrorCode(ErrorCode.code_4001);
                j.put("data", new HashMap<>());
            }
            return j;
        }catch (Exception e){
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_3001);
            j.setMsg("获取群组详情失败");
            return j;
        }

	}

	/**
	 * 创建群组
	 *
	 * @throws IOException
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "createGroupAndjoinMember", method = RequestMethod.POST)
	public AjaxJson createGroupAndjoinMember(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
		try {
            String groupName = URLDecoder.decode(requestMap.get("groupName")==null?"":requestMap.get("groupName"), "UTF-8");
            String desc = URLDecoder.decode(requestMap.get("desc")==null?"":requestMap.get("desc"), "UTF-8");
            //String groupName = requestMap.get("groupName");
           //String desc = requestMap.get("desc");
            String officeIds = requestMap.get("officeIds");
            String members = requestMap.get("members");
            Set<String> set = new HashSet<String>();
            if(officeIds !=null && !officeIds.equals("")){
                String [] offices = officeIds.split(",");
                for (int i = 0; i < offices.length; i++) {
                    List<User> users = systemService.findUserByOfficeId(offices[i]);
                    for (User user:users){
                        if (!UserUtils.getUser().getId().equals(user.getId())) {
                            set.add(user.getId());
                        }
                    }
                }
            }
            if(members !=null && !members.equals("")){
                String [] users = members.split(",");
                for (int i = 0; i < users.length; i++) {
                    if (!UserUtils.getUser().getId().equals(users[i])){
                        if (!UserUtils.getUser().getId().equals(users[i])) {
                            set.add(users[i]);
                        }
                    }
                }
            }

            if (StringUtils.isBlank(groupName)){
                j.setMsg("创建群组失败,群组名不能为空！");
            }
            LayGroup layGroup = new LayGroup();
            layGroup.setGroupname(groupName);
            List<LayGroupUser> layGroupUserList = Lists.newArrayList();
            if (set!=null && set.size()!=0)
            for (String userId:set){
                LayGroupUser layGroupUser = new LayGroupUser();
                layGroupUser.setUser(new User(userId));
                layGroupUserList.add(layGroupUser);
            }
            layGroup.setLayGroupUserList(layGroupUserList);
            layGroup.setRemarks(desc);
            layGroup.setAvatar("https://gangwan-app.oss-cn-hangzhou.aliyuncs.com/app-img/photo/static/qunzhu.png");
            layGroupService.save(layGroup);//保存

            j.setMsg("创建群组成功");
            Map<String,Object> map = new HashMap<>();
            map.put("name",layGroup.getGroupname());
            map.put("groupid",layGroup.getId());
            map.put("groupImage",layGroup.getAvatar());
            j.put("data", map);
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_3001);
            j.setMsg("获取群组详情失败");
        }
		return j;

	}


	/**
	 * 修改群组
	 *
	 * @throws IOException
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "changeGroupInfo", method = RequestMethod.POST)
	public AjaxJson changeGroupInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
		AjaxJson j = new AjaxJson();
		try {
            String groupId = requestMap.get("groupId");
            String groupName = URLDecoder.decode(requestMap.get("groupName")==null?"":requestMap.get("groupName"), "UTF-8");
            String desc = URLDecoder.decode(requestMap.get("desc")==null?"":requestMap.get("desc"), "UTF-8");
            LayGroup layGroup = layGroupService.getNoOwner(groupId);
            if (StringUtils.isNotBlank(groupName)){
                layGroup.setGroupname(groupName);
            }
            if (StringUtils.isNotBlank(desc)){
                layGroup.setRemarks(desc);
            }
            layGroupService.save(layGroup);
            j.setMsg("修改群组成功");
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            j.setMsg("修改群组失败");
            j.put("group", "");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_2004);
        }

		return j;

	}

    /**
     * 解散群组
     *
     * @throws IOException
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "deleteChatGroup", method = RequestMethod.POST)
    public AjaxJson deleteChatGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        AjaxJson j = new AjaxJson();
        try{
            String groupId = requestMap.get("groupId");
            LayGroup layGroup = layGroupService.getNoOwner(groupId);
            layGroupService.delete(layGroup);
            j.setMsg("解散群组成功");
            j.setErrorCode(ErrorCode.code_1004);
            return j;
        }catch (Exception e){
            j.setMsg("解散群组失败");
            j.setErrorCode(ErrorCode.code_3002);
            j.setSuccess(false);
            return j;
        }

    }


	/**
	 * 新增群组成员
	 *
	 * @throws IOException
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "addUsers", method = RequestMethod.POST)
	public AjaxJson addUsers(HttpServletRequest request, HttpServletResponse response) throws IOException {
		AjaxJson j = new AjaxJson();
        try {
            HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            String groupId = requestMap.get("groupId");
            String members = requestMap.get("members");
            int count = layGroupService.saveUsers(groupId,members);

            j.setMsg("新增成员共" + members.split(",").length + "个," + count + "个成员新增成功! " + "," + (members.split(",").length-count) + "个成员已存在!");
            j.put("group", count);
            j.setErrorCode(ErrorCode.code_1004);
            return j;
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("新增成员失败");
            j.setErrorCode(ErrorCode.code_3002);
            return j;
        }

	}

	/**
	 * 批量移除群组用户
	 *
	 * @throws IOException
	 */
	@Transactional
	@ResponseBody
        @RequestMapping(value = "removeBatchUsersFromChatGroup", method = RequestMethod.POST)
	public AjaxJson removeBatchUsersFromChatGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
		AjaxJson j = new AjaxJson();
        try {
            HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            String groupId = requestMap.get("groupId");
            String members = requestMap.get("members");
            LayGroup layGroup = layGroupService.getNoOwner(groupId);
            if (layGroup!=null && !layGroup.getCreateBy().getId().equals(members)){
                j.setErrorCode(ErrorCode.code_1004);
                j.setMsg("批量移除群组用户成功");
                layGroupService.deleteGroupUser(layGroup,members);
            }else {
                j.setMsg("批量移除群组用户失败");
                j.setErrorCode(ErrorCode.code_1010);
            }
        }catch (Exception e){
            j.setMsg("批量移除群组用户失败");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_3002);
            return j;
        }
		return j;

	}

    /**
     * 移除群组用户
     *
     * @throws IOException
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "outGroup", method = RequestMethod.GET)
    public AjaxJson outGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson j = new AjaxJson();
        try {
            HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            String groupId = requestMap.get("groupId");
            LayGroup layGroup = layGroupService.getNoOwner(groupId);
            if (layGroup!=null && !layGroup.getCreateBy().getId().equals(UserUtils.getUser().getId())){
                j.setErrorCode(ErrorCode.code_1004);
                j.setMsg("退出群组成功");
                int count = layGroupService.deleteGroupUser(layGroup,UserUtils.getUser().getId());
                if (count == 0){
                    j.setMsg("退出群组失败");
                }
            }else {
                j.setMsg("退出群组失败");
                j.setErrorCode(ErrorCode.code_1010);
            }
        }catch (Exception e){
            j.setMsg("退出群组失败");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_3002);
            return j;
        }
        return j;

    }

    /**
     * 移除群组用户
     *
     * @throws IOException
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "removeBatchUserFromChatGroup", method = RequestMethod.POST)
    public AjaxJson removeBatchUserFromChatGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson j = new AjaxJson();
        try {
            HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            String groupId = requestMap.get("groupId");
            String userId = requestMap.get("userId");
            if(userId == null ){
                userId = UserUtils.getUser().getId();
            }
            LayGroup layGroup = layGroupService.getNoOwner(groupId);
            if (layGroup!=null && !layGroup.getCreateBy().getId().equals(userId)){
                j.setErrorCode(ErrorCode.code_1004);
                j.setMsg("移除群组用户成功");
                layGroupService.deleteGroupUser(layGroup,userId);
            }else {
                j.setMsg("移除群组用户失败");
                j.setErrorCode(ErrorCode.code_1010);
            }
        }catch (Exception e){
            j.setMsg("移除群组用户失败");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_3002);
            return j;
        }
        return j;

    }

	/**
	 * 获取群组成员
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "getUsersFromGroup", method = RequestMethod.GET)
	public AjaxJson getUsersFromGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
		AjaxJson j = new AjaxJson();
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
		String groupId = requestMap.get("groupId");
		String username = requestMap.get("userName");
        Map<String,Object> mapTotal = new HashMap<String,Object>();
        List list = new ArrayList();
        try {
            LayGroup layGroup = layGroupService.get(groupId);
            List<LayGroupUser> layGroupUsers = layGroup.getLayGroupUserList();
            if (layGroupUsers!=null && layGroupUsers.size()!=0){
                for (LayGroupUser layGroupUser:layGroupUsers){
                    User user = layGroupUser.getUser();
                    String name = "";
                    String photo = "";
                    if (username!=null && StringUtils.isNotBlank(username)) {
                        if (user != null && StringUtils.isNotBlank(user.getName()) && user.getName().contains(username)) {
                            Map<String,Object> maps = new HashMap<>();
                            name = user.getName();
                            photo = user.getPhoto();
                            maps.put("name", name);
                            maps.put("imageURl", photo);
                            maps.put("member", user.getId());
                            if (!user.getId().equals(layGroup.getCreateBy().getId())){
                                maps.put("type","2");
                            }else {
                                maps.put("type","1");
                            }
                            list.add(maps);
                        }
                    }else {
                        if (user != null && StringUtils.isNotBlank(user.getName())) {
                            Map<String,Object> map = new HashMap<>();
                            name = user.getName();
                            photo = user.getPhoto();
                            map.put("name", name);
                            map.put("imageURl", photo);
                            map.put("member", user.getId());
                            if (!user.getId().equals(layGroup.getCreateBy().getId())){
                                map.put("type","2");
                            }else {
                                map.put("type","1");
                            }
                            list.add(map);
                        }
                    }
                }
            }
            mapTotal.put("data",list);
            j.put("group", mapTotal);
            j.setErrorCode(ErrorCode.code_1004);
            return j;
        }catch (Exception e){
            j.setMsg("获取群组成员信息错误");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_3002);
            return j;
        }
	}

	/**
	 * 修改群主
	 *
	 * @throws IOException
	 */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "transferGroupOwner", method = RequestMethod.POST)
	public AjaxJson transferGroupOwner(HttpServletRequest request, HttpServletResponse response) throws IOException {
		AjaxJson j = new AjaxJson();
        try {
            HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            String groupId = requestMap.get("groupId");
            String newOwner = requestMap.get("newOwner");
            LayGroup layGroup = layGroupService.get(groupId);
            String oldOwner = layGroup.getCreateBy().getId();
            layGroup.setCreateBy(new User(newOwner));
            layGroup.preUpdate();
            List<LayGroupUser> layGroupUsers = layGroup.getLayGroupUserList();
            List<LayGroupUser> layGroupUserList = new ArrayList<>();
            for (LayGroupUser layUser:layGroupUsers){
                String userId = layUser.getUser().getId();
                if (newOwner.equals(userId)){
                    layUser.setIsAdmin("1");
                }else if (oldOwner.equals(layUser.getUser().getId())){
                    layUser.setIsAdmin("0");
                }
                layGroupUserList.add(layUser);
            }
            layGroupService.save(layGroup);
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            j.setMsg("修改群主信息错误");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_3002);
        }
		return j;

	}


	/**
	 * 新增群组屏蔽
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "addBlockUsers", method = RequestMethod.POST)
	public AjaxJson addBlockUsers(HttpServletRequest request, HttpServletResponse response) throws IOException {
		AjaxJson j = new AjaxJson();
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
		String groupId = requestMap.get("groupId");
		String userName = requestMap.get("userName");
        UserNames userNames = new UserNames();
        UserName userList = new UserName();
        userList.add(userName);
        userNames.usernames(userList);
        Object result = null;//easemobChatGroup.addBatchBlockUsersToChatGroup(groupId, userNames);
        logger.info(result.toString());
		JSONObject json = JSONObject.fromObject(result);
		j.put("group", json);
        j.setErrorCode(ErrorCode.code_1004);
		return j;

	}


	/**
	 * 移除群组屏蔽
	 *
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "removeBlockUser", method = RequestMethod.POST)
	public AjaxJson removeBlockUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		AjaxJson j = new AjaxJson();
		HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
		String groupId = requestMap.get("groupId");
		String userId = requestMap.get("userId");
	    String[] userIds = userId.split(",");
	    Object result = null;//easemobChatGroup.removeBatchBlockUsersFromChatGroup(groupId, userIds);
	    logger.info(result.toString());

		JSONObject json = JSONObject.fromObject(result);
        j.put("group", json);
        j.setErrorCode(ErrorCode.code_1004);
		return j;

	}



    /**
     * 删除用户
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "deleteUser", method = RequestMethod.POST)
    public AjaxJson deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson j = new AjaxJson();
        HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        String username = requestMap.get("username");
          /*  Object result = easemobIMUsers.deleteIMUserByUserName(username);
        logger.info(result.toString());

        JSONObject json = JSONObject.fromObject(result);
        j.put("group", json);*/
        j.setErrorCode(ErrorCode.code_1004);
        return j;

    }


    /**
     *  获取用户头像昵称
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "getIMUserPhotoNickname", method = RequestMethod.GET)
    public AjaxJson getIMUserPhotoNickname(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson j=new AjaxJson();
            HashMap<String, String> requestMap = findRequestMap(request);
        String userId = requestMap.get("userId");
        if(userId == null ){
            userId = UserUtils.getUser().getId();
        }
        User user = UserUtils.get(userId);
        Map<String,Object> map = Maps.newHashMap();
            map.put("photo", user.getPhoto());
            map.put("name", user.getName());
        j.put("data", map);
        j.setErrorCode(ErrorCode.code_1004);
        return j;
    }

    /**
     *
     *获取用户 所有群组
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "getIMUserAllChatGroups", method = RequestMethod.GET)
    public AjaxJson getIMUserAllChatGroups(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson j = new AjaxJson();
        try {
            HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            String userId = requestMap.get("userId");
            if(userId == null ){
                userId = UserUtils.getUser().getId();
            }
            Map<String,Object> map = Maps.newHashMap();

            //用户自己创建的群组和属于的群组
            //查找我自己创建的群组
            LayGroup layGroup = new LayGroup();
            layGroup.setCreateBy(new User(userId));
            List<LayGroup> ownerLayGroupList = layGroupService.findList(layGroup);
            //查找我属于的群组
            List<LayGroup> memberLayGroupLists = new ArrayList<>();
            List<LayGroup> memberLayGroupList = layGroupService.findGroupList(UserUtils.get(userId));
            memberLayGroupLists.addAll(memberLayGroupList);
            map.put("ownerList",ownerLayGroupList);
            map.put("memberList",memberLayGroupLists);
            j.put("data", map);
            j.setErrorCode(ErrorCode.code_1004);
            j.setSuccess(true);
            j.setMsg("获取我的群组成功！");
        }catch (Exception e){
            j.put("data", "");
            j.setErrorCode(ErrorCode.code_2004);
            j.setSuccess(false);
            j.setMsg("获取我的群组失败！");
        }

        return j;

    }


    /**
     * 发送消息
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "sendExtMessage", method = RequestMethod.POST)
    public AjaxJson sendExtMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson j = new AjaxJson();


        j.setSuccess(true);
            j.setMsg("发送消息成功");
        Object result = SendMessage();
        JSONObject json = JSONObject.fromObject(result);
        j.put("message", json);
        j.setErrorCode(ErrorCode.code_1004);
        return j;

    }

    /**
     * 获取我的群组
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "getGroupsInfoByUserId", method = RequestMethod.GET)
    public AjaxJson getGroupsInfoByUserId(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson j = new AjaxJson();
        try {
           HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
           String userId = requestMap.get("userId");
           String groupName = URLDecoder.decode(requestMap.get("groupName")==null?"":requestMap.get("groupName"), "UTF-8");
           //String groupName = requestMap.get("groupName");
           if(userId == null ){
               userId = UserUtils.getUser().getId();
           }
           Map<String,Object> map = Maps.newHashMap();

           //用户自己创建的群组和属于的群组
           //查找我属于的群组
          List<LayGroup> ownerLayGroupList = layGroupService.findGroupListOwner(UserUtils.getUser());
          List<LayGroup> memberLayGroupList = layGroupService.findGroupListNotOwner(UserUtils.getUser());
           List<Map<String,Object>> ownermaps = new ArrayList<>();
           List<Map<String,Object>> membermaps = new ArrayList<>();
           if (ownerLayGroupList!=null && ownerLayGroupList.size()!=0){
               for (LayGroup layGroup1 :ownerLayGroupList){
                   Map<String,Object> map1= new HashMap<>();
                   map1.put("name",layGroup1.getGroupname());
                   map1.put("groupid",layGroup1.getId());
                   map1.put("groupImage",layGroup1.getAvatar());
                   ownermaps.add(map1);
               }
           }
           if (memberLayGroupList!=null && memberLayGroupList.size()!=0){
               for (LayGroup layGroup1 :memberLayGroupList){
                   Map<String,Object> map1= new HashMap<>();
                   map1.put("name",layGroup1.getGroupname());
                   map1.put("groupid",layGroup1.getId());
                   map1.put("groupImage",layGroup1.getAvatar());
                   membermaps.add(map1);
               }
           }
           map.put("ownerList",ownermaps);
           map.put("memberList",membermaps);
           j.put("data", map);
           j.setErrorCode(ErrorCode.code_1004);
           j.setSuccess(true);
           j.setMsg("获取我的群组成功！");
       }catch (Exception e){
           j.put("data", "");
           j.setErrorCode(ErrorCode.code_2004);
           j.setSuccess(false);
           j.setMsg("获取我的群组失败！");
       }

        return j;

    }

    /**
     * 获取聊天记录
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "getGroupIdMessage", method = RequestMethod.GET)
    public AjaxJson getGroupIdMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        String time = requestMap.get("time");

        AjaxJson j = new AjaxJson();
        try {
           /* String url = "http://a1.easemob.com/" + OrgInfo.ORG_NAME + "/" + OrgInfo.APP_NAME + "/chatmessages/" + time;
            String result = HttpRequest.sendExportChatMessage(url);*/
            Object result = null;//easemobChatMessage.exportChatMessage(time);
            logger.info(result + "");
            j.setMsg("获取群组详情成功");
            JSONObject json = JSONObject.fromObject(result);
            j.put("group", json);
            j.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("获取群组详情失败");
            j.setErrorCode(ErrorCode.code_3001);
        }


        return j;

    }
    /**
     * 获取聊天记录
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "getIMUserByUserName", method = RequestMethod.GET)
    public AjaxJson getIMUserByUserName(String userId ,HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        String time = requestMap.get("time");

        AjaxJson j = new AjaxJson();
       /* try {
            Object result = easemobIMUsers.getIMUserByUserName(userId);
            logger.info(result.toString());
        }catch (Exception e){
            j.setMsg("获取群组详情失败");
            j.setErrorCode(ErrorCode.code_3001);
        }*/
        return j;

    }

    /**
     *
     * 常用联系人
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "getIMUserContacts", method = RequestMethod.GET)
    public AjaxJson getIMUserContacts(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxJson j = new AjaxJson();
        try {
            String userId = "";
            HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
            if (StringUtils.isBlank(requestMap.get("userId"))) {
                userId = UserUtils.getUser().getId();
            } else {
                userId = requestMap.get("userId");
            }
            ChatHistory chatHistory = new ChatHistory();
            chatHistory.setUserid2(userId);
            List<ChatHistory> list = chatHistoryService.getIMUserContacts(chatHistory);
            List<Map<String, Object>> userList = new ArrayList<>();
            for (ChatHistory history : list) {
                Map<String, Object> map = new HashMap<>();
                User user = UserUtils.get(history.getUserid1());
                map.put("id", user.getId());
                map.put("name", user.getName());
                map.put("photo", user.getPhoto());
                map.put("loginName", user.getLoginName());
                userList.add(map);
            }
            j.put("group", userList);
            j.setErrorCode(ErrorCode.code_1004);
            j.setSuccess(true);
            j.setMsg("获取常用联系人成功");
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("获取常用联系人失败");
            j.setErrorCode(ErrorCode.code_2004);
        }
        return j;

    }

    public  Object SendMessage(){
        MsgContent msgContent = new MsgContent();
        Msg msg = new Msg();
        msgContent.type(MsgContent.TypeEnum.TXT).msg("您已加入!");
        UserName userName = new UserName();
        userName.add("");
        Map<String, Object> ext = new HashMap<>();
        ext.put("test_key", "test_value");
        msg.from("1").target(userName).targetType("users").msg(msgContent).ext(ext);
        Object result = null;//easemobSendMessage.sendMessage(msg);
        return  result;
    }
    public static Object mapToObject(Map<String, Object> map,Class<?> clazz) throws Exception{
        Object obj = clazz.newInstance();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for(Field field:declaredFields){
            int mod = field.getModifiers();
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                continue;
            }
            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }
        return obj;
    }



    static class ImageMsgContent extends MsgContent {
        private String url;
        private String filename;
        private String secret;
        private Size size;

        ImageMsgContent url(String url) {
            this.url = url;
            return this;
        }

        ImageMsgContent filename(String filename) {
            this.filename = filename;
            return this;
        }

        ImageMsgContent secret(String secret) {
            this.secret = secret;
            return this;
        }

        ImageMsgContent size(Size size) {
            this.size = size;
            return this;
        }

        static class Size {
            private long width;
            private long height;

            Size(long width, long height) {
                this.width = width;
                this.height = height;
            }
        }
    }
}
