/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.iim.web;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.utils.*;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.iim.entity.Friend;
import com.jeeplus.modules.iim.entity.FriendGroup;
import com.jeeplus.modules.iim.entity.LayFileJsonData;
import com.jeeplus.modules.iim.entity.LayGroup;
import com.jeeplus.modules.iim.entity.LayGroupJsonData;
import com.jeeplus.modules.iim.entity.LayGroupUser;
import com.jeeplus.modules.iim.entity.LayJson;
import com.jeeplus.modules.iim.entity.LayJsonData;
import com.jeeplus.modules.iim.entity.Mine;
import com.jeeplus.modules.iim.service.LayGroupService;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 联系人Controller
 * 
 * @author jeeplus(seven修改)
 * @version 2016-6-23
 */
@Controller
@RequestMapping(value = "${adminPath}/iim/contact")
public class ContactController extends BaseController {

	@Autowired
	private SystemService systemService;

	@Autowired
	private LayGroupService layGroupService;
	@Autowired
	private UserofficeService userofficeService;


	@Autowired
	private UserDao userDao;

	@Autowired
	private OfficeService officeService;

	private ExecutorService poolExecutor = Executors.newFixedThreadPool(10);

	/**
	 * 打开通讯录
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "index", "" })
	public String index(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<User> list = systemService.findUser(user);
		model.addAttribute("list", list);
		return "modules/iim/contacts";
	}

	/**
	 * 查找
	 * 
	 * @param u
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "searchUsers")
	public String searchUsers(User u, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if(! user.isAdmin()) {
			if (StringUtils.isNotBlank(u.getMobile()) || StringUtils.isNotBlank(u.getName())) {
				List<User> users = userDao.findFriendByMobileOrName(u);
				model.addAttribute("list", users);
			}else if(StringUtils.isNotBlank(u.getComId()) && u.getComId().equals("comId")) {
				Useroffice useroffice = new Useroffice();
				List<Office> companyList = UserUtils.getAllCompany(user);
				List companyIds = new ArrayList();
				for (Office office : companyList) {
					companyIds.add(office.getId());
				}
				useroffice.setCompanyIds(companyIds);
				useroffice.setDelFlag("0");
				List<Useroffice> list = new ArrayList<Useroffice>();
				if(StringUtils.isEmpty(u.getName())&&StringUtils.isEmpty(u.getMobile())){
					list = userofficeService.searchUsers(useroffice);
				}
				if(StringUtils.isNotEmpty(u.getName())&&StringUtils.isEmpty(u.getMobile())){
					useroffice.setName(u.getName());
					list = userofficeService.searchUsers(useroffice);
				}
				if (StringUtils.isEmpty(u.getName())&&StringUtils.isNotEmpty(u.getMobile())) {
					useroffice.setMobile(u.getMobile());
					list = userofficeService.searchUsers(useroffice);
				}
				if (StringUtils.isNotEmpty(u.getName())&&StringUtils.isNotEmpty(u.getMobile())) {
					useroffice.setName(u.getName());
					useroffice.setMobile(u.getMobile());
					list = userofficeService.searchUsers(useroffice);
				}
				List<User> friends = new ArrayList<User>();
				for (int i = 0; i < list.size(); i++) {
					User u1 = UserUtils.get(list.get(i).getUserId());
					if(u1!=null&&u1.getCompany().getName().equals(user.getCompany().getName())&&!u1.getLoginName().equals(user.getLoginName())){
						friends.add(u1);
					}
				}
				// 我的好友--->常用联系人
				User currentUser = UserUtils.getUser();
				friends.addAll(userDao.findFriends(currentUser));
				List<User> users = new ArrayList<>();
				if (StringUtils.isNotBlank(u.getMobile())) {
					if (StringUtils.isNotBlank(u.getName())){
						for (User user1:friends){
							if (user1.getMobile().equals(u.getMobile())){
								if(user1.getName().contains(u.getName())) {
									users.add(user1);
								}
								break;
							}
						}
					}else {
						for (User user1:friends){
							if (user1.getMobile().equals(u.getMobile())){
								users.add(user1);
								break;
							}
						}
					}

					model.addAttribute("list", users);
				}else if (StringUtils.isNotBlank(u.getName())){
					for (User user1 : friends) {
						if (user1.getName().contains(u.getName())) {
							users.add(user1);
						}
					}
					model.addAttribute("list", users);
				}else {
					users.addAll(friends);
					model.addAttribute("list", users);
				}
			}else {
				model.addAttribute("list", null);
			}
		}else{
			List<User> friends = userDao.searchUsers(u);
			model.addAttribute("list", friends);
		}
		/*
		User u = UserUtils.getUser();
		if(! u.isAdmin()){
			user.setCompany(UserUtils.getSelectCompany());
		}
		List<User> friends = userDao.searchUsers(user);*/


		return "modules/iim/search_user";
	}

	/**
	 * 添加好友--->常用联系人
	 */
	@RequestMapping(value = "addFriend")
	public String addFriend(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] = ids.split(",");
		User currentUser = UserUtils.getUser();
		for (String id : idArray) {
			if (userDao.findFriend(currentUser.getId(), id) == null) {

				userDao.insertFriend(IdGen.uuid(), currentUser.getId(), id,"0","0");// 添加对方为好友
				userDao.insertFriend(IdGen.uuid(), id,
				 currentUser.getId(),"0","1");//同时把自己添加为对方的好友
			}
		}
		addMessage(redirectAttributes, "添加好友成功");
		return "redirect:" + Global.getAdminPath() + "/iim/contact/myFriends/?repage";
	}

	/**
	 * 删除好友
	 */
	@RequestMapping(value = "delFriend")
	public String delFriend(String id, RedirectAttributes redirectAttributes) {
		User friend = UserUtils.get(id);
		User currentUser = UserUtils.getUser();
		if (friend != null && userDao.findFriend(currentUser.getId(), friend.getId()) != null) {
			userDao.deleteFriend(currentUser.getId(), friend.getId());// 删除好友
			userDao.deleteFriend(friend.getId(),
					currentUser.getId());//同时把自己从对方的好友列表删除
		}

		return "redirect:" + Global.getAdminPath() + "/iim/contact/myFriends/?repage";
	}
	/**
	 * 确认通过好友
	 */
	@RequestMapping(value = "friendAudit")
	public String friendAudit(String id, RedirectAttributes redirectAttributes) {
		User friend = UserUtils.get(id);
		User currentUser = UserUtils.getUser();
		if (friend != null && userDao.findFriend(currentUser.getId(), friend.getId()) == null) {
			userDao.friendAudit(currentUser.getId(), friend.getId());// 确认通过好友
			userDao.friendAudit(friend.getId(),
					currentUser.getId());//同时把自己从对方的好友列表确认通过好友
		}

		return "redirect:" + Global.getAdminPath() + "/iim/contact/myFriends/?repage";
	}
	/**
	 * 拒绝通过好友
	 */
	@RequestMapping(value = "friendAuditNo")
	public String friendAuditNo(String id, RedirectAttributes redirectAttributes) {
		User friend = UserUtils.get(id);
		User currentUser = UserUtils.getUser();
		if (friend != null && userDao.findFriend(currentUser.getId(), friend.getId()) == null) {
			userDao.friendAuditNo(currentUser.getId(), friend.getId());// 确认通过好友
			userDao.friendAuditNo(friend.getId(),
					currentUser.getId());//同时把自己从对方的好友列表确认通过好友
		}

		return "redirect:" + Global.getAdminPath() + "/iim/contact/myFriends/?repage";
	}

	/**
	 * 打开我的好友列表--->常用联系人列表
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "myFriends")
	public String myFriends(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		List<User> friends = userDao.findFriends(currentUser);
		model.addAttribute("list", friends);
		List<User> friendsAudit = userDao.findFriendsAudit(currentUser);
		model.addAttribute("listAudit", friendsAudit);
		return "modules/iim/myFriends";
	}

	/**
	 * 打开我的好友列表--->常用联系人列表
	 *
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "myFriendsAudit")
	public String myFriendsAudit(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		List<User> friends = userDao.findFriendsAudit(currentUser);
		model.addAttribute("list", friends);
		return "modules/iim/myFriends";
	}

	/**
	 * 打开聊天窗口
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "layerIM")
	public String layerIM(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<User> list = systemService.findUser(user);
		model.addAttribute("list", list);
		return "modules/iim/layerIM";
	}

	/**
	 * layim初始化信息
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "friend")
	@ResponseBody
	public LayJson getFriend(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		LayJsonData data = new LayJsonData();

		data.getFriend().clear();
		LayJson j = new LayJson();
		j.setCode(0);
		// 我的个人信息
		Mine m = new Mine();
		m.setId(UserUtils.getUser().getId());
		m.setUsername(UserUtils.getUser().getName());
		m.setStatus("online");
		m.setRemark(UserUtils.getUser().getSign());
		m.setAvatar(UserUtils.getUser().getPhoto());
		data.setMine(m);

		// 我的好友--->常用联系人
		User currentUser = UserUtils.getUser();
		List<User> friends = userDao.findFriends(currentUser);
		FriendGroup friendGroup = new FriendGroup();
		friendGroup.setGroupname("我的好友");
		friendGroup.setId(1);
		friendGroup.setOnline(friends.size());
		for (User u : friends) {
			Friend friend = new Friend();
			friend.setId(u.getId());
			friend.setUsername(u.getName());
			friend.setAvatar(u.getPhoto());
			friend.setSign(u.getSign());
			friendGroup.getList().add(friend);
		}
		data.getFriend().add(friendGroup);

		// 按部门显示联系人
		//List<Office> officeList = officeService.findList(false);
		Office company = UserUtils.getSelectCompany();
		if(!"1".equals(company.getId())){
			List<Office> officeList = officeService.findByParentIdsCompany(UserUtils.getSelectCompany(), UserUtils.getSelectOffice());
			int index = 1;
			for (Office office : officeList) {
				user.setOffice(office);
				user.setCompany(UserUtils.getSelectCompany());
				List<User> users = userDao.findListByOffice(user);
				FriendGroup fgroup = new FriendGroup();
				fgroup.setGroupname(office.getName());
				fgroup.setOnline(users.size());
				fgroup.setId(++index);
				for (User u : users) {
				    if(currentUser.getId().equals(u.getId())){
				        continue;
                    }
					Friend friend = new Friend();
					friend.setId(u.getId());
					friend.setAvatar(u.getPhoto());
					friend.setUsername(u.getName());
					friend.setSign(u.getSign());
					fgroup.getList().add(friend);
				}
				data.getFriend().add(fgroup);
			}
		}

		// 不属于任何部门的联系人
		/*user.setOffice(null);
		List<User> users = userDao.findListByOffice(user);
		FriendGroup group = new FriendGroup();
		group.setGroupname("未分组");
		group.setOnline(users.size());
		group.setId(++index);
		for (User u : users) {
			Friend friend = new Friend();
			friend.setId(u.getLoginName());
			friend.setUsername(u.getName());
			friend.setAvatar(u.getPhoto());
			friend.setSign(u.getSign());
			group.getList().add(friend);
		}
		data.getFriend().add(group);*/

		// 用户自己创建的群组和属于的群组

		// 查找我属于的群组
		List<LayGroup> memberLayGroupList = layGroupService.findGroupList(UserUtils.getUser());

		for (LayGroup g : memberLayGroupList) {
			data.getGroup().add(g);
		}

		j.setData(data);
		return j;
	}

	/**
	 * 群组成员接口
	 * 
	 * @return
	 */
	@RequestMapping(value = "getMembers")
	@ResponseBody
	public LayJson getMembers(LayGroup group) {
		LayGroupJsonData data = new LayGroupJsonData();
		group = layGroupService.get(group.getId());
		// 设置群主
		data.getOwner().put("username", group.getCreateBy().getName());
		data.getOwner().put("id", group.getCreateBy().getId());
		data.getOwner().put("avatar", group.getCreateBy().getPhoto());
		data.getOwner().put("sign", group.getCreateBy().getSign());
		// 将群主添加到群聊第一个

		List<LayGroupUser> zlist = group.getLayGroupUserList();
		for (LayGroupUser lgUser : zlist) {
			Friend friend = new Friend();
			friend.setUsername(lgUser.getUser().getName());
			friend.setId(lgUser.getUser().getId());
			friend.setAvatar(lgUser.getUser().getPhoto());
			friend.setSign(lgUser.getUser().getSign());
			data.getList().add(friend);
		}

		LayJson j = new LayJson();
		j.setData(data);
		return j;
	}

	@ResponseBody
	@RequestMapping(value = { "uploadImage", "uploadFile" })
	public String uploadImage(HttpServletRequest request, HttpServletResponse response, MultipartFile file)
			throws IllegalStateException, IOException {
		String filepath = "";
		String content = null;
		LayFileJsonData data = new LayFileJsonData();
		String contentType = "";
		// 判断文件是否为空
		if (!file.isEmpty()) {
		    contentType = file.getContentType();
			// 文件保存路径
            String realPath ="messages/"+DateUtils.formatDate(new Date())+"/"+ UserUtils.getPrincipal() + "/";
            OSSClientUtil ossUtil = new OSSClientUtil();
            String newName = System.currentTimeMillis()+"-"+file.getOriginalFilename();

            ossUtil.uploadFile2OSS(file.getInputStream(),realPath,newName);
            filepath = Global.getAliDownloadUrl() + "/" + realPath + newName;

			data.setName(file.getOriginalFilename());
			data.setSrc(filepath);
		}
		ObjectMapper mapper = new ObjectMapper();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", "0");
		map.put("data", data);

		content = mapper.writeValueAsString(map);
 		return content;
	}


    @RequestMapping(value = "friendStatus")
    @ResponseBody
    public AjaxJson getFriendStatus(User user,boolean flag,String status, HttpServletRequest request, HttpServletResponse response, Model model) {
        AjaxJson data = new AjaxJson();
        StringBuilder stringBuilder = new StringBuilder();
        // 我的好友--->常用联系人
        User currentUser = UserUtils.getUser();
        List<User> friends = userDao.findFriends(currentUser);
        List<String> ids = null;
        if(friends!=null&&friends.size()>0) {
            ids = new ArrayList<>(friends.size());
            for (User u : friends) {
                if ("online".equals(SmackUtils.IsUserOnLine(u.getId()))) {
                    stringBuilder.append(u.getId()).append(",");
                }
                ids.add(u.getId());
            }
        }

        // 按部门显示联系人
        //List<Office> officeList = officeService.findList(false);
        Office company = UserUtils.getSelectCompany();
        if(!"1".equals(company.getId())){
            List<Office> officeList = officeService.findByParentIdsCompany(UserUtils.getSelectCompany(), UserUtils.getSelectOffice());
            for (Office office : officeList) {
                user.setOffice(office);
                user.setCompany(UserUtils.getSelectCompany());
                List<User> users = userDao.findListByOffice(user);
                for (User u : users) {
                    if((ids!=null&&ids.contains(u.getId()))||currentUser.getId().equals(u.getId())){
                        continue;
                    }
//                    if("online".equals(SmackUtils.IsUserOnLine(u.getId()))){
//                        stringBuilder.append(u.getId()).append(",");
//                    }
                }
            }
        }
        final String users = stringBuilder.toString();
        data.getBody().put("userStr", users);
        if(flag){
            if(StringUtils.isBlank(status)){
                status = "online";
            }
            final JSONObject body = new JSONObject();
            body.put("id",currentUser.getId());
            body.put("status",status);
            final String string = body.toJSONString();
            if(StringUtils.isNotBlank(users)) {
                poolExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        String[] split = users.split(",");
                        Set<String> set = new HashSet<>(split.length * 2);
                        set.addAll(Arrays.asList(split));
                        for (String u : set) {
                            //SmackUtils.sendSmackMessage(u, string, "_online_all_status_");
                        }
                    }
                });
            }
        }
        return data;
    }
}