package com.game;

import java.util.List;

import com.data.bean.GameBean;
import com.data.bean.GroupBean;
import com.data.bean.GroupPlayBean;
import com.data.cache.GameCache;
import com.data.cache.GroupCache;
import com.data.cache.GroupMemberCache;
import com.data.util.EventType;
import com.game.data.Player;
import com.game.data.Room;
import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TObject;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.util.StringUtil;

/**
 * redis 事件控制器
 */
public class EventController {
	private final static String GROUP_EVT_KEY = "evt_group_";
	private final static String EVT_KEY = "event_";
	private final static String CHACHE_KEY = "group1_db8";

	private final static String EVT_TYPE = "E";
	private final static String EVT_GID = "gid";
	private final static String EVT_UID = "uid";

	private static void sendGroupEvt(int type, int gid, ITObject data) {
		int id = gid % 10;
		data.putInt(EVT_GID, gid);
		data.putInt(EVT_TYPE, type);
		Redis.use(CHACHE_KEY).lpush(GROUP_EVT_KEY + id, data.toJson());
	}

	private static void sendEvt(int type, int uid, ITObject data) {
		int id = uid % 10;
		data.putInt(EVT_UID, uid);
		data.putInt(EVT_TYPE, type);
		Redis.use(CHACHE_KEY).lpush(EVT_KEY + id, data.toJson());
	}

	/**
	 * 注册redis事件
	 * 
	 * @param uid
	 * @param type
	 * @param num
	 */
	public void redisEvent(int uid, int type, int num) {
		ITObject data = TObject.newInstance();
		data.putInt("N", num);
		sendEvt(type, uid, data);
	}

	/**
	 * 圈子一局结束事件
	 * 
	 * @param gid
	 * @param pid
	 * @param valid
	 */
	public void redisGroupRound(Room room, int gid, int pid, int valid) {
		ITObject data = TObject.newInstance();
		data.putInt("pid", pid);
		data.putInt("valid", valid);
		List<Player> list = room.scoreDesc();
		Player winner = list.get(0);
		for (int i = 0; i < room.getValidPlayerList().size(); i++) {
			if (winner.playerid == room.getValidPlayerList().getInt(i)) {
				data.putInt("win_player", winner.playerid);
			}
		}
		data.putTArray("player_list", room.getValidPlayerList());
		data.putInt("perfect_round", room.endType == Constant.END_TYPE_NORMAL ? 1 : 0);
		int maxPlayer = room.getValidPlayer();
		Global.logger.info("maxPlayer:" + maxPlayer);
		Global.logger.info("valid:" + valid);
		if (valid == 1 && maxPlayer > 0) {
			data.putInt("valid_count", 100);
//			data.putInt("valid_count", 100 / maxPlayer);

		} else {
			data.putInt("valid_count", 0);
		}

		if (maxPlayer > 0) {
			data.putInt("all_count", 100 / maxPlayer);
		}

		try {
			GroupPlayBean gpb = GroupCache.getPlay(gid, pid);
			if (gpb != null) {
				int maxPlayers = gpb.maxPlayers;
				ITObject configData = TObject.newFromJsonData(gpb.config);
				int opt = configData.getInt("opt");
				int gameId = gpb.gameId;
				GameBean gb = GameCache.getGame(gameId);
				if (gb != null) {
					Integer pay = gb.pay.get("pay" + opt + "_" + maxPlayers);
					if (pay != null && pay > 0 && maxPlayer > 0) {
						data.putInt("valid_diamo", pay * 100 / maxPlayer);
					}
				}
			}
		} catch (Exception e) {
			Global.logger.error(e);
		}

		sendGroupEvt(EventType.REDIS_EVENT_GROUP_ROUND, gid, data);
	}

	/**
	 * 圈子玩家一局结束事件
	 * 
	 * @param owner
	 * @param pid
	 * @param win
	 */
	public void redisGroupMemberRound(Player owner, int pid, boolean win, boolean hpPump, int cur_hp) {

		Room room = owner.room;
		ITObject data = TObject.newInstance();
		data.putInt("pid", pid);
		data.putInt("uid", owner.playerid);
		if (owner.hp != null) {
			data.putInt("score", owner.hp.total_hp);
		} else {
			data.putInt("score", owner.score.total_score);
		}
		data.putInt("time", (int) (System.currentTimeMillis() / 1000));
		data.putInt("pump", owner.practicalHpPump);
		data.putInt("pumpReal", owner.practicalHpPumpReal);
		data.putInt("pumpBase", room.basePump);

		data.putInt("xi_pai_total", owner.xi_pai_total);
		data.putInt("win", win ? 1 : 0);
		data.putInt("perfect_round", owner.room.endType == Constant.END_TYPE_NORMAL ? 1 : 0);
		data.putInt("cur_hp", cur_hp);
		data.putUtfString("room", room.roomid);
		int maxPlayer = owner.room.getValidPlayer();
		Global.logger.info("maxPlayer:" + maxPlayer);
		Global.logger.info("hpPump:" + hpPump);

		// if (hpPump && maxPlayer > 0) {
		data.putInt("valid_count", 100 / maxPlayer);
		// } else {
		// data.putInt("valid_count", 0);
		// }

		sendGroupEvt(EventType.REDIS_EVENT_GROUP_MEMBER_ROUND, owner.room.groupId, data);
	}

	/**
	 * 注册redis体力值事件 reward以前没有用到，现在表示抽水值只给盟主，不给合伙人参与分成
	 */
	public long redisFag(Player owner, int hp, boolean hpPump, boolean mengzhu_reward, int xipai_score, boolean xipai,
			String desc) {
		Room room = owner.room;
		String gm_key = GroupMemberCache.genKey(room.groupId, owner.playerid);
		Global.logger.info("playid:" + owner.playerid + "hp:" + hp + "total_hp:" + owner.hp.total_hp + "hpPump:"
				+ hpPump + "mr:" + mengzhu_reward + "xp:" + xipai_score + "xipai:" + xipai + "desc:" + desc
				+ "owner.practicalHpPumpReal:" + owner.practicalHpPumpReal);
		long cur_hp = 0;
		if (hpPump) {
			String strCurHp = Redis.use("group1_db10").hget(gm_key, "hp");
			if (StringUtil.isNotEmpty(strCurHp)) {
				cur_hp = Long.parseLong(strCurHp);
				if (cur_hp < owner.practicalHpPumpReal) {
					owner.practicalHpPumpReal = (int) cur_hp;
					owner.practicalHpPump = (int) cur_hp / 2;
					if (owner.practicalHpPumpReal < 0) {
						owner.practicalHpPumpReal = 0;
					}
				}
			}
			cur_hp = Redis.use("group1_db10").hincrBy(gm_key, "hp", -owner.practicalHpPumpReal);
		} else if (xipai) {
			String strCurHp = Redis.use("group1_db10").hget(gm_key, "hp");
			if (StringUtil.isNotEmpty(strCurHp)) {
				cur_hp = Long.parseLong(strCurHp);
				if (cur_hp < xipai_score) {
					xipai_score = (int) cur_hp;
					if (xipai_score < 0) {
						xipai_score = 0;
					}
				}
			}
			cur_hp = Redis.use("group1_db10").hincrBy(gm_key, "hp", -xipai_score);
		} else {
			cur_hp = Redis.use("group1_db10").hincrBy(gm_key, "hp", hp);
		}

		ITObject data = TObject.newInstance();
		if (cur_hp > Integer.MAX_VALUE) {
			long del_value = cur_hp - (long) Integer.MAX_VALUE;
			cur_hp = Redis.use("group1_db10").hincrBy(gm_key, "hp", -del_value);
			Redis.use("group1_db10").hincrBy(gm_key, "bank_hp", del_value);
			data.putInt("hp_than_max_value", (int) del_value);
		}
		if (owner.hp.total_hp == 0 && !xipai) {
			// 如果平局则每人抽保底的一半
			Redis.use("group1_db10").hincrBy(gm_key, "hp", -room.basePump);
			GroupBean gb = GroupCache.getGroup(room.groupId);
//			String qunzhu_key = GroupMemberCache.genKey(room.groupId, gb.owner);
//			Redis.use("group1_db10").hincrBy(qunzhu_key, "hp", room.basePump);
		}
		Global.logger.info("hp:" + hp);
		Global.logger.info("cur_hp:" + cur_hp);
		Global.logger.info("owner.prs:" + owner.prs);
		Global.logger.info("owner.hp.total_hp:" + owner.hp.total_hp);

		data.putInt("hp", hp);
		data.putInt("cur_hp", (int) cur_hp);
		data.putInt("pid", room.groupPid);
		data.putInt("uid", owner.playerid);
		data.putInt("time", (int) (System.currentTimeMillis() / 1000));
		data.putUtfString("room", room.roomid);
		// 临时处理
		data.putUtfString("desc", StringUtil.isNotEmpty(desc) ? desc : Global.gameName + " " + room.roomid);
		data.putInt("rewardType", room.rewardType);
		data.putInt("rewardValueType", room.rewardValueType);
		data.putInt("xipai_rewardType", room.xipai_rewardType);
		data.putInt("xipai_rewardValueType", room.xipai_rewardValueType);

		if (xipai) {
			data.putInt("xipai", xipai_score);
			int xipai_reward_value = 0;
			if (room.xipai_rewardValueType == 1) {
				xipai_reward_value = xipai_score;
			}

			data.putInt("max_player", room.maxPlayers);
			data.putInt("xipai_reward_type", room.xipai_rewardType);
			data.putInt("xipai_reward_value", xipai_reward_value);

		}
		int readScore = xipai ? owner.hp.total_hp - xipai_score : owner.hp.total_hp;
		ITArray rewards_list = room.hpData.getTArray("rewards_list");
		int UpperLimit = 0;
		int UpperLimitReward = 0;
		if (rewards_list.size() > 0) {
			UpperLimit = rewards_list.getTObject(0).getInt("UpperLimit");
			UpperLimitReward = rewards_list.getTObject(0).getInt("UpperLimitReward");
		}
		data.putInt("pumpReal", 0);

		if (UpperLimit > readScore && mengzhu_reward && readScore > 0) {
			// 如果输赢低于UpperLimit的分数则只扣除大赢家

			data.putInt("pumpBase", UpperLimitReward);
			data.putInt("pumpBaseWin", UpperLimitReward);

		} else if (UpperLimit > readScore && mengzhu_reward && readScore == 0 && !xipai) {
			// 如果平局则扣双方
			data.putInt("pumpBase", room.basePump);
		} else {
			// 否则不扣保底分
			if (hpPump) {
				owner.practicalHpPumpReal = rewards_list.getTObject(0).getInt("pumpProportion");
			}
			data.putInt("pumpBase", 0);
			data.putInt("pumpReal", owner.practicalHpPumpReal);
			data.putInt("hpReal", hp);

		}
		Global.logger.info("mengzhu_reward:" + mengzhu_reward);
		Global.logger.info("readScore:" + readScore);

		Global.logger.info("room.basePump:" + data.getInt("pumpBase"));
		if (hpPump || room.basePump != 0) {
			data.putInt("pump", owner.practicalHpPump);

			int reward_value = 0;
			int max_player = room.getValidPlayer();
			if (room.rewardValueType == 1) {

				if (room.rewardType == 1) {
					if (room.totalPump + room.basePump != 0) {
						reward_value = owner.practicalHpPump
								- room.basePump * owner.practicalHpPump / (room.totalPump + room.basePump);
					} else {
						reward_value = owner.practicalHpPump;
					}
				} else {
					reward_value = room.totalPump / max_player;
					if (room.basePump > 0) {
						if (reward_value + (room.basePump / max_player) > owner.practicalHpPump) {
							reward_value = owner.practicalHpPump - (room.basePump / max_player);
							if (reward_value < 0) {
								reward_value = 0;
							}
						}
					} else {
						if (reward_value > owner.practicalHpPump) {
							reward_value = owner.practicalHpPump;
						}
					}
				}
			}

			data.putInt("max_player", room.getValidPlayer());
			data.putInt("reward_type", room.rewardType);
			data.putInt("reward_value", reward_value);
		}
		if (StringUtil.isNotEmpty(owner.prs)) {
			data.putUtfString("prs", owner.prs);
		}

		Global.logger.info("记录：" + data);
		sendGroupEvt(EventType.REDIS_EVENT_GROUP_HP, room.groupId, data);
		return cur_hp;
	}

	/**
	 * 返还钻石
	 * 
	 * @param uid
	 * @param pay
	 * @param groupId
	 */
	public void refundDiamo(int uid, int pay, int groupId, int pid) {
		ITObject data = TObject.newInstance();
		data.putInt("pay", -pay);
		data.putInt("game", Global.gameId);
		if (groupId > 0) {
			data.putInt("group", groupId);
			data.putInt("pid", pid);
		}
		sendEvt(EventType.REDIS_EVENT_BACK_PAY, uid, data);
	}

	/**
	 * 大局结束事件
	 * 
	 * @param gid
	 * @param pid
	 * @param valid
	 */
	public void redisOver(Player owner, int time, String rec_key) {
		Room room = owner.room;
		ITObject data = TObject.newInstance();
		if (StringUtil.isNotEmpty(rec_key)) {
			data.putInt("is_rec", 1);
			data.putUtfString("roomid", room.roomid);
			data.putInt("gid", room.groupId);
			data.putUtfString("rec_key", rec_key);
			data.putInt("time", time);
		} else {
			data.putInt("is_rec", 0);
		}
		sendEvt(EventType.REDIS_EVENT_OVER, owner.playerid, data);
	}
}
