package com.ssj.service.sys.schoolmatecircle.service.impl;

import com.ssj.bean.sys.schoolmatecircle.domain.SSJUserFriend;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.sys.schoolmatecircle.dao.SSJUserFriendApplyDao;
import com.ssj.dao.sys.schoolmatecircle.dao.SSJUserFriendDao;
import com.ssj.dao.sys.schoolmatecircle.dao.SSJUserFriendQueryDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.service.conch.student.dto.UserFriendDto;
import com.ssj.service.sys.easemob.service.EasemobService;
import com.ssj.service.sys.schoolmatecircle.service.SSJUserFriendService;
import com.ssj.service.sys.schoolmatecircle.service.SSJUserMessageService;
import com.ssj.service.weixin.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
@Transactional
public class SSJUserFriendServiceImpl extends BaseServiceImpl<SSJUserFriend, String> implements SSJUserFriendService {
    protected static final Logger logger = LoggerFactory.getLogger(SSJUserFriendServiceImpl.class);

    @Autowired
    private SSJUserFriendDao dao;
    
    @Autowired
    private SSJUserFriendApplyDao userFriendApplyDao;
    
    @Autowired
    private SSJUserFriendQueryDao userFriendQueryDao;
    
    @Autowired
	private EasemobService easemobService;
    
    @Autowired
	private UserService userService;
    
    @Autowired
    private SSJUserMessageService userMessageService;

    @Override
    public PagingAndSortingRepository<SSJUserFriend, String> getDao() {
        return dao;
    }
    
    @Override
	public List<UserFriendDto> findFriends(String userId) {
    	List<UserFriendDto> dtoList = new ArrayList<UserFriendDto>();
    	//获取孩子的家长好友列表
    	List<Map<String,Object>> list = userFriendQueryDao.findParents(userId);
    	for (Map<String,Object> map : list) {
			UserFriendDto dto = new UserFriendDto();
			dto.setFriendUserId((String)map.get("id"));
			dto.setFriendUserName((String)map.get("parent_role"));
			dto.setImgUrl((String)map.get("photo"));
			if(map.get("sex") != null) {
				dto.setSex(Integer.valueOf(map.get("sex").toString()));
			}
			dto.setEasemobName((String)map.get("easemob_name"));
			dto.setUnreadNum(Integer.parseInt(map.get("unreadnum").toString()));
			dto.setIsParent(1);
			dtoList.add(dto);
		}
    	//获取小孩绑定的其他副账号的家长列表
    	list = userFriendQueryDao.findOtherParents(userId);
    	for (Map<String,Object> map : list) {
			UserFriendDto dto = new UserFriendDto();
			dto.setFriendUserId((String)map.get("id"));
			dto.setFriendUserName((String)map.get("role_name"));
			dto.setImgUrl((String)map.get("photo"));
			if(map.get("sex") != null) {
				dto.setSex(Integer.valueOf(map.get("sex").toString()));
			}
			dto.setEasemobName((String)map.get("easemob_name"));
			dto.setUnreadNum(Integer.parseInt(map.get("unreadnum").toString()));
			dto.setIsParent(1);
			dtoList.add(dto);
		}
    	
		List<Map<String,Object>> friendList =  userFriendQueryDao.findFriends(userId);
		for (Map<String,Object> map : friendList) {
			UserFriendDto dto = new UserFriendDto();
			dto.setFriendUserId((String)map.get("id"));
			dto.setFriendUserName((String)map.get("user_name"));
			dto.setImgUrl((String)map.get("photo"));
			if(map.get("sex") != null) {
				dto.setSex(Integer.valueOf(map.get("sex").toString()));
			}
			dto.setEasemobName((String)map.get("easemob_name"));
			dto.setUnreadNum(Integer.parseInt(map.get("unreadnum").toString()));
			dtoList.add(dto);
		}
		return dtoList;
	}

	@Override
	public boolean addFriend(String userId, String friendUserId, int status) {
		//判断是同意还是忽略好友
		if(status == 1) {
			//判断是否已经添加过好友
			int count = dao.validateIsFriend(userId, friendUserId);
			if(count > 0) {
				return false;
			}
			//判断好友是否有忽略同意申请，如果有则不添加，如果没有则添加好友关系
			count = userFriendApplyDao.countByRefuseUserFriendApply(userId, friendUserId);
			if(count > 0) {
				//单边同意好友申请
				userFriendApplyDao.updateUserFriendApplyStatus(userId, friendUserId, status);
			}else {
				//添加好友关系
				userFriendApplyDao.updateUserFriendApplyStatus(userId, friendUserId, status);
				userFriendApplyDao.updateUserFriendApplyStatus(friendUserId, userId, status);
				
				SSJUserFriend userFriend = new SSJUserFriend();
				userFriend.setOwnerUserId(userId);
				userFriend.setFriendUserId(friendUserId);
				userFriend.setCreateTime(new Date());
				dao.save(userFriend);
				//环信添加好友关系
				User user = userService.getById(userId);
				User friendUser = userService.getById(friendUserId);
				if(StringUtils.isBlank(user.getEasemobName())) {
					user.setEasemobName(userService.createUniqueEasemobName());
					//创建小孩环信账号
					easemobService.createUserSingle(user.getEasemobName(), user.getUserName());
					userService.save(user);
				}
				if(StringUtils.isBlank(friendUser.getEasemobName())) {
					friendUser.setEasemobName(userService.createUniqueEasemobName());
					//创建小孩环信账号
					easemobService.createUserSingle(friendUser.getEasemobName(), friendUser.getUserName());
					userService.save(friendUser);
				}
				easemobService.addFriendSingle(user.getEasemobName(), friendUser.getEasemobName());
			}
		}else if(status == 2) {
			//忽略好友申请
			userFriendApplyDao.updateUserFriendApplyStatus(userId, friendUserId, status);
		}
		return true;
	}

	@Override
	public void deleteFriend(String userId, String friendUserId) {
		//删除表好友记录
		dao.deleteFriends(userId);
		//删除好友申请记录
		userFriendApplyDao.deleteFriendApply(userId,friendUserId);
		//环信解除好友关系
		User user = userService.getById(userId);
		User friendUser = userService.getById(friendUserId);
		easemobService.deleteFriendSingle(user.getEasemobName(), friendUser.getEasemobName());
		//删除好友聊天记录
		userMessageService.deleteUserMessage(userId, friendUserId);
	}


	@Override
	public void deleteTheFriends(String userId) {
		//删除表好友记录
		dao.deleteFriends(userId);
		//删除好友申请记录
		userFriendApplyDao.deleteFriendsApply(userId);

	}

	@Override
	public boolean validateIsFriend(String userId, String friendUserId) {
		int count = dao.validateIsFriend(userId, friendUserId);
		if(count > 0) {
			return true;
		}
		return false;
	}
}