package com.pingpang.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pingpang.dao.UserGroupDao;
import com.pingpang.redis.RedisPre;
import com.pingpang.redis.service.RedisService;
import com.pingpang.service.UserGroupService;
import com.pingpang.util.StringUtil;
import com.pingpang.websocketchat.ChatGroup;

@Service
@Transactional
@DubboService
public class UserGroupServiceImpl implements UserGroupService{

	@Autowired
	private UserGroupDao userGroupDao;
	
	/**
	 *redis
	 */
	 @Autowired
	 private RedisService redisService;
	
	 /**
	 * 获取所有群组信息
	 * @param queryMap
	 * @return
	 */
    public Set<ChatGroup> getAllGroupSet(Map<String,String> queryMap){
    	return userGroupDao.getAllGroupSet(queryMap);
    }
    
    /**
	  * 获取群组总数
	 * @param queryMap
	 * @return
	 */
	public int getAllGroupCount(Map<String,String> queryMap) {
		return userGroupDao.getAllGroupCount(queryMap);
	}
	
	/**
	 * 添加群组
	 * @param cg
	 */
	public Map<String,Object> addGroup(ChatGroup cg) {
		Map<String,String> queryMap=new HashMap<String,String>();
		queryMap.put("groupCode", cg.getGroupCode());
		queryMap.put("groupUserCode", cg.getGroupUserCode());
        if(null==userGroupDao.getGroup(queryMap)) {
        	userGroupDao.addGroup(cg);
            return StringUtil.returnSucess();        	
        }
        return StringUtil.returnMap("F","此群已存在");
	}
	
	/**
	 * 跟新群组信息
	 * @param cg
	 */
	public void updateGroup(ChatGroup cg) {
		this.redisService.delete(RedisPre.DB_GROUP+cg.getGroupCode());
		userGroupDao.updateGroup(cg);
	}

	/**
	 * 获取群组信息
	 * @param queryMap
	 * @return
	 */
	public ChatGroup getGroup(Map<String,String> queryMap) {
		 ChatGroup cg=(ChatGroup) this.redisService.get(RedisPre.DB_GROUP+queryMap.get("groupCode"));
		 if(null==cg) {
			 cg=userGroupDao.getGroup(queryMap);
			 this.redisService.set(RedisPre.DB_GROUP, cg);
		 }
		 return cg;
	}
	
	/**
	 * 批量更新数据
	 * @param status
	 * @param ids
	 */
	public void updateGroupS(String status,Set<String>ids) {
		if(null==ids || ids.isEmpty() || (!"-1".equals(status) && !"0".equals(status))){
			return;
		}
		Set<ChatGroup> groups=userGroupDao.getGroupByID(ids);
		if(null!=groups && !groups.isEmpty()) {
			for(ChatGroup cg : groups) {
				this.redisService.delete(RedisPre.DB_GROUP+cg.getGroupCode());
			}
		}
        userGroupDao.updateGroups(status, ids);
        
	}
	
	
}
