
package com.data.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.data.bean.GameBean;
import com.data.bean.GroupMemberBean;
import com.data.cache.GameCache;
import com.data.cache.GroupCache;
import com.data.cache.GroupMemberCache;
import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TArray;
import com.taurus.core.entity.TObject;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.util.Logger;
import com.taurus.core.util.StringUtil;

import redis.clients.jedis.Jedis;


public class Utility {
	/**
	 * API 版本
	 */
	public static int		API_VER = 2;


	private static final Logger log = Logger.getLogger(Utility.class);
	/**
	 * 获取战绩数据
	 * @param jedis5
	 * @param key
	 * @param platform
	 * @return
	 */
	public final static ITObject getMilitaryList(Jedis jedis5,String key,String platform) {
		Map<String, String> military = jedis5.hgetAll(key);
		if (military == null || military.isEmpty()) {
			return null;
		}
		ITObject obj = TObject.newInstance();
		obj.putString("military_id", key);
		String strData = military.get("game_id");
		if (strData == null) {
			return null;
		}
		obj.putString("game_id", strData);
		obj.putString("room_id", military.get("room_id"));
		obj.putString("round", military.get("round"));
		int hp_times = 10;
		if(military.containsKey("hp_times")) {
			hp_times = Integer.parseInt(military.get("hp_times"));
		}
		int groupPid = 0;
		if(military.containsKey("groupPid")) {
			groupPid = Integer.parseInt(military.get("groupPid"));
		}
		obj.putInt("hp_times", hp_times);
		obj.putInt("groupPid", groupPid);
		GameBean gb = GameCache.getGame(Integer.parseInt(strData));
		ITObject gameObj = gb.getTObject();
		obj.putTObject("game_info",gameObj);
		obj.putString("create_time", military.get("create_time"));
		strData = military.get("totalScore");
		if (strData != null) {
			obj.putString("totalScore", strData);
		}
		String hpOnOff = military.get("hpOnOff");
		if(StringUtil.isNotEmpty(hpOnOff)) {
			obj.putInt("hpOnOff", Integer.parseInt(hpOnOff));
		}else {
			obj.putInt("hpOnOff", 0);
		}
		
		strData = military.get("groupId");
		if (strData == null) {
			strData = "0";
		}
		obj.putString("groupId", strData);
		for (int i = 1; i <= Integer.parseInt(military.get("round")); i++) {
			String roundKey = "round_" + i;
			try {
				obj.putString(roundKey, military.get(roundKey));
			} catch (Exception e) {
			}
		}
		return obj;
	}
	
	/**
	 * 获取成员上级列表
	 * @param groupId
	 * @param uid
	 * @return
	 */
	public static List<Integer> getMemberParents(int groupId,int uid){
		Jedis jedis10 = Redis.use("group1_db10").getJedis();
		try {
			return getMemberParents(jedis10,groupId,uid,false);
		}finally {
			jedis10.close();
		}
	}
	
	/**
	 * 获取成员上级列表
	 * @param groupId
	 * @param uid
	 * @return
	 */
	public static List<Integer> getMemberParents(Jedis jedis10,int groupId,int uid,boolean self){
		return getMemberParents(jedis10,groupId,uid,self,1);
	}


	public static int getParentsinfo(int groupId,int uid){
		//Jedis jedis10 = Redis.use("group1_db10").getJedis();
		GroupMemberBean gmb = GroupCache.getMember(groupId, uid);
		if (gmb == null)
		{
			return 0;
		}
		int parentId = 0;
		parentId =gmb.parentId;
		return parentId;
	}

	/**
	 * 获取成员上级列表
	 * @param groupId
	 * @param uid
	 * @return
	 */
	public static List<Integer> getMemberParents(Jedis jedis10,int groupId,int uid,boolean self,int start_par_lev){
		GroupMemberBean gmb = GroupCache.getMember(groupId, uid);
		if (gmb == null)
		{
			return null;
		}

		int partnerLev = 0;
		int parentId = 0;
		if(self) {
			partnerLev = gmb.partnerLev;
			if(partnerLev>0) {
				parentId = uid;
			}else {
				parentId =gmb.parentId;
			}
		}else {
			parentId =gmb.parentId;
		}
		
		if(parentId>0) {
			if(parentId!=uid) {
				gmb = GroupCache.getMember(groupId, parentId);
				partnerLev = gmb.partnerLev;
			}
			if(partnerLev==0)return null;
			List<Integer> list = new ArrayList<Integer>(partnerLev);
			for(int i=start_par_lev-1;i<partnerLev;++i) {
				list.add(parentId);
				parentId =gmb.parentId;
				gmb = GroupCache.getMember(groupId, parentId);
			}
			return list;
		}
		return null;
	}


	
	/**
	 * 获取子合伙人Sql
	 * @param groupId
	 * @param uid
	 * @return
	 */
	public static String getChildParentSql(int groupId,int uid,boolean self) {
		String pl_key = String.format("g{%s}:par_list:%s",groupId,uid);
		Set<String> child_list = Redis.use("group1_db10").smembers(pl_key);
		String p = self ? uid+"" : StringUtil.Empty;
		for(String str:child_list) {
			p +=","+str;
		}
		return p;
	}
	
	/**
	 * 获取子合伙人Sql
	 * @param groupId
	 * @param uid
	 * @return
	 */
	public static List<Integer> getChildParentList(int groupId,int uid,boolean self) {
		String pl_key = String.format("g{%s}:par_list:%s",groupId,uid);
		Set<String> child_list = Redis.use("group1_db10").smembers(pl_key);
		List<Integer> list = new ArrayList<>();
		if(self) {
			list.add(uid);
		}
		for(String str:child_list) {
			list.add(Integer.parseInt(str));
		}
		return list;
	}
	
	/**
     * 
     * @param type 1 update 2 call
     * @param sql
     */
    public static void evtdb(int gid, int type, String sql) {
		if (StringUtil.isEmpty(sql))
		    return;
		String str = type + sql;
		Redis.use(CHACHE_KEY).lpush("evt_db_" + (gid % 10), str);
    }

	/**
	 *
	 * @param type 1 update 2 call 插入不是很重要的LOG, 可以走随机线程
	 * @param sql
	 */
	public static void evtdbLog(int gid, int type, String sql) {
		if (StringUtil.isEmpty(sql))
			return;
		String str = type + sql;
		int id = (int)(gid * Math.random() * 100);
		id = id % 10;
		Redis.use(CHACHE_KEY).lpush("evt_db_" + (id), str);
	}
    
	private final static String 			EVT_TYPE = "E";
	private final static String 			EVT_UID = "uid";
	private final static String 			CHACHE_KEY ="group1_db8";
	
	/**
	 * 支付钻石事件
	 * @param type
	 * @param uid
	 * @param game
	 * @param pay
	 * @param gid
	 * @param pid
	 */
	public static void payDiamo(int type,int uid,int game,int pay,int gid,int pid) {
		ITObject data = TObject.newInstance();
		data.putInt("pay", pay);
		data.putInt("game", game);
		data.putInt("group", gid);
		if(pid > 0) {
			data.putInt("pid", pid);
		}
		data.putInt(EVT_UID, uid);
		data.putInt(EVT_TYPE, type);
		Redis.use(CHACHE_KEY).lpush("event_"+(uid%10),data.toJson());
	}
	
	/**
	 * 支付钻石事件
	 * @param type
	 * @param uid
	 * @param game
	 * @param pay
	 * @param cur_diamo
	 * @param gid
	 * @param pid
	 */
	public static void payDiamo(int type,int uid,int game,int pay,int cur_diamo,int gid,int pid) {
		ITObject data = TObject.newInstance();
		data.putInt("pay", pay);
		data.putInt("game", game);
		data.putInt("diamo", cur_diamo);
		data.putInt("group", gid);
		if(pid > 0) {
			data.putInt("pid", pid);
		}
		data.putInt(EVT_UID, uid);
		data.putInt(EVT_TYPE, type);
		Redis.use(CHACHE_KEY).lpush("event_"+(uid%10),data.toJson());
	}
	
	
	final static String pay_lua="local diamo = tonumber(redis.call('hget', KEYS[1],'diamo'))\n"
			+ "local pay = tonumber(ARGV[1]) \n"
			+ "if pay > diamo then \n"
			+ "return {2,0}\n"
			+ "end\n"
			+ "diamo = redis.call('hincrBy',KEYS[1],'diamo',-pay)\n"
			+ "return {0,diamo}";
	
	@SuppressWarnings("unchecked")
	public static ArrayList<Long> payDiamo(Jedis jedis0,String session,int pay) {
		Object obj = jedis0.eval(pay_lua, Arrays.asList(session),Arrays.asList(pay + ""));
		if(obj==null)return null;
		return (ArrayList<Long>) obj;
	}
	
	
	/**
	 * 检测房间钻石
	 * @param jedis0
	 * @param session
	 * @param pay
	 * @param opt
	 * @param AA
	 * @param maxPlayers
	 * @return
	 * @throws Exception
	 */
	public static int checkRoomDiamo(Jedis jedis0,String session,int pay) throws Exception {
		if(pay <=0) {
			return 0;
		}
		int p_diamo = Integer.parseInt(jedis0.hget(session, "diamo"));
		if(p_diamo<pay) {
			return ErrorCode.NO_DIAMO;
		}
		return 0;
	}
	
	/**
	 * 获取session 已在房间
	 * @param jedis0
	 * @param groupId
	 * @param session
	 * @param uid
	 * @return
	 */
	public static final String getOldRoomV2(Jedis jedis0,int groupId,String session,int uid) {
		String oldRoom  = jedis0.hget(session, "room");
		boolean enter_old = false;
        if (StringUtil.isNotEmpty(oldRoom)) {
        	enter_old = true;
        }
		if (enter_old) {
			List<String> _list = jedis0.hmget(oldRoom, "status","score_"+uid);
			String status = _list.get(0);
			if (StringUtil.isEmpty(status) || status.equals("2") || status.equals("3")) {
				jedis0.hdel(session, "room");
				return null;
			}
			String s_uid = _list.get(1);
			if(StringUtil.isNotEmpty(s_uid)) {
				return oldRoom;
			}
		}
		return null;
	}
	
	/**
	 * 删除session房间
	 * @param jedis0
	 * @param session_key
	 * @param room_key
	 * @return
	 */
	public static final boolean delRoomBySession(Jedis jedis0,String session_key, String room_key) {
		String cur_room = jedis0.hget(session_key, "room");
		if (StringUtil.isNotEmpty(cur_room)) {
			if (cur_room.equals(room_key)) {
				if(API_VER==1) {
					jedis0.hdel(session_key, "room", "seat");
				}else {
					jedis0.hdel(session_key, "room");
				}
				return true;
			}
		}
		return false;
	}

}
