package com.platform.modules.trtc.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.platform.modules.trtc.socket.WebSocket;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.platform.common.utils.Constant;
import com.platform.common.utils.RedisContants;
import com.platform.common.utils.RedisUtils;
import com.platform.modules.app.entity.LocationEntity;
import com.platform.modules.plm.util.MateriaFileProperties;
import com.platform.modules.plm.util.MaterialUtils;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysUserService;
import com.platform.modules.trtc.service.TrtcService;

@Service("trtcService")
public class TrtcServiceImpl implements TrtcService {
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private MateriaFileProperties materiaFileProperties; 
	@Autowired
	private RedisUtils redisUtils;

	@Override
	public List<Map<String, Object>> getReporterList(Long userId) {
		List<SysUserEntity> userEntities = sysUserService.selectByRoleId(2);
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		if(userEntities!=null && userEntities.size()>0){
			for(SysUserEntity user : userEntities){
				if(user==null || user.getUserId()==null || ( user!=null && user.getUserId()!=null && user.getUserId()==userId)){
					continue;
				}
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("userId", user.getUserId());
				map.put("username", user.getUsername());
				map.put("userImg", MaterialUtils.getMaterialUrl(user.getUserImg(), materiaFileProperties.getBasePath()));
				map.put("realname", user.getRealname());
				map.put("mobile", user.getMobile());
				map.put("email", user.getEmail());
				map.put("status", getReporterOnLineRedisById(user.getUserId()));
				// 20200528 weiyan 记者推流状态
				map.put("isPush", getReporterPushState(user.getUserId()));
				list.add(map);
			}
		}
		return list;
	}
	
	@Override
	public Map<String, Object> getReporterInfo(Long userId){
		SysUserEntity user = sysUserService.selectBaseById(userId);
		Map<String, Object> map = new HashMap<String, Object>();
		if(user!=null && user.getUserId()!=null){
			map.put("userId", user.getUserId());
			map.put("username", user.getUsername());
			map.put("userImg", MaterialUtils.getMaterialUrl(user.getUserImg(), materiaFileProperties.getBasePath()));
			map.put("realname", user.getRealname());
			map.put("mobile", user.getMobile());
			map.put("email", user.getEmail());
			map.put("status", getReporterOnLineRedisById(user.getUserId()));
			// 20200528 weiyan 记者推流状态
			map.put("isPush", getReporterPushState(user.getUserId()));
		}
		return map;
	}
	
	@Override
	public void updateReporterStatusRedisById(Long userId,Integer status){
		String key = RedisContants.REPORTER_ONLINE + userId;
		redisUtils.set(key, status, 30);
	}
	@Override
	public Integer getReporterOnLineRedisById(Long userId){
		String key = RedisContants.REPORTER_ONLINE + userId;
		Integer status = redisUtils.get(key, Integer.class);
		return status==null ? 0 : status;
	}
	
	@Override
	public void deleteReporterStatusRedisById(Long userId){
		String key = RedisContants.REPORTER_ONLINE + userId;
		redisUtils.delete(key);
	}
	
	@Override
	public Integer getReporterPushState(Long userId){
		String key = RedisContants.REPORTER_PUSH_STATE + userId;
		Integer status = redisUtils.get(key, Integer.class);
		return status==null ? 0 : status;
	}
	
	@Override
	public List<Map<String, Object>> getReporterStatusList(Long userId, Integer status){
		updateReporterStatusRedisById(userId, status);
//		System.out.println("service::::"+userId+"---"+status+"----"+getReporterOnLineRedisById(userId)+"----"+DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
		Set<Long> uids = new HashSet<Long>();
		String key = RedisContants.REPORTER_ONLINE+"*";
		Set<String> set = redisUtils.keys(key);
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
//		System.out.println("service::::"+userId+"---"+status+"----"+set.size()+"----"+set.toString()+"----"+DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
	    if(set!=null && set.size()>0){
	    	for(String str : set){
	    		Map<String, Object> map = new HashMap<String, Object>();
	    		if(StringUtils.isBlank(str) || StringUtils.isBlank(str.replace(RedisContants.REPORTER_ONLINE, ""))){
	    			continue;
	    		}
	    		Long uid = Long.valueOf(str.replace(RedisContants.REPORTER_ONLINE, ""));
	    		if(uid==userId){
	    			continue;
	    		}
	    		uids.add(uid);
	    		
	    		Integer s = getReporterOnLineRedisById(uid);
	    		map.put("userId", uid);
	    		map.put("status", s);
	    		map.put("isPush", getReporterPushState(uid));
	    		LocationEntity locationEntity = redisUtils.hget(Constant.REDIS_LOCATION_REPORT, uid.toString(),LocationEntity.class);
	    		if(locationEntity!=null){
	    			map.put("lng", locationEntity.getLng());
		    		map.put("lat", locationEntity.getLat());
	    		}
	    		list.add(map);
	    	}
	    }
	    //记者推流状态
	    key = RedisContants.REPORTER_PUSH_STATE+"*";
		set = redisUtils.keys(key);
	    if(set!=null && set.size()>0){
	    	for(String str : set){
	    		Map<String, Object> map = new HashMap<String, Object>();
	    		if(StringUtils.isBlank(str) || StringUtils.isBlank(str.replace(RedisContants.REPORTER_PUSH_STATE, ""))){
	    			continue;
	    		}
	    		Long uid = Long.valueOf(str.replace(RedisContants.REPORTER_PUSH_STATE, ""));
	    		if(uid==userId || uids.contains(uid)){
	    			continue;
	    		}
	    		uids.add(uid);
	    		Integer s = getReporterOnLineRedisById(uid);
	    		map.put("userId", uid);
	    		map.put("status", s);
	    		map.put("isPush", getReporterPushState(uid));
	    		LocationEntity locationEntity = redisUtils.hget(Constant.REDIS_LOCATION_REPORT, uid.toString(),LocationEntity.class);
	    		if(locationEntity!=null){
	    			map.put("lng", locationEntity.getLng());
		    		map.put("lat", locationEntity.getLat());
	    		}
	    		list.add(map);
	    	}
	    }
	    
	    return list;
	}
	/**
	 * 清除记者定位
	 */
	@Override
	public void deleteReporterLocationRedisById(Long userId){
		redisUtils.hdel(Constant.REDIS_LOCATION_REPORT, userId.toString());
	}
	
//	@Override
//	public void updateReporterStatusRedisById(Long userId,Integer status){
//		String key = RedisContants.REPORTER_ONLINE_LIST;
//		String fieid = RedisContants.REPORTER_ONLINE_LIST + userId;
////		if(status==0 || status.equals(0)){
////			redisUtils.hdel(key, fieid);
////		}else{
//			redisUtils.hset(key, fieid, status);
////		}
//	}
//	@Override
//	public Integer getReporterOnLineRedisById(Long userId){
//		String key = RedisContants.REPORTER_ONLINE_LIST;
//		String fieid = RedisContants.REPORTER_ONLINE_LIST + userId;
//		Integer status = redisUtils.hget(key, fieid, Integer.class);
//		return status==null ? 0 : status;
//	}
//	
//	@Override
//	public void deleteReporterStatusRedisById(Long userId){
//		String key = RedisContants.REPORTER_ONLINE_LIST;
//		String fieid = RedisContants.REPORTER_ONLINE_LIST + userId;
//		
//		redisUtils.hdel(key, fieid);
//	}
	/**
	 * pad发起或者终止通话
	 * @param userId 记者ID
	 * @param status 状态 1发起 2终止
	 */
	@Override
	public void padControlCall(Long userId,Integer status){
		WebSocket ws = new WebSocket();

		JSONObject jo = new JSONObject();

		jo.put("toUserId",userId);
		jo.put("fromUserId",81);
		jo.put("type",status);

		ws.onMessage(jo.toString(),null ,"81");
	}
}
