package com.evt.mgr.job;

import java.util.List;
import java.util.Set;

import com.taurus.core.util.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;

import com.data.util.EventType;
import com.data.util.Utility;
import com.evt.mgr.GroupPublisherService;
import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.TArray;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.plugin.redis.RedisLock;
import com.taurus.core.util.Logger;
import com.taurus.core.util.StringUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;

public class CleanTimeOutRoomJob implements Job{

	private Logger logger = Logger.getLogger(CleanTimeOutRoomJob.class);
	
	public CleanTimeOutRoomJob() {
		
    }
	
	private void deleteRoomFromRedis(String tag_key,Jedis jedis0) {
		
		RedisLock room_lock = new RedisLock(tag_key, jedis0);
		try {
			//                                                                   0         1          2         3          4               5              6            7             8       9
    		List<String> paramList = jedis0.hmget(tag_key, "AA", "payer", "pay", "group","game","delete_status","status","create_time","id","players");
    		
    		if(StringUtil.isEmpty(paramList.get(4))) {
    			Redis.use().expire(tag_key, 20);
				return;
    		}
    		
    		String delete_status = paramList.get(5);
    		if(StringUtil.isEmpty(delete_status)) {
    			
    			String status = paramList.get(6);
    			int _status = Integer.parseInt(status);
    			if(_status == 2 || _status == 3) {
    				logger.info(tag_key + "房间的状态不对，此时房间的状态["+status + "]");
    				Redis.use().expire(tag_key, 20);
    				return;
    			}
    			
    			// 如果房间的存活时间小于4个小时，考虑到游戏服务器也在删除 所以延时10分钟
    			String create_time = paramList.get(7);
    			String roomid = paramList.get(8);
    			long now = System.currentTimeMillis() / 1000;
    			if((now - Long.parseLong(create_time)) > 14400 + 600) {
    				
    				deleteRoomFromServer(tag_key,jedis0,false);
    			}
    			
    			return;
    		}
    		
    		boolean pay_AA = Integer.parseInt(paramList.get(0)) == 1;
    		int payer = Integer.parseInt(paramList.get(1));
    		int pay = Integer.parseInt(paramList.get(2));
    		int gameId = Integer.parseInt(paramList.get(4));
			String group = paramList.get(3);
    		int _gid = 0;
			if(StringUtil.isNotEmpty(group)) {
				_gid = Integer.parseInt(group);
			}
    		int _delete_status = Integer.parseInt(delete_status);
    		if(_delete_status == 0) {
    			
    			// 如果需要支付钻石
    			if(pay >  0) {
    				
    				if (pay_AA) {
    					
						String players_json = paramList.get(9);
						if(StringUtil.isEmpty(players_json) == false) {
							ITArray players = TArray.newFromJsonData(players_json);
							for (int i = 0; i < players.size(); i++) {
								//GroupPublisherService.refundDiamo(players.getInt(i), pay, _gid, gameId);
							}
						}
    				}else{
    					
    					if(_gid == 0) {
    						//GroupPublisherService.refundDiamo(payer, pay, _gid, gameId);
    					}	
    				}
    			}
    		}
    		
    		Redis.use().hset(tag_key, "status", 3 + "");
			Redis.use().hincrBy(tag_key, "cache_ver", 1);
			Redis.use().expire(tag_key, 20);
		}
		catch(Exception e) {
			logger.info(tag_key + "删除房间发生异常["+e.getMessage() + "]");
		}
		finally {
			room_lock.unlock(false);
		}
	}
	
	private boolean deleteRoomFromServer(String roomid,Jedis jedis0,boolean lock) {
		
		String tag_key = roomid;
    	RedisLock room_lock = null;
    	
    	if(lock) {
    		room_lock = new RedisLock(tag_key, jedis0);
    	}
    	
    	try {
    		
    		if( jedis0.exists(tag_key) == false) {
    			return false;
    		}
    		//                                                                    0         1         2          3         4          5             6           7
    		List<String> paramList = jedis0.hmget(tag_key, "AA", "payer", "pay", "group","game","status","create_time","id");
    		
			String status = paramList.get(5);
			int _status = Integer.parseInt(status);
			if(_status == 2 || _status == 3) {
				logger.info("删除房间" + roomid + "失败，原因状态不对,此时的状态是[" + _status +"]");
				return true;
			}
			
			String group = paramList.get(3);
			int _gid = 0;
			if(StringUtil.isNotEmpty(group)) {
				_gid = Integer.parseInt(group);
			}
			
			// 如果房间的存活时间小于4个小时，考虑到游戏服务器也在删除 所以延时10分钟
			String create_time = paramList.get(6);
			long now = System.currentTimeMillis() / 1000;
			if((now - Long.parseLong(create_time)) < 14400 + 600) {
				logger.info("删除房间" + roomid + "失败，房间距离创建没有超过4个小时");
				return true;
			}
			
			if(_gid != 0) {
				
				// 如果游戏没有开始_status = 0
				//			不是aa支付，则退出回创建者创建钻石的费用
				//			aa支付，设置status=2之后，则交给游戏服务器去做(如果游戏服务器挂了呢，或者房间在游戏服务器中根本就不存在呢)，
				// 如果游戏已经开始_status = 1，则不用考虑钻石回退的问题，下一次执行的时候，如果redis还存在房间的信息，则直接从redis删除就可以了
				if(_status==0) {
		
					int gameId = Integer.parseInt(paramList.get(4));
					boolean pay_AA = Integer.parseInt(paramList.get(0)) == 1;
					if (!pay_AA) {
						int payer = Integer.parseInt(paramList.get(1));
						int pay = Integer.parseInt(paramList.get(2));
						//Utility.payDiamo(EventType.REDIS_EVENT_BACK_PAY, payer, gameId, pay, _gid,0);
					}
				}
				String strRoomID = "";
				if(StringUtil.isNotEmpty(paramList.get(7))) {
					strRoomID =paramList.get(7);
				}
				GroupPublisherService.delRoomEvt(_gid, strRoomID);
			}
			
			jedis0.hset(tag_key, "status", "2");
			jedis0.hset(tag_key, "delete_status", "" + status);
			jedis0.hincrBy(tag_key, "cache_ver", 1);
			
			logger.info("删除房间" + roomid + "成功");
    	}
    	catch(Exception e){
    		
    	}
    	finally {
    		
    		if(room_lock != null) {
    			room_lock.unlock(false);
    		}
    	}
    	
    	return true;
	}
	
	/**
	 * 清除无效的房间
	 */
	private void cleanInvalidRoom() {
		try {
			
			Jedis jedis0 = Redis.use("group1_db0").getJedis();
			try {
				
			    String cursor = ScanParams.SCAN_POINTER_START;
			    String key = "room:*";
			    ScanParams scanParams = new ScanParams();
			    scanParams.match(key);
			    scanParams.count(1000);
			    
			    // 处理所有redis的房间
			    while (true){
			    	
			    	ScanResult<String> scanResult = jedis0.scan(cursor, scanParams);
			    	cursor = scanResult.getStringCursor();
			    	List<String> list = scanResult.getResult();
			    	
			    	for(int m = 0; m < list.size(); m++){
			    		
			            String mapentry = list.get(m);
			            logger.info("正在检查房间          " + mapentry);
			            deleteRoomFromRedis(mapentry,jedis0);
			    	}
			    	
			    	if ("0".equals(cursor)){
			            break;
			        }
			    }
			}
			finally {
				jedis0.close();
			}
		}
		catch(Exception e) {
			
		}
	}
	
	/**
	 * 清除亲友圈中无效的房间
	 */
	private void cleanGroupRoom() {
		
		try {
			
			Jedis jedis11 = Redis.use("group1_db11").getJedis();
			Jedis jedis0 = Redis.use("group1_db0").getJedis();
			
			RedisLock lock = new RedisLock("room_clean", jedis11);
			try {
				
				String cursor = ScanParams.SCAN_POINTER_START;
				String key = "*:rooms*";
				ScanParams scanParams = new ScanParams();
			    scanParams.match(key);
			    scanParams.count(1000);
			    
			    // 处理亲友圈的房间
			    while (true){
			    	
			    	ScanResult<String> scanResult = jedis11.scan(cursor, scanParams);
			    	cursor = scanResult.getStringCursor();
			    	List<String> list = scanResult.getResult();
			    	
			    	for(int m = 0; m < list.size(); m++){
			    		
			    		
			            String mapentry = list.get(m);
			            logger.info("正在查询群" +mapentry + "的无效房间");
			            Set<String> rooms = jedis11.zrangeByScore(mapentry, 100000, 1000000);
			            
			            for (String roomId : rooms) {
			            	logger.info("正在查询群" +mapentry + "的无效房间" + roomId);
			            	boolean existed = deleteRoomFromServer(roomId,jedis0,true);
			            	if(!existed) {
			            		jedis11.zrem(mapentry, roomId);
			            		logger.info("删除群" +mapentry + "的无效房间" + roomId + "因为房间不存在");
			            	}
			            }
			    	}
			    	
			    	if ("0".equals(cursor)){
			            break;
			        }
			    }
			}
			finally {
				lock.unlock();
				jedis0.close();
			}
		}
		catch(Exception e) {
			
		}
	}

	/**
	 * 清除亲友圈中无效的房间
	 */
	private void cleanGroupMemberLog() {
		int time = DateUtils.getBeginDay() - 5 * 24 * 3600;
		String deleteSql = String.format("delete from group_member_log where time < %s", time);
		Utility.evtdbLog(1, 1, deleteSql);
		String deleteSql2 = String.format("delete from room_rec_log where time < %s and time > %s", time, time - 24 * 3600);
		Utility.evtdbLog(1, 1, deleteSql2);
		String deleteSql3 = String.format("delete from group_hp_log where time < %s and time > %s", time, time - 24 * 3600);
		Utility.evtdbLog(1, 1, deleteSql3);
	}

	@Override
	public void execute(JobExecutionContext context) {
		
		JobKey jobKey = context.getJobDetail().getKey();
		if(jobKey.getName().equals("clean_group_room") || jobKey.getName().equals("clean_group_room1")) {
			logger.info("执行成功" + jobKey.getName());
			cleanGroupRoom();
			logger.info("执行成功cleanGroupMemberLog");
			cleanGroupMemberLog();
		}
		else if(jobKey.getName().equals("clean_invalid_room")|| jobKey.getName().equals("clean_invalid_room1")) {
			logger.info("执行成功" + jobKey.getName());
			cleanInvalidRoom();
		}
	}
}
