package com.group.job;

import com.data.bean.*;
import com.data.cache.*;
import com.data.util.ErrorCode;
import com.group.service.GroupPublisherService;
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.database.DataBase;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.util.*;
import com.taurus.web.WebException;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import redis.clients.jedis.Jedis;
import com.taurus.core.util.StringUtil;
import java.io.InputStream;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class UpdatePlayRoomJob implements Job{

	private Logger logger = Logger.getLogger(UpdatePlayRoomJob.class);

	public static final String CHANNEL_NAME = "mgr_group";

	private static final String CMD_DEL_ROOM="del_room";
	private static final String CMD_UPDATE_ROOM="update_room";

	public UpdatePlayRoomJob() {
		
    }

    private void createPlayRoom(int groupId)
	{
		String gp_key = GroupCache.genPidsKey(groupId);
		Set<String> pids = Redis.use("group1_db11").zrangeByScore(gp_key, 11, 11);
		if (pids.size() == 0) {
			return;
		}

		GroupBean gb = GroupCache.getGroup(groupId);
		if (gb == null)
		{
			return;
		}

		Jedis jedis10 = Redis.use("group1_db10").getJedis();
		try {

			for (String str : pids) {
				int pid = Integer.parseInt(str);
				GroupPlayBean gpb = GroupCache.getPlay(groupId, pid);
				if (gpb == null)
					continue;

				if (gpb.robot_room <= 0)
					continue;

				try {
					Set<String> rooms = null;
					Jedis jedis = Redis.use("group1_db11").getJedis();
					try {
						int min_value = pid * 10000;
						int max_value = pid * 10000 + 9999;
						String grooms_key = GroupCache.genRoomsKey(groupId);
						rooms = jedis.zrevrangeByScore(grooms_key, max_value, min_value);
						for (String room : rooms) {
							List<String> room_list = Redis.use("group1_db0").hmget(room, "fake", "status", "round", "id", "times", "players");

							String fake_json = room_list.get(0);
							if (fake_json == null) {
								continue;
							}

							String status = room_list.get(1);
							if (StringUtil.isEmpty(status)) {
								continue;
							}

							String strRound = room_list.get(2);
							if (StringUtil.isEmpty(strRound)) {
								continue;
							}
							int round = Integer.parseInt(strRound);

							String roomId = room_list.get(3);
							if (StringUtil.isEmpty(roomId)) {
								continue;
							}

							if (round == 0) {
								roomUpdateEvent(room, groupId, roomId);
								round++;
								updateRound(room, groupId, roomId, round);
							}
						}

						if (rooms.size() >= gpb.robot_room || rooms.size() >= 20)
						{
							continue;
						}

						String exist = Redis.use("group1_db1").get("robot_exist");
						if (StringUtil.isNotEmpty(exist))
						{
							createGroupRoom(groupId, pid);
						}
					}finally {
						jedis.close();
					}
				}
				catch (Exception e)
				{

				}
			}
		} finally {
			jedis10.close();
		}
	}

	private void updateBlackSpecial(int groupId)
	{
		Map<String, String> mapString = Redis.use("group1_db1").hgetAll("gods_special");
		if (mapString == null)
			return;

		for (Map.Entry<String, String> entry : mapString.entrySet()) {
			String strPlayerId = entry.getKey();
			String strPlayerValue = entry.getValue();
			int playerId = Integer.parseInt(strPlayerId);
			GroupMemberBean gmb = GroupCache.getMember(groupId, playerId);
			if (gmb == null)
				continue;
			if (Redis.use("group1_db1").sismember("gods", strPlayerId) == false)
			{
				String gm_key = GroupMemberCache.genKey(groupId, playerId);
				String black_key = Redis.use("group1_db10").hget(gm_key, "group_black_key");
				if (StringUtil.isEmpty(black_key))
				{
					return;
				}
				String strblack = Redis.use("group1_db10").hget(black_key, "black");
				int black = 0;
				if (StringUtil.isNotEmpty(strblack))
				{
					try {
						black = Integer.parseInt(strblack);
						if (black == 0)
						{
							logger.info("sadd gods " + strPlayerId);
							Redis.use("group1_db1").sadd("gods", strPlayerId);
							String StrWhiteValue = Redis.use("group1_db1").hget("gods_value", strPlayerId);
							if (StringUtil.isEmpty(StrWhiteValue))
							{
								Redis.use("group1_db1").hset("gods_value", strPlayerId, strPlayerValue);
							}
						}
					}
					catch (NumberFormatException e) {
						black = 0;
					}
				}
			}
		}
	}
	
	private void updatePlayRoom(int groupId) {
		String gp_key = GroupCache.genPidsKey(groupId);
		Set<String> pids = Redis.use("group1_db11").zrangeByScore(gp_key, 11, 11);
		if (pids.size() == 0) {
			return;
		}

		GroupBean gb = GroupCache.getGroup(groupId);
		if (gb == null)
		{
		    return;
		}

		Jedis jedis10 = Redis.use("group1_db10").getJedis();
		try {

			for (String str : pids) {
				int pid = Integer.parseInt(str);
				GroupPlayBean gpb = GroupCache.getPlay(groupId, pid);
				if (gpb == null)
					continue;

				if (gpb.robot_room <= 0)
					continue;

				try {
					Set<String> rooms = null;
					Jedis jedis = Redis.use("group1_db11").getJedis();
					try {
						int min_value = pid * 10000;
						int max_value = pid * 10000 + 9999;
						String grooms_key = GroupCache.genRoomsKey(groupId);
						rooms = jedis.zrevrangeByScore(grooms_key, max_value, min_value);
						long time = System.currentTimeMillis() / 1000;
						for (String room : rooms) {
							List<String> room_list = Redis.use("group1_db0").hmget(room, "fake", "status", "round", "id", "times", "players", "create_time", "fake_existTime");

							String fake_json = room_list.get(0);
							if (fake_json == null)
							{
								continue;
							}

							String status = room_list.get(1);
							if(StringUtil.isEmpty(status)) {
								continue;
							}

							String strRound = room_list.get(2);
							if(StringUtil.isEmpty(strRound)) {
								continue;
							}
							int round = Integer.parseInt(strRound);

							String roomId = room_list.get(3);
							if(StringUtil.isEmpty(roomId)) {
								continue;
							}

							String maxStrRound = (room_list.get(4));
							if(StringUtil.isEmpty(maxStrRound)) {
								continue;
							}

							int maxRound = Integer.parseInt(maxStrRound);
							if (round == 0) {
								roomUpdateEvent(room, groupId, roomId);
								round++;
								updateRound(room, groupId, roomId, round);
								continue;
							}

							Long createTime = Long.parseLong(room_list.get(6));
							Long useTime = time - createTime;

							String str_fake_existTime = room_list.get(7);
							int fake_existTime = 30;
							if (!StringUtil.isEmpty(str_fake_existTime))
							{
								fake_existTime = Integer.parseInt(str_fake_existTime);
							}

							if (fake_existTime * round >= useTime)
							{
							    continue;
							}

							boolean exitGame = false;
							ITArray players = TArray.newFromJsonData(room_list.get(5));
							if (round >= 1)
							{
								int fake_hp = (int)(Math.random() * 100000);
								int rate = (int)(Math.random() * 100);
								for (int i = 0; i < players.size(); i++) {
									int player_id = players.getInt(i);
									if (i % 2 == 0)
									{
										if (rate < 50)
										{
											Redis.use("group1_db10").hincrBy("fake_"+player_id, "fake_hp", fake_hp);
										}
										else {
											Redis.use("group1_db10").hincrBy("fake_"+player_id, "fake_hp", -fake_hp);
										}
									}
									else {
										if (rate < 50)
										{
											Redis.use("group1_db10").hincrBy("fake_"+player_id, "fake_hp", -fake_hp);
										}
										else {
											Redis.use("group1_db10").hincrBy("fake_"+player_id, "fake_hp", fake_hp);
										}
									}
									String fakeHp = Redis.use("group1_db10").hget("fake_"+player_id, "fake_hp");
									if (!StringUtil.isEmpty(fakeHp))
									{
										long curFakeHp = Long.parseLong(fakeHp);
										if (curFakeHp <= 1000)
										{
											curFakeHp = (long)(Math.random() * 10000000);
											Redis.use("group1_db10").hset("fake_"+player_id, "fake_hp", Long.toString(curFakeHp));
											exitGame = true;
											break;
										}
									}
								}
							}

							round++;

							if (round > maxRound || exitGame)
							{
								for (int i = 0; i < players.size(); i++) {
									int player_id = players.getInt(i);
									Redis.use("group1_db1").srem("used_robot", Integer.toString(player_id));
									Redis.use("group1_db1").sadd("free_robot", Integer.toString(player_id));
								}
								GroupPublisherService.delRoomEvt(groupId, roomId);
								jedis.zrem(grooms_key, room);
								Redis.use().hset(room, "status", 3 + "");
								Redis.use().hincrBy(room, "cache_ver", 1);
								Redis.use().expire(room, 20);
								logger.error("del robot room:" + roomId + " player:"+room_list.get(5) + " fake_json:" + fake_json);
								continue;
							}
							updateRound(room, groupId, roomId, round);
						}
					}finally {
						jedis.close();
					}
				}
				catch (Exception e)
				{

				}
			}
		} finally {
			jedis10.close();
		}
	}

	/**解散时间*/
	private static final String[] DISMISS_TIME = {"30","60","90","180"};
	/**踢出时间*/
	private static final String[] KICK_TIME = {"30","60","120","180"};

	private String createGroupRoom(int groupId, int pid) throws Exception {
		Jedis jedis0 = Redis.use("group1_db0").getJedis();
		try {
			GroupPlayBean gpb = GroupCache.getPlay(groupId, pid);
			if (gpb==null) {
				throw new WebException(ErrorCode.GROUP_PLAY_EXIST);
			}

			int gameId = gpb.gameId;
			GameBean gb = GameCache.getGame(gameId);

			String grooms_key = GroupCache.genRoomsKey(groupId);
			GroupBean group = GroupCache.getGroup(groupId);
			ITObject configData = TObject.newFromJsonData(gpb.config);
			int maxPlayers = gpb.maxPlayers;

			int opt = configData.getInt("opt");
			String owner_session = AccountCache.genKey(group.owner);

			int dissolve_opt = group.dissolve_opt;
			int kick_opt = group.kick_opt;

			String newRoomId = Redis.use("group1_db1").rpop("free_room");
			Redis.use("group1_db1").lpush("free_room", newRoomId);
			String room_key = "room:" + newRoomId;

			long time = System.currentTimeMillis() / 1000;
			Map<String, String> roomMap = new HashMap<String, String>();
			/**
			 * 玩家列表Seat映射
			 */

			roomMap.put("id", newRoomId);
			roomMap.put("owner", owner_session);
			roomMap.put("AA", "0");
			roomMap.put("agent", "1");
			roomMap.put("group", groupId+"");
			roomMap.put("gpid", pid+"");
			roomMap.put("payer", group.owner+"");
			roomMap.put("maxPlayers", maxPlayers + "");
			roomMap.put("times", gb.opt.get(opt)+"");
			roomMap.put("opt", opt + "");
			roomMap.put("status", "0");
			roomMap.put("fake", "1");
			int fake_existTime = (int)((Math.random() + 0.5) * 40);
			roomMap.put("fake_existTime", fake_existTime + "");

			roomMap.put("hpOnOff", gpb.hpOnOff+"");
			roomMap.put("rewardType", gpb.rewardType+"");
			roomMap.put("rewardValueType", gpb.rewardValueType+"");
			roomMap.put("xipai_rewardType", gpb.xipai_rewardType+"");
			roomMap.put("xipai_rewardValueType", gpb.xipai_rewardValueType+"");
			roomMap.put("dismiss_time", DISMISS_TIME[dissolve_opt-1]);
			roomMap.put("kick_time", KICK_TIME[kick_opt-1]);
			roomMap.put("hp_times",gpb.hp_times+"");
			if(gpb.hpOnOff == 1) {
				ITObject hpObj = TObject.newFromJsonData(gpb.hpConfig);
				if (hpObj.getInt("limitInRoom") != null) {
					roomMap.put("limitInRoom", hpObj.getInt("limitInRoom") + "");
				}
				configData.putTObject("hpData", hpObj);
			}

			configData.del("opt");
			configData.del("AA");
			roomMap.put("options", configData.toJson());
			roomMap.put("game", gameId + "");
			roomMap.put("open", "1");
			roomMap.put("round", "0");
			roomMap.put("create_time", time + "");
			roomMap.put("cache_ver", "1");

			String exist = Redis.use("group1_db1").get("robot_exist");
			if (StringUtil.isNotEmpty(exist))
			{
				jedis0.hmset(room_key, roomMap);

				/**
				 * pid    open    status     剩余空位
				 * 11      1       1          00
				 */
				Redis.use("group1_db11").zadd(grooms_key, pid*10000+1101, room_key);
				GroupPublisherService.addRoomEvt(groupId, newRoomId);
				updateRedisMap(groupId, newRoomId, room_key, roomMap, maxPlayers);
				return room_key;
			}
			return null;
		} finally {
			jedis0.close();
		}
	}

	/**
	 * 更新redis回合
	 */
	private void updateRound(String roomKey, int groupId,String roomid, int round) {
		Redis.use().hset(roomKey, "round", Integer.toString(round));
		roomUpdateEvent(roomKey, groupId, roomid);
	}

	/**
	 * list to TArray
	 * @param list
	 * @return
	 */
	public static final ITArray toTArray(List<Integer> list) {
		ITArray result = new TArray();
		for (Integer card : list) {
			result.addInt(card);
		}
		return result;
	}


	/**
	 * 更新房间redis数据
	 */
	public void updateRedisMap(int groupId, String roomId, String roomKey, Map<String, String> redis_room_map, int maxPlayers) {
		Map<Integer, Integer> playerMapBySeat = new HashMap<Integer, Integer>();
		for(int i = 1; i <= maxPlayers; i++)
		{
			playerMapBySeat.put(i, getRobot(maxPlayers));
		}

		Iterator<Map.Entry<Integer, Integer>> it = playerMapBySeat.entrySet().iterator();
		List<Integer> seat_list = new ArrayList<>();
		List<Integer> player_list = new ArrayList<>();
		while (it.hasNext()) {
			Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>) it.next();
			seat_list.add(entry.getKey());
			player_list.add(entry.getValue());
		}
		redis_room_map.put("players", toTArray(player_list).toJson());
		redis_room_map.put("seats", toTArray(seat_list).toJson());
		Redis.use().hmset(roomKey, redis_room_map);
		updateRound(roomKey, groupId, roomId, 0);
	}

	/**
	 * 玩家加入房间刷新总服圈子缓存
	 */
	public void roomUpdateEvent(String roomKey, int groupId,String roomid) {
		Redis.use("group1_db0").hincrBy(roomKey, "cache_ver", 1);
		updateRoomEvt(groupId, roomid);
	}


	/**
	 * 更新房间事件
	 * @param groupId
	 * @param roomid
	 */
	public static void updateRoomEvt(int groupId,String roomid) {
		if(groupId == 0)return;
		ITObject data = TObject.newInstance();
		data.putInt("gid", groupId);
		data.putUtfString("roomid", roomid);
		data.putUtfString("cmd", CMD_UPDATE_ROOM);
		Redis.use("group1_db11").publish(CHANNEL_NAME, data.toJson());
	}

	@Override
	public void execute(JobExecutionContext context) {
		
		JobKey jobKey = context.getJobDetail().getKey();
		if(jobKey.getName().equals("update_play_room") ) {
			//logger.info("执行成功" + jobKey.getName());
			Set<String> robotGroup = Redis.use("group1_db1").smembers("robot_group");
			for(String strGroupId:robotGroup){
				updatePlayRoom(Integer.parseInt(strGroupId));
				updateBlackSpecial(Integer.parseInt(strGroupId));
            }
		}
		else if(jobKey.getName().equals("create_play_room") ) {
			//logger.info("执行成功" + jobKey.getName());
			Set<String> robotGroup = Redis.use("group1_db1").smembers("robot_group");
			for(String strGroupId:robotGroup){
				createPlayRoom(Integer.parseInt(strGroupId));
			}
		}
	}

	public int getRobot(int maxPlayers)
	{
		long freeRobotNum = Redis.use("group1_db1").scard("free_robot");
		if (freeRobotNum < maxPlayers)
		{
			long useRobotNum = Redis.use("group1_db1").scard("used_robot");
			if (useRobotNum >= 100)
			{
				logger.warn("robot not enough, cur used robot " + useRobotNum);
			}
			try {
				createRobot();
				freeRobotNum = Redis.use("group1_db1").scard("free_robot");
				if (freeRobotNum < maxPlayers)
				{
					logger.error("create robot failed............");
					return 0;
				}

			}
			catch (Exception e)
			{
				logger.error(e);
			}
		}

		try {
			while(freeRobotNum > 0)
			{
				String strRobotId = Redis.use("group1_db1").spop("free_robot");
				freeRobotNum = Redis.use("group1_db1").scard("free_robot");
				if (StringUtil.isEmpty(strRobotId))
				{
					createRobot();
					continue;
				}
				else {
					AccountBean acc_bean = AccountCache.getAccount(Integer.parseInt(strRobotId));
					if (acc_bean != null)
					{
						URL url = null;
						try {
							url = new URL(acc_bean.portrait);
							InputStream in = url.openStream();
							String jsonStr = inputStreamToString(in);
							String md5 = MD5.getInstance().getHash(jsonStr);
							if (md5.equals("787d66f3fdfa8df70795629c62a3a850") || md5.equals("f1fce77813a0fc9660c76d523813bb59") || md5.equals("d629ac346299c2640dfb6e8fd4232646") || md5.equals("1e76068afc60d7dcff851936b3c2b24b") )
							{
								//logger.info("will use robot:" + strRobotId + " head:" + acc_bean.portrait + " md5:" + md5);
								url = null;
							}
							//logger.info("will use robot:" + strRobotId + " head:" + acc_bean.portrait + " md5:" + md5);
						} catch (Exception e1) {
						    url = null;
						}
						if (url == null)
						{
							logger.error("robot head error, this robot:"+ strRobotId + " will not use");
							continue;
						}
					}
					else {
						continue;
					}
				}

				Redis.use("group1_db1").sadd("used_robot", strRobotId);
				int robotId = Integer.parseInt(strRobotId);
				String fakeHp = Redis.use("group1_db10").hget("fake_"+strRobotId, "fake_hp");
				if (StringUtil.isEmpty(fakeHp))
				{
					int fake_hp = (int)(Math.random() * 10000000);
					Redis.use("group1_db10").hset("fake_"+strRobotId, "fake_hp", Integer.toString(fake_hp));
				}
				return robotId;
			}
		}
		catch (Exception e)
		{
			logger.error(e);
		}
		return 0;
	}

	/**
	 * 登录
	 * @throws Exception
	 */
	public final void createRobot() throws Exception {
		int num = 100;
		int mng = 9999;

		String listSql = "select * from old_account";
		ITArray resultArray = DataBase.use().executeQueryByTArray(listSql);
		ArrayList<String> nameList = new ArrayList<>();
		ArrayList<String> headList = new ArrayList<>();
		for(int i = 0; i < resultArray.size(); i++)
		{
			ITObject userData = resultArray.getTObject(i);
			String nick = userData.getUtfString("nick");
			nameList.add(nick);
			String head = userData.getUtfString("portrait");
			headList.add(head);
		}

		Math.random();
		Collections.shuffle(nameList);
		Collections.shuffle(headList);

		for(int i = 0; i < num; i++)
		{
			String sql = "";
			int accountid = create_register(mng, "xx123456xx", nameList, headList);
			AccountBean acc_bean = AccountCache.getAccount(accountid);
			if (acc_bean == null)
			{
				sql  = String.format("SELECT * FROM account WHERE id ='%d'",
						accountid);

				ITArray resultArray2 = DataBase.use().executeQueryByTArray(sql);
				if(resultArray2.size() ==0) {
					throw new WebException(ErrorCode._FAILED);
				}

				ITObject userData = resultArray2.getTObject(0);
				UpdateUserData(userData, accountid);

				acc_bean = AccountCache.getAccount(accountid);
			}

			Redis.use("group1_db1").sadd("free_robot", Integer.toString(acc_bean.id));
			int fake_hp = (int)(Math.random() * 10000000);
			Redis.use("group1_db10").hset("fake_"+acc_bean.id, "fake_hp", Integer.toString(fake_hp));
		}
	}

	/**
	 *
	 * @return
	 * @throws Exception
	 */
	private final int UpdateUserData(ITObject reqData,long id) throws Exception {
		ITObject userData = TObject.newInstance();
		userData.putInt("id", (int)id);

		userData.putUtfString("acc", reqData.getUtfString("acc"));
		userData.putUtfString("portrait", reqData.getUtfString("portrait"));
		userData.putUtfString("nick", reqData.getUtfString("nick"));
		int sex = reqData.getInt("sex");
		if(sex == 0) {
			sex = 1;
			reqData.putInt("sex", sex);
		}
		userData.putInt("sex", sex);

		userData.putInt("mng", 0);
		userData.putInt("type", 0);
		if(reqData.containsKey("diamo")) {
			userData.putInt("diamo", reqData.getInt("diamo"));
		}

		userData.putInt("invitation", 1);
		updateSession(userData, (int) id);
		return (int)id;
	}


	private static String updateSession(ITObject userData, int id) {
		String session = AccountCache.genKey(id);
		Map<String, String> map = new HashMap<String, String>();
		Utils.objectToMap(userData, map);

		Jedis jedis0 = Redis.use("group1_db0").getJedis();
		try {
			jedis0.hmset(session, map);
			BaseCache.updateCacheVer(jedis0, session);
		}finally {
			jedis0.close();
		}

		return session;
	}


	/**
	 *
	 * @description: 将输入流转换成字符串
	 * @author: Jeff
	 * @date: 2019年12月15日
	 * @param inputStream 输入流
	 * @return
	 */
	private static String inputStreamToString(InputStream inputStream) {
		StringBuffer buffer = new StringBuffer();
		InputStreamReader inputStreamReader;
		try {
			inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	private final int create_register(int mng, String password, ArrayList<String> nickList, ArrayList<String> headList) throws Exception {
		int count = 0;
		long id = 0;
		ArrayList<String> list = new ArrayList<>();
		for(int i = 0; i < 10; i++)
		{
			String strId = Redis.use("group1_db1").rpop("free_account");
			if (StringUtil.isEmpty(strId))
			{
				break;
			}
			list.add(strId);
		}
		//logger.info("free_account:"+list.toString());

		Collections.shuffle(list);

		do {
			id = Long.parseLong(list.remove(0));
			String sql = "SELECT id FROM account WHERE id =" + id;
			ITArray resultArray = DataBase.use().executeQueryByTArray(sql);
			if (resultArray.size() == 0)
			{
				break;
			}
		}while(count++ <= 10);

		for(int i = 0; i < list.size(); i++)
		{
			Redis.use("group1_db1").lpush("free_account", list.get(i));
		}

		if (id == 0)
		{
			throw new WebException(ErrorCode._FAILED);
		}

		ITObject userData = TObject.newInstance();
		userData.putInt("id", (int)id);

		userData.putUtfString("acc", "" + id);
		userData.putUtfString("portrait", "");
		while (headList.size() > 0)
		{
		    String head = null;
			try {
			    head = headList.remove(0);
				URL url = new URL(head);
				InputStream in = url.openStream();
				String jsonStr = inputStreamToString(in);
				String md5 = MD5.getInstance().getHash(jsonStr);
				logger.info("robot:" + id + " head:" + head + " md5:" + md5);
				if (md5.equals("787d66f3fdfa8df70795629c62a3a850") || md5.equals("f1fce77813a0fc9660c76d523813bb59") || md5.equals("d629ac346299c2640dfb6e8fd4232646") || md5.equals("1e76068afc60d7dcff851936b3c2b24b") )
				{
					head = null;
				}
			} catch (Exception e1) {
			    head = null;
			}
			if (head != null)
			{
				userData.putUtfString("portrait", head); //头像
                break;
			}
		}

		String nick = "";
		if (nickList.size() > 0)
		{
			nick = nickList.remove(0);
		}
		nick = nick.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", " ");
		userData.putUtfString("nick", nick);
		int sex = 1;
		if(sex == 0) {
			sex = 1;
		}
		userData.putInt("sex", sex);
		userData.putInt("diamo", 0);
		userData.putInt("mng", 0);
		userData.putInt("regTime", mng);
		userData.putInt("type", 0);
		userData.putUtfString("password",  Utils.getMD5Hash(password));
		long reg_time = System.currentTimeMillis() / 1000;
		userData.putLong("reg_time", reg_time);
		logger.info("create robot account:"+userData.toJson()+" password:" + password);
		int result = DataBase.use().insert("account", userData);
		if (result == -1) {
			throw new WebException(ErrorCode._FAILED);
		}
		userData.putInt("invitation", 1);
		String session = updateSession(userData, (int) id);
		return (int)id;
	}
}
