package com.mgr.group;

import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import com.data.bean.AccountBean;
import com.data.bean.GroupMemberBean;
import com.data.bean.GroupPlayBean;
import com.data.cache.AccountCache;
import com.data.cache.GroupCache;
import com.data.cache.GroupMemberCache;
import com.data.util.ErrorCode;
import com.mgr.group.data.CommandData;
import com.mgr.group.data.Group;
import com.mgr.group.data.Room;
import com.mgr.group.data.User;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TObject;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.routes.ActionKey;
import com.taurus.core.routes.IController;
import com.taurus.core.util.StringUtil;
import com.taurus.core.util.Utils;
import com.taurus.permanent.TPServer;
import com.taurus.permanent.data.Session;

import com.taurus.web.WebException;
import redis.clients.jedis.Jedis;

/**
 * 基本游戏控制器
 * 
 */
public class GroupController implements IController {

	/**
	 * 请求进入房间
	 */
	@ActionKey(Router.FGMGR_ENTER_GROUP)
	public void RouterJoinGroup(Session sender, ITObject params, int gid) {
		String session_id = params.getUtfString("session");
		String token = null;
		if (StringUtil.isEmpty(session_id)) {
			Global.logger.info("---------------参数session为null，参数params：{}", params);
			session_id = "";
		} else {
			String[] sourceStrArray = session_id.split(",");
			if (sourceStrArray.length == 2) {
				session_id = sourceStrArray[0];
				token = sourceStrArray[1];
			}

			if (StringUtil.isNotEmpty(token) && StringUtil.isNotEmpty(session_id)) {
				String token_session = Redis.use("group1_db0").hget(token, "user");
				String key = session_id + "_token";

				Global.logger.info("---------------key，参数params：{}" + key);

				Set<String> canTokenList = Redis.use("group1_db0").smembers(key);
				Global.logger.info("---------------canTokenList，参数params：{}" + canTokenList);
				Global.logger.info("---------------token，参数params：{}" + token);
				Global.logger.info("---------------session_id，参数params：{}" + session_id);

//				if (canTokenList.size() == 0) {
//					TPServer.me().getController().sendResponse(gid, ErrorCode._NO_SESSION, null, sender);
//					return;
//
//				}
//				boolean canEnter = false;
//				for (String canToken : canTokenList) {
//					if (canToken.equalsIgnoreCase(token)) {
//						canEnter = true;
//					}
//				}
//				if (!canEnter) {
//					TPServer.me().getController().sendResponse(gid, ErrorCode._NO_SESSION, null, sender);
//					return;
//
//				}

				if (StringUtil.isEmpty(token_session)) {
					TPServer.me().getController().sendResponse(gid, ErrorCode._NO_SESSION, null, sender);
					return;
				} else {
					if (!token_session.equals(session_id)) {
						TPServer.me().getController().sendResponse(gid, ErrorCode._NO_SESSION, null, sender);
						return;
					}
				}
			} else {
				TPServer.me().getController().sendResponse(gid, ErrorCode._NO_SESSION, null, sender);
				return;
			}
		}
		sender.setHashId(session_id);
		int groupId = params.getInt("groupId");
		Global.groupCtr.joinGroup(sender, groupId, gid);

	}

	private static AtomicInteger invi_id = new AtomicInteger(0);

	public void joinGroup(Session sender, int groupId, int gid) {
		Group group = null;
		synchronized (Global.groupMap) {
			if (Global.groupMap.containsKey(groupId)) {
				group = Global.groupMap.get(groupId);
			} else {
				group = new Group(groupId);
				Global.groupMap.put(groupId, group);
			}
			group.lastTime = System.currentTimeMillis();
		}

		group.start();
		if (group.isDestroy) {
			TPServer.me().getController().sendResponse(gid, ErrorCode._FAILED, null, sender);
			return;
		}

		group.enqueueRunnable(new Runnable() {

			@Override
			public void run() {
				Group group = Global.groupMap.get(groupId);
				User user = null;
				AccountBean acc = null;
				if (sender != null && StringUtil.isNotEmpty(sender.getHashId())) {
					acc = AccountCache.getAccount(sender.getHashId());
				} else {
					if (sender != null) {
						if (StringUtil.isNotEmpty(sender.getHashId())) {
							Global.logger.info("---------------session.id:" + sender.getId() + " hashId null");
						}
					} else {
						Global.logger.info("---------------session为null，");
					}
				}
				if (acc == null) {
					TPServer.me().getController().sendResponse(gid, ErrorCode._NO_SESSION, null, sender);
					return;
				}
				int uid = acc.id;
				if (!group.userMap.containsKey(uid)) {
					user = new User();
					user.uid = uid;
					user.session_key = AccountCache.genKey(uid);
					user.group = group;
					user.setSender(sender);
					group.userMap.put(uid, user);
				} else {
					user = group.userMap.get(uid);
					user.setSender(sender);
				}
				if (user.gm_key == null) {
					user.gm_key = GroupMemberCache.genKey(groupId, uid);
				}
				String gm_key = user.gm_key;
				sender.setHashId(gm_key);
				GroupMemberBean gmb = GroupCache.getMember(groupId, uid);
				if (gmb == null) {
					user.response(null, gid, ErrorCode._FAILED);
					return;
				}
				int partnerLev = gmb.partnerLev;
				int lev = gmb.lev;
				long hp = 0;
				int permission = gmb.permission;
				int ban = gmb.ban;
				int mail_tip = 0;
				int queueid = 0;
				int seeid = gmb.seeid;
				Jedis jedis10 = Redis.use("group1_db10").getJedis();
				try {
					hp = Long.parseLong(jedis10.hget(gm_key, "hp"));
					queueid = Integer
							.parseInt(jedis10.hget(gm_key, "queueid") == null ? "0" : jedis10.hget(gm_key, "queueid"));
					seeid = Integer
							.parseInt(jedis10.hget(gm_key, "seeid") == null ? "0" : jedis10.hget(gm_key, "seeid"));
					long last_time = System.currentTimeMillis() / 1000;
					jedis10.hset(gm_key, "last_time", last_time + "");
					jedis10.hset(gm_key, "on_line", 1 + "");
					String mail_tip_key = GroupCache.genMailTipKey(groupId);
					Double tem = jedis10.zscore(mail_tip_key, uid + "");
					if (tem != null && tem > 0) {
						mail_tip = 1;
					}
				} finally {
					jedis10.close();
				}
				String fp = Redis.use("group1_db1").hget("alllook", uid + "");
				user.partnerLev = partnerLev;
				if (fp != null) {
					user.lev = 1;
				} else {
					user.lev = lev;
				}

				user.hp = hp;
				// user.queueid = queueid;
				user.ban = ban;
				ITObject info = group.getInfo(lev, uid);

				if (fp != null) {
					info.putInt("lev", 1);
				} else {
					info.putInt("lev", lev);
				}

				// info.putInt("lev", lev);
				info.putInt("partnerLev", partnerLev);
				info.putInt("permission", permission);
				info.putLong("hp", hp);
				info.putInt("mail_tip", mail_tip);
				info.putInt("queueid", queueid);
				info.putInt("seeid", seeid);
				user.response(info, gid, 0);

				// Global.logger.info("joinGroup / playlist --> info: "+info);
			}
		});

	}

	public void addRoom(Group group, String roomid) {
		Room room = group.addRoom(roomid);
		if (room == null)
			return;
		ITObject param = room.data;
		group.addRoomCommand(roomid, CommandData.ADD_ROOM, param);
	}

	public void delRoom(Group group, String roomid) {
		group.delRoom(roomid);
		ITObject param = TObject.newInstance();
		param.putUtfString("roomid", roomid);
		group.addRoomCommand(roomid, CommandData.DEL_ROOM, param);
	}

	public void updateRoom(Group group, String roomid) {
		Room room = group.updateRoom(roomid);
		if (room == null)
			return;
		if (room.priorityValue == 0) {
			ITObject param = TObject.newInstance();
			param.putUtfString("roomid", roomid);
			group.addRoomCommand(roomid, CommandData.DEL_ROOM, param);
		} else {
			ITObject param = room.data;
			group.addRoomCommand(roomid, CommandData.UPDATE_ROOM, param);
		}

	}

	public void delPlay(Group group, int pid) {
		group.delPlay(pid);
		ITObject param = TObject.newInstance();
		param.putInt("pid", pid);
		group.broadCastToClient(Router.FGMGR_EVT_DEL_PLAY, param);
	}

	public void addPlay(Group group, int pid) {
		GroupPlayBean gp = group.addPlay(pid);
		if (gp != null) {
			//
			group.broadCastToClient(Router.FGMGR_EVT_ADD_PLAY, gp.data);

			Global.logger.info("addPlay: -------------> " + gp.data);
		}
	}

	public void updatePlay(Group group, int pid) {
		GroupPlayBean gp = group.addPlay(pid);
		if (gp != null) {
			group.broadCastToClient(Router.FGMGR_EVT_UPDATE_PLAY, gp.data);

			Global.logger.info("updatePlay: -------------> " + gp.data);
		}
	}

	public void updateGroup(Group group, String name, int ban, String notice, int option, int showNum) {
		ITObject param = TObject.newInstance();
		param.putUtfString("name", name);
		param.putInt("ban", ban);
		param.putUtfString("notice", notice);
		param.putInt("option", option);
		param.putInt("show_num", showNum);
		group.broadCastToClient(Router.FGMGR_EVT_UPDATE_GROUP, param);
	}

	public void updateJoins(Group group, int joins) {
		if (joins <= 0)
			return;
		List<Session> list = group.getSessionListByMgr();
		if (list.size() == 0)
			return;
		ITObject param = TObject.newInstance();
		param.putInt("joins", joins);
		TPServer.me().getController().sendEvent(Router.FGMGR_EVT_UPDATE_JOINS, param, list);
	}

	public void updateMember(Group group, int uid, int type, int value) {
//		User user = group.userMap.get(uid);
//		if(user!=null) {
//			ITObject param = TObject.newInstance();
//			param.putInt("type", type);
//			param.putInt("value", value);
//			MainServer.instance.sendEvent(Router.FGMGR_EVT_UPDATE_MEMBER, param, user.sender);
//		}
	}

	public void updateMailTip(Group group, int uid) {
		User user = group.userMap.get(uid);
		if (user != null) {
			ITObject param = TObject.newInstance();
			TPServer.me().getController().sendEvent(Router.FGMGR_EVT_UPDATE_MAILTIP, param, user.sender);
		}
	}
}
