package com.mjlogin.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

import org.eclipse.jetty.util.log.Log;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.data.bean.AccountBean;
import com.data.bean.GameBean;
import com.data.cache.AccountCache;
import com.data.cache.BaseCache;
import com.data.cache.GameCache;
import com.data.util.ErrorCode;
import com.data.util.Utility;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mjlogin.MainServer;
import com.mjlogin.Protocol;
import com.mjlogin.WebInterceptor;
import com.mjlogin.util.sms.RedisKey;
import com.mjlogin.util.sms.WeChatOpenIdValidator;
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.plugin.redis.RedisLock;
import com.taurus.core.routes.ActionKey;
import com.taurus.core.util.Logger;
import com.taurus.core.util.StringUtil;
import com.taurus.core.util.Utils;
import com.taurus.web.Controller;
import com.taurus.web.WebException;

import redis.clients.jedis.Jedis;

public class AccountService extends Controller {
	private static Logger logger = Logger.getLogger(AccountService.class);

	/**
	 * 手机验证码登录
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.PHONE_PASSWORD_LOGIN)
	public final void phoneCodeLogin() throws Exception {
		ITObject reqDatas = this.getParams();
		String phone = reqDatas.getUtfString("phone");
		String code = reqDatas.getUtfString("password");
		logger.info("jefe phone:" + phone + " == code:" + code);
		// 判断code 是否正确
		if (Redis.use("group1_db1").exists("code" + phone)) {

			String vfcode = Redis.use("group1_db1").get("code" + phone);
			logger.info("jefe phone:" + phone + " == code:" + code + "vfcode:" + vfcode);
			if (vfcode.equals(code)) {
				String acc = md5(phone);

				ITObject reqData = TObject.newInstance();

				String sqluid = "SELECT id,nickname FROM uuids WHERE uuid =?";
				String[] params1 = new String[1];
				params1[0] = acc + "";

				ITArray resultArrayuid = DataBase.use().executeQueryByTArrayLogin(sqluid, params1);
				int accountUid = 0;
				String nickname = "";
				if (resultArrayuid.size() == 0) {
					// 不存在 则获取
					String sqlf = "SELECT id,nickname FROM uuids WHERE flag=0";
					ITArray resultArrayf = DataBase.use().executeQueryByTArrayLogin(sqlf, new String[0]);

					if (resultArrayf.size() == 0) {
						return;
					}

					ITObject obj = resultArrayf.getTObject(0);
					accountUid = obj.getInt("id");
					nickname = obj.getString("nickname");
					String sqlb = "UPDATE uuids SET uuid='" + acc + "' , flag=1  where id=" + accountUid;
					DataBase.use().executeUpdate(sqlb);
					// resData.putInt("id",accountid);
					// resData.putString("nickname",nickname);
				} else {
					ITObject obj = resultArrayuid.getTObject(0);
					accountUid = obj.getInt("id");
					nickname = obj.getString("nickname");
					// resData.putInt("id",accountid);
					// resData.putString("nickname",nickname);
				}

				// 获取头像信息
				String sql = "SELECT id FROM account WHERE acc =?";
				String[] params2 = new String[1];
				params2[0] = acc + "";

				ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params2);

				reqData.putUtfString("acc", acc);
				reqData.putInt("sex", 1);
				// String strNick = reqData.getUtfString("nick");
				String strNick = nickname;
				strNick = StringUtil.filterEmoji(strNick);
				reqData.putUtfString("nick", strNick);
				reqData.putUtfString("portrait",
						"https://headerimgs2023.oss-cn-guangzhou.aliyuncs.com/headers/man_" + accountUid + ".jpg");
				int accountid = 0;
				if (resultArray.size() == 0) {
					accountid = register(reqData);
				} else {
					ITObject obj = resultArray.getTObject(0);
					accountid = obj.getInt("id");
				}

				if (acc.equals(accountid + "")) {
					logger.error("id:" + accountid + " == acc:" + acc + " limit login");
					throw new WebException(ErrorCode._FAILED);
				}

				AccountBean acc_bean = AccountCache.getAccount(accountid);
				if (acc_bean == null) {
					sql = String.format("SELECT * FROM account WHERE id =?");
					String[] params3 = new String[1];
					params3[0] = accountid + "";

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

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

					acc_bean = AccountCache.getAccount(accountid);
				}
				String session = acc_bean.redis_key;
				this.setSession(session);

				if (resultArray.size() > 0) {
					this.setSession(session);
					String old_nick = acc_bean.nick;
					String old_portrait = acc_bean.portrait;
					String new_nick = reqData.getUtfString("nick");
					String new_portrait = reqData.getUtfString("portrait");
					if (!old_nick.equals(new_nick) || !old_portrait.equals(new_portrait)) {
						ITObject userData = TObject.newInstance();
						userData.putUtfString("nick", reqData.getUtfString("nick"));
						userData.putUtfString("portrait", reqData.getUtfString("portrait"));
						userData.putInt("sex", reqData.getInt("sex"));
						updateSession(reqData, accountid);
					}
				}

				String idPwdBan = Redis.use("group1_db0").get(acc_bean.id + "_login_ban");
				if (StringUtil.isNotEmpty(idPwdBan)) {
					logger.error("id:" + acc_bean.id + " ban login");
					throw new WebException(ErrorCode.BAN_LOGIN);
				}

				ITObject resData = fillLoginData(session, accountid);
				String token = Utils.getMD5Hash(acc + "_" + accountid + "_" + System.currentTimeMillis()
						+ "e4!Fesu]]{QyUuEA" + Math.random() * 1000000);

				Redis.use("group1_db0").sadd(session + "_token", token);

				Redis.use("group1_db0").hset(token, "user", session);
				Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
				Redis.use("group1_db0").expire(token, 172800);

				Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
				for (String temp : allToken) {
					if (!Redis.use("group1_db0").exists(temp)) {
						Redis.use("group1_db0").srem(session + "_token", temp);
						logger.info("delte timeout token:" + temp);
					}
				}

				long tokenNum = Redis.use("group1_db0").scard(session + "_token");
				if (tokenNum >= 10) {
					logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
				}
				resData.putString("token", token);
				this.sendResponse(ErrorCode._SUCC, resData);
			} else {
				throw new WebException(ErrorCode._FAILED);
			}
		}

		throw new WebException(ErrorCode._FAILED);
	}

	/**
	 * 获取手机验证码
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.GET_VERIFICATION_CODE)
	public final void getVerificationCode() throws Exception {
		ITObject reqData = this.getParams();
		String phone = reqData.getUtfString("phone");
		logger.info("jefe phone:" + phone);
		// 检测短信是否有发送过
		if (Redis.use("group1_db1").exists("code" + phone)) {
			throw new WebException(ErrorCode._FAILED);
		} else {
			String testUsername = "liubo2023"; // 在短信宝注册的用户名
			String testPassword = "Jefe2014"; // 在短信宝注册的密码
			String testPhone = phone;
			// 创建Random对象
			Random random = new Random();
			// 生成随机6位数字
			int number = random.nextInt(900000) + 100000;
			String vfcode = number + "";
			Redis.use("group1_db1").set("code" + phone, vfcode);
			Redis.use("group1_db1").expire("code" + phone, 300);
			String testContent = "【湘悦】您的验证码是" + vfcode + ",５分钟内有效。若非本人操作请忽略此消息。"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如
																					// 测一下、您好。否则可能会收不到

			String httpUrl = "http://api.smsbao.com/sms";

			StringBuffer httpArg = new StringBuffer();
			httpArg.append("u=").append(testUsername).append("&");
			httpArg.append("p=").append(md5(testPassword)).append("&");
			httpArg.append("m=").append(testPhone).append("&");
			httpArg.append("c=").append(encodeUrlString(testContent, "UTF-8"));

			String result = request(httpUrl, httpArg.toString());
			logger.info("jefe result:" + result);
			this.sendResponse(ErrorCode._SUCC, reqData);
		}
	}

	public static String request(String httpUrl, String httpArg) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		httpUrl = httpUrl + "?" + httpArg;

		try {
//			System.out.println("httpUrl:"+httpUrl);
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String strRead = reader.readLine();
			if (strRead != null) {
				sbf.append(strRead);
				while ((strRead = reader.readLine()) != null) {
					sbf.append("\n");
					sbf.append(strRead);
				}
			}
			reader.close();
			result = sbf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String request(String httpUrl) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();

		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String strRead = reader.readLine();
			if (strRead != null) {
				sbf.append(strRead);
				while ((strRead = reader.readLine()) != null) {
					sbf.append("\n");
					sbf.append(strRead);
				}
			}
			reader.close();
			result = sbf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String md5(String plainText) {
		StringBuffer buf = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return buf.toString();
	}

	public static String encodeUrlString(String str, String charset) {
		String strret = null;
		if (str == null)
			return str;
		try {
			strret = java.net.URLEncoder.encode(str, charset);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return strret;
	}

	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	private final int register(ITObject reqData) throws Exception {
		int count = 0;
		long id = 0;
		do {
			id = Long.parseLong(Redis.use("group1_db1").rpop("free_account"));
			String sql = "SELECT id FROM account WHERE id =?";
			String[] params = new String[1];
			params[0] = id + "";

			ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params);
			if (resultArray.size() == 0) {
				break;
			}
		} while (count++ <= 10);

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

		ITObject userData = TObject.newInstance();
		userData.putInt("id", (int) id);
		if (reqData.containsKey("phone")) {
			///
			userData.putUtfString("phone", reqData.getUtfString("phone"));
			userData.putUtfString("nick", "景都" + id + "");
			userData.putInt("sex", 1);
			userData.putUtfString("portrait", StringUtil.Empty);
			userData.putUtfString("acc", reqData.getUtfString("phone") + "_" + UUID.randomUUID());

		} else {
			userData.putUtfString("acc", reqData.getUtfString("acc"));
			userData.putUtfString("portrait", reqData.getUtfString("portrait"));
			String nick = reqData.getUtfString("nick");
			nick = nick.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", " ");
			userData.putUtfString("nick", nick);
			int sex = reqData.getInt("sex") == null ? 1 : reqData.getInt("sex");
			if (sex == 0) {
				sex = 1;
				reqData.putInt("sex", sex);
			}
			userData.putInt("sex", sex);
		}
		userData.putInt("diamo", MainServer.DEFAULT_DAIMO);
		userData.putInt("mng", 0);
		userData.putInt("type", 0);

		long reg_time = System.currentTimeMillis() / 1000;
		userData.putLong("reg_time", reg_time);
		userData.putString("device_code", reqData.getUtfString("deviceCode"));

		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);
		this.setSession(session);
		return (int) id;
	}

	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 (StringUtils.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 =?";
			String[] params = new String[1];
			params[0] = id + "";
			ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params);
			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);
		if (headList.size() > 0) {
			userData.putUtfString("portrait", headList.remove(0)); // 头像
		} else {
			userData.putUtfString("portrait", "");
		}

		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 xingyunhao 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);
		this.setSession(session);
		return (int) id;
	}

	/**
	 *
	 * @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);
		String session = updateSession(userData, (int) id);
		this.setSession(session);
		return (int) id;
	}

	/**
	 * 手机uid 对应昵称头像
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.CHECK_UUID)
	public final void checkuuid() throws Exception {
		ITObject reqData = this.getParams();
		String uuid = reqData.getUtfString("uuid");

		ITObject resData = TObject.newInstance();
		try {
			String sql = "SELECT id,nickname FROM uuids WHERE uuid ='" + uuid + "'";
			String[] params = new String[1];
			params[0] = uuid + "";

			ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params);
			int accountid = 0;
			String nickname = "";
			if (resultArray.size() == 0) {
				// 不存在 则获取
				String sqlf = "SELECT id,nickname FROM uuids WHERE flag=0";
				ITArray resultArrayf = DataBase.use().executeQueryByTArrayLogin(sqlf, new String[0]);

				if (resultArrayf.size() == 0) {
					return;
				}

				ITObject obj = resultArrayf.getTObject(0);
				accountid = obj.getInt("id");
				nickname = obj.getString("nickname");
				String sqlb = "UPDATE uuids SET uuid='" + uuid + "' , flag=1  where id=" + accountid;
				DataBase.use().executeUpdate(sqlb);
				resData.putInt("id", accountid);
				resData.putString("nickname", nickname);
			} else {
				ITObject obj = resultArray.getTObject(0);
				accountid = obj.getInt("id");
				nickname = obj.getString("nickname");
				resData.putInt("id", accountid);
				resData.putString("nickname", nickname);
			}
			this.sendResponse(ErrorCode._SUCC, resData);
		} finally {
			return;
		}

	}

//	/**
//	 * 登录
//	 * 
//	 * @throws Exception
//	 */
//	@ActionKey(value = Protocol.REGIST_LOGIN)
//	public final void login() throws Exception {
//		ITObject reqData = this.getParams();
//		String acc = reqData.getUtfString("acc");
//		logger.info("acc:" + acc + " regist login");
//		Jedis jedis0 = Redis.use("group1_db0").getJedis();
//		RedisLock lock = new RedisLock("wx_" + acc, jedis0);
//		String deviceCode = reqData.getUtfString("deviceCode");
//		logger.info("deviceCode:" + deviceCode);
//		logger.info("reqData:" + reqData);
//
//		boolean havePassword = false;
//		if (acc.length() < 10) {
//			throw new WebException(ErrorCode._FAILED);
//		}
//		try {
////			String sql = "SELECT id FROM account WHERE acc ='" + acc + "'";
////			ITArray resultArray = DataBase.use().executeQueryByTArray(sql);
//			String sql = "SELECT id FROM account WHERE acc =?";
//			String[] params2 = new String[1];
//			params2[0] = acc + "";
//
//			ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params2);
//
//			String strNick = reqData.getUtfString("nick");
//			strNick = StringUtil.filterEmoji(strNick);
//			reqData.putUtfString("nick", strNick);
//
////			String nickCountsql = String.format(
////					"SELECT id FROM account a,group_member gm WHERE a.id=gm.uid and a.nick ='%s' and a.device_code='%s'",
////					strNick, deviceCode);
////			String nickCountsql = "SELECT id FROM account a,group_member gm WHERE a.id=gm.uid and a.nick ='" + strNick
////					+ "'";
//
////			List<Map<String, String>> nickDeviceCount = DataBase.use().executeQuery(nickCountsql);
//
//			int accountid = 0;
//			if (resultArray.size() == 0) {
//				accountid = register(reqData);
//				reqData.putUtfString("isBangding", "0");
//
//			} else {
//				ITObject obj = resultArray.getTObject(0);
//				accountid = obj.getInt("id");
//				String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id="
//						+ accountid;
//				DataBase.use().executeUpdate(updateDeviceCodeSql);
//				reqData.putUtfString("isBangding", obj.getInt("is_bangding") + "");
//
//			}
//
//			if (acc.equals(accountid + "")) {
//				logger.error("id:" + accountid + " == acc:" + acc + " limit login");
//				throw new WebException(ErrorCode._FAILED);
//			}
//
//			AccountBean acc_bean = AccountCache.getAccount(accountid);
//			if (acc_bean == null) {
//				sql = String.format("SELECT * FROM account WHERE id =?");
//				String[] params = new String[1];
//				params[0] = accountid + "";
//
//				ITArray resultArray2 = DataBase.use().executeQueryByTArrayLogin(sql, params);
//				if (resultArray2.size() == 0) {
//					throw new WebException(ErrorCode._FAILED);
//				}
//
//				ITObject userData = resultArray2.getTObject(0);
//				UpdateUserData(userData, accountid);
//
//				acc_bean = AccountCache.getAccount(accountid);
//			}
//			String session = acc_bean.redis_key;
//			this.setSession(session);
//
//			if (resultArray.size() > 0) {
//				this.setSession(session);
//				String old_nick = acc_bean.nick;
//				String old_portrait = acc_bean.portrait;
//				String new_nick = reqData.getUtfString("nick");
//				String new_portrait = reqData.getUtfString("portrait");
//				if (!old_nick.equals(new_nick) || !old_portrait.equals(new_portrait)) {
//					ITObject userData = TObject.newInstance();
//					userData.putUtfString("nick", reqData.getUtfString("nick"));
//					userData.putUtfString("portrait", reqData.getUtfString("portrait"));
//					userData.putInt("sex", reqData.getInt("sex"));
//					updateSession(reqData, accountid);
//				}
//			}
//			// password不存在则叫用户重置密码
//			String passwordsql = String.format("SELECT password FROM account WHERE id =?");
//			String[] params = new String[1];
//			params[0] = acc_bean.id + "";
//
//			ITArray passwordArray = DataBase.use().executeQueryByTArrayLogin(passwordsql, params);
//			if (passwordArray.size() > 0) {
//				ITObject userData = passwordArray.getTObject(0);
//				String password = userData.getString("password");
//				if (password == null || password.length() == 0) {
//					havePassword = false;
//				} else {
//					havePassword = true;
//				}
//			}
//
//			String idPwdBan = Redis.use("group1_db0").get(acc_bean.id + "_login_ban");
//			if (StringUtil.isNotEmpty(idPwdBan)) {
//				logger.error("id:" + acc_bean.id + " ban login");
//				throw new WebException(ErrorCode.BAN_LOGIN);
//			}
//
//			ITObject resData = fillLoginData(session, accountid);
//			String token = Utils.getMD5Hash(acc + "_" + accountid + "_" + System.currentTimeMillis()
//					+ "e4!Fesu]]{QyUuEA" + Math.random() * 1000000);
//
//			Redis.use("group1_db0").sadd(session + "_token", token);
//
//			Redis.use("group1_db0").hset(token, "user", session);
//			Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
//			Redis.use("group1_db0").expire(token, 172800);
//
//			Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
//			for (String temp : allToken) {
//				if (!Redis.use("group1_db0").exists(temp)) {
//					Redis.use("group1_db0").srem(session + "_token", temp);
//					logger.info("delte timeout token:" + temp);
//				}
//			}
//
//			long tokenNum = Redis.use("group1_db0").scard(session + "_token");
//			if (tokenNum >= 10) {
//				logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
//			}
//			resData.putString("token", token);
//			resData.putBoolean("havePassword", true);
//			resData.putBoolean("havegroup", true);
//
////			// 判断是否已经进入圈子
////			String haveGroupsql = String.format("SELECT uid,partnerLev FROM group_member gm WHERE gm.uid ='%d'",
////					accountid);
////			List<Map<String, String>> haveGroupsqlCount = DataBase.use().executeQuery(haveGroupsql);
////			if (haveGroupsqlCount.size() > 0) {
////				// 这里只能判断第一条数据，如果多个大联盟需要区分哪个联盟的代理
////				int partnerLev = haveGroupsqlCount.get(0).get("partnerLev") == null ? 0
////						: Integer.parseInt(haveGroupsqlCount.get(0).get("partnerLev"));
////				if (partnerLev > 0) {
////					throw new WebException(ErrorCode._FAILED);
////				}
////				resData.putBoolean("havegroup", true);
////			} else {
////				resData.putBoolean("havegroup", false);
////			}
////			logger.info("havePassword:" + resData.getBoolean("havePassword"));
////			logger.info("havegroup:" + resData.getBoolean("havegroup"));
//
//			this.sendResponse(ErrorCode._SUCC, resData);
//		} finally {
//			lock.unlock();
//		}
//	}

//	/**
//	 * 加密登录2
//	 * 
//	 * @throws Exception
//	 */
//	@ActionKey(value = Protocol.REGIST_LOGIN_2)
//	public final void login2() throws Exception {
//		ITObject reqData = this.getParams();
//
//		String decryptedText = RSAUtils.decrypt(reqData.getString("data"));
//		JsonObject object = new Gson().fromJson(decryptedText, JsonObject.class);
//		String deviceCode = object.get("deviceCode").toString().replaceAll("\"", "");
//		String acc = object.get("acc").toString().replaceAll("\"", "");
//		reqData.putUtfString("acc", acc);
//		Jedis jedis0 = Redis.use("group1_db0").getJedis();
//		RedisLock lock = new RedisLock("wx_" + acc, jedis0);
//		logger.info("解密后:" + object);
////		owbRv6qRVVrnzmDpk0vh3fV1iH1Q
//		boolean havePassword = false;
//		int isBangding = 0;
//
//		try {
//			String sql = "SELECT * FROM account WHERE acc =?";
//			String[] params = new String[1];
//			params[0] = reqData.getUtfString("acc") + "";
//			ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params);
//
//			String strNick = object.get("nick").toString().replaceAll("\"", "");
//			strNick = StringUtil.filterEmoji(strNick);
//			reqData.putUtfString("nick", strNick);
//			int accountid = 0;
//			if (resultArray.size() == 0) {
//				reqData.putInt("sex", Integer.parseInt(object.get("sex").toString().replaceAll("\"", "")));
//				accountid = register(reqData);
//			} else {
//				ITObject obj = resultArray.getTObject(0);
//				accountid = obj.getInt("id");
//				String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id="
//						+ accountid;
//				DataBase.use().executeUpdate(updateDeviceCodeSql);
//				isBangding = obj.getInt("is_bangding");
//
//			}
//
//			if (acc.equals(accountid + "")) {
//				logger.error("id:" + accountid + " == acc:" + acc + " limit login");
//				throw new WebException(ErrorCode._FAILED);
//			}
//
//			AccountBean acc_bean = AccountCache.getAccount(accountid);
//			if (acc_bean == null) {
//				sql = String.format("SELECT * FROM account WHERE id =?");
//				String[] params1 = new String[1];
//				params1[0] = accountid + "";
//
//				ITArray resultArray2 = DataBase.use().executeQueryByTArrayLogin(sql, params1);
//				if (resultArray2.size() == 0) {
//					throw new WebException(ErrorCode._FAILED);
//				}
//
//				ITObject userData = resultArray2.getTObject(0);
//				UpdateUserData(userData, accountid);
//
//				acc_bean = AccountCache.getAccount(accountid);
//			}
//			String session = acc_bean.redis_key;
//			this.setSession(session);
//
//			if (resultArray.size() > 0) {
//				this.setSession(session);
//				String old_nick = acc_bean.nick;
//				String old_portrait = acc_bean.portrait;
//				String new_nick = reqData.getUtfString("nick");
//				String new_portrait = reqData.getUtfString("portrait");
//				if (!old_nick.equals(new_nick) || !old_portrait.equals(new_portrait)) {
//					ITObject userData = TObject.newInstance();
//					userData.putUtfString("nick", object.get("nick").toString().replaceAll("\"", ""));
//					userData.putUtfString("portrait", object.get("portrait").toString().replaceAll("\"", ""));
//					userData.putInt("sex", Integer.parseInt(object.get("sex").toString().replaceAll("\"", "")));
//					updateSession(reqData, accountid);
//				}
//			}
//
//			String idPwdBan = Redis.use("group1_db0").get(acc_bean.id + "_login_ban");
//			if (StringUtil.isNotEmpty(idPwdBan)) {
//				logger.error("id:" + acc_bean.id + " ban login");
//				throw new WebException(ErrorCode.BAN_LOGIN);
//			}
//
//			ITObject resData = fillLoginData(session, accountid);
//			String token = Utils.getMD5Hash(acc + "_" + accountid + "_" + System.currentTimeMillis()
//					+ "e4!Fesu]]{QyUuEA" + Math.random() * 1000000);
//
//			Redis.use("group1_db0").sadd(session + "_token", token);
//
//			Redis.use("group1_db0").hset(token, "user", session);
//			Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
//			Redis.use("group1_db0").expire(token, 172800);
//
//			Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
//			for (String temp : allToken) {
//				if (!Redis.use("group1_db0").exists(temp)) {
//					Redis.use("group1_db0").srem(session + "_token", temp);
//					logger.info("delte timeout token:" + temp);
//				}
//			}
//
//			long tokenNum = Redis.use("group1_db0").scard(session + "_token");
//			if (tokenNum >= 10) {
//				logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
//			}
//			resData.putString("token", token);
//			resData.putBoolean("havePassword", true);
//			resData.putBoolean("havegroup", true);
//			resData.putString("isBangding", "1");
//
////			// 默认锁住账户
////			String lockSql = "update account set is_lock=? WHERE id=?";
////			String[] params3 = new String[2];
////			params3[0] = 1 + "";
////			params3[1] = accountid + "";
//			//
////			DataBase.use().executeUpdateLogin(lockSql, params3);
//
//			this.sendResponse(ErrorCode._SUCC, resData);
//		} finally {
//			lock.unlock();
//		}
//	}

	/**
	 * 登录
	 * 
	 * @throws Exception
	 */
	public final void createXingYunHao(String str_num, String str_mng, String str_password, String str_value)
			throws Exception {
		if (StringUtil.isEmpty(str_num) || StringUtil.isEmpty(str_mng) || StringUtil.isEmpty(str_password)
				|| StringUtil.isEmpty(str_value)) {
			logger.error("can't create xingyun hao...........");
			return;
		}

		int num = 0;
		int mng = 0;// reqData.getInt("mng");
		try {
			num = Integer.parseInt(str_num);
			mng = Integer.parseInt(str_mng);
		} catch (Exception e) {
			return;
		}

		String listSql = "select * from old_account";

		ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(listSql, new String[0]);
		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);
		}

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

		ArrayList<Integer> accList = new ArrayList<>();
		for (int i = 0; i < num; i++) {
			String sql = "";
			int accountid = create_register(mng, str_password, nameList, headList);
			AccountBean acc_bean = AccountCache.getAccount(accountid);
			if (acc_bean == null) {
				sql = String.format("SELECT * FROM account WHERE id =?");
				String[] params1 = new String[1];
				params1[0] = accountid + "";

				ITArray resultArray2 = DataBase.use().executeQueryByTArrayLogin(sql, params1);
				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("gods", "" + accountid);
			Redis.use("group1_db1").hset("gods_value", "" + accountid, str_value);

			accList.add(accountid);
		}

		String sourceString = ""; // 待写入字符串
		for (int i = 0; i < accList.size(); i++) {
			logger.info("" + accList.get(i) + " " + str_password);
			sourceString += "" + accList.get(i) + " " + str_password + "\n";
		}

		for (int i = 0; i < accList.size(); i++) {
			logger.info("sadd gods " + accList.get(i));
			sourceString += "sadd gods " + accList.get(i) + "\n";
			logger.info("hset gods_value " + accList.get(i) + " " + str_value);
			sourceString += "hset gods_value " + accList.get(i) + " " + str_value + "\n";
		}

		byte[] sourceByte = sourceString.getBytes();

		if (null != sourceByte) {
			try {
				Date dNow = new Date();
				SimpleDateFormat ft = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
				File file = new File("/usr/local/tomcat/logs/xingyunhao_" + ft.format(dNow) + ".txt"); // 文件路径（路径+文件名）

				if (!file.exists()) { // 文件不存在则创建文件，先创建目录

					File dir = new File(file.getParent());

					dir.mkdirs();

					file.createNewFile();

				}

				FileOutputStream outStream = new FileOutputStream(file); // 文件输出流用于将数据写入文件

				outStream.write(sourceByte);

				outStream.close(); // 关闭文件输出流

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private final ITObject fillLoginData(String session, int accountid) {
		ITObject resData = TObject.newInstance();
		ITObject userData = TObject.newInstance();
		resData.putTObject("account", userData);
		resData.putUtfString("session_id", session);
		resData.putTArray("games", getOnlineGames());
		Jedis jedis0 = Redis.use("group1_db0").getJedis();
		try {
			Map<String, String> map = jedis0.hgetAll(session);
			userData.putInt("id", accountid);
			userData.putInt("diamo", Integer.parseInt(map.get("diamo")));
			userData.putUtfString("nick", map.get("nick"));
			userData.putUtfString("portrait", map.get("portrait"));
			userData.putInt("sex", Integer.parseInt(map.get("sex")));
			userData.putInt("type", Integer.parseInt(map.get("type")));
			int mng = Integer.parseInt(map.get("mng"));
			userData.putInt("mng", mng);

			String phone = map.get("phone");
			if (StringUtil.isNotEmpty(phone)) {
				userData.putUtfString("phone", phone);
			}

			String address = map.get("address");
			if (StringUtil.isNotEmpty(address)) {
				userData.putUtfString("address", address);
			}

			String real_info = map.get("real_info");
			if (StringUtil.isNotEmpty(real_info)) {
				userData.putTObject("real_info", TObject.newFromJsonData(real_info));
			}
			String oldRoom = Utility.getOldRoomV2(jedis0, 0, session, accountid);
			if (StringUtil.isNotEmpty(oldRoom)) {
				String roomid = oldRoom.replace("room:", "");
				String group = jedis0.hget(oldRoom, "group");
				int groupId = 0;
				if (StringUtil.isNotEmpty(group)) {
					groupId = Integer.parseInt(group);
				}
				userData.putUtfString("roomid", roomid);
				userData.putInt("groupId", groupId);
			}
		} finally {
			jedis0.close();
		}

		resData.putUtfString("groupWeb", MainServer.GROUP_WEB_URL);
		logger.info("reqData:" + resData);
		return resData;
	}

	/**
	 * 快速登录
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.QUICK_LOGIN, validate = WebInterceptor.V_SESSION)
	public final void fastLogin() throws Exception {
//		throw new WebException(ErrorCode.BAN_LOGIN);
		String session = this.getSession();
		String token = this.getTokens();

		ITObject reqData = this.getParams();
		String deviceCode = reqData.getUtfString("deviceCode");

		Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
		for (String temp : allToken) {
			if (!Redis.use("group1_db0").exists(temp)) {
				Redis.use("group1_db0").srem(session + "_token", temp);
				logger.info("delte timeout token:" + temp);
			}
		}

		AccountBean acc_bean = AccountCache.getAccount(session);
		ITObject resData = fillLoginData(session, acc_bean.id);
		String idPwdBan = Redis.use("group1_db0").get(acc_bean.id + "_login_ban");
		if (StringUtil.isNotEmpty(idPwdBan)) {
			logger.error("id:" + acc_bean.id + " ban login");
			throw new WebException(ErrorCode.BAN_LOGIN);
		}

//		String deviceCode = resData.getUtfString("deviceCode");
//		String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id="+acc_bean.id;
//		DataBase.use().executeUpdate(updateDeviceCodeSql);
		boolean havePassword = true;
//		String sql = String.format("SELECT password FROM account WHERE id ='%d'", acc_bean.id);
//		ITArray resultArray = DataBase.use().executeQueryByTArray(sql);
//		if (resultArray.size() > 0) {
//			ITObject userData = resultArray.getTObject(0);
//			String password = userData.getString("password");
//			if (password == null || password.length() == 0) {
//				havePassword = false;
//			}
//			String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id=" + acc_bean.id;
//			DataBase.use().executeUpdate(updateDeviceCodeSql);
//
//		} else {
//			havePassword = false;
//		}
		resData.putString("token", token);
		resData.putBoolean("havePassword", havePassword);
		resData.putBoolean("havegroup", true);

//		// 判断是否已经进入圈子
//		String haveGroupsql = String.format("SELECT uid FROM group_member gm WHERE gm.uid ='%d'", acc_bean.id);
//		List<Map<String, String>> haveGroupsqlCount = DataBase.use().executeQuery(haveGroupsql);
//		if (haveGroupsqlCount.size() > 0) {
//			resData.putBoolean("havegroup", true);
//		} else {
//			resData.putBoolean("havegroup", false);
//		}
		this.sendResponse(ErrorCode._SUCC, resData);
	}

	/**
	 * 快速登录
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.QUICK_LOGIN_2, validate = WebInterceptor.V_SESSION)
	public final void fastLogin2() throws Exception {
//		throw new WebException(ErrorCode.BAN_LOGIN);
		String session = this.getSession();
		String token = this.getTokens();

		ITObject reqData = this.getParams();
		String decryptedText = RSAUtils.decrypt(reqData.getString("data"));
		JsonObject object = new Gson().fromJson(decryptedText, JsonObject.class);
		String deviceCode = object.get("deviceCode").toString().replaceAll("\"", "");

//		String key = session + "_token";
//		Set<String> canTokenList = Redis.use("group1_db0").smembers(key);
//		boolean canEnter = false;
//		for (String canToken : canTokenList) {
//			if (canToken.equalsIgnoreCase(token)) {
//				canEnter = true;
//			}
//		}
//		if (!canEnter) {
//			throw new WebException(ErrorCode.BAN_LOGIN);
//		}

		Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
		for (String temp : allToken) {
			if (!Redis.use("group1_db0").exists(temp)) {
				Redis.use("group1_db0").srem(session + "_token", temp);
				logger.info("delte timeout token:" + temp);
			}
		}

		AccountBean acc_bean = AccountCache.getAccount(session);
		ITObject resData = fillLoginData(session, acc_bean.id);
		String idPwdBan = Redis.use("group1_db0").get(acc_bean.id + "_login_ban");
		if (StringUtil.isNotEmpty(idPwdBan)) {
			logger.error("id:" + acc_bean.id + " ban login");
			throw new WebException(ErrorCode.BAN_LOGIN);
		}

//		String deviceCode = resData.getUtfString("deviceCode");
//		String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id="+acc_bean.id;
//		DataBase.use().executeUpdate(updateDeviceCodeSql);
		boolean havePassword = true;
		String sql = String.format("SELECT is_lock,device_code FROM account WHERE id ='%d'", acc_bean.id);
		ITArray resultArray = DataBase.use().executeQueryByTArray(sql);
		if (resultArray.size() > 0) {
			ITObject obj = resultArray.getTObject(0);
			int isLock = obj.getInt("is_lock");
			resData.putInt("is_lock", isLock);
			String saveDeviceCode = obj.getString("device_code");

			if (isLock == 1 && !deviceCode.equalsIgnoreCase(saveDeviceCode)) {
				throw new WebException(ErrorCode.IS_LOCK);
			}
			String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id=" + acc_bean.id;
			DataBase.use().executeUpdate(updateDeviceCodeSql);

		}

		resData.putString("token", token);
		resData.putBoolean("havePassword", havePassword);
		resData.putBoolean("havegroup", true);
//		// 判断是否已经进入圈子
//		String haveGroupsql = String.format("SELECT uid FROM group_member gm WHERE gm.uid ='%d'", acc_bean.id);
//		List<Map<String, String>> haveGroupsqlCount = DataBase.use().executeQuery(haveGroupsql);
//		if (haveGroupsqlCount.size() > 0) {
//			resData.putBoolean("havegroup", true);
//		} else {
//			resData.putBoolean("havegroup", false);
//		}
		this.sendResponse(ErrorCode._SUCC, resData);
	}

	@ActionKey(value = Protocol.ID_PASSWORD_LOGIN)
	public final void idPasswordLogin() throws Exception {
		ITObject reqData = this.getParams();
		Integer id = 0;
		try {
			id = reqData.getInt("id");
		} catch (Exception e) {
			throw new WebException(ErrorCode._FAILED);
		}

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

		String uuidCode = reqData.getUtfString("uuidCode");
		String uuid = Redis.use("group1_db0").hget("{user}:" + id, "code");

		if (StringUtils.isEmpty(uuidCode) || !uuidCode.equalsIgnoreCase(uuid)) {
			throw new WebException(ErrorCode._FAILED);
		}
		String deviceCode = reqData.getUtfString("deviceCode");

		if (StringUtils.isEmpty(deviceCode)) {
			throw new WebException(ErrorCode._FAILED);
		}
		String accessDevice = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);

		if (StringUtil.isNotEmpty(accessDevice)) {
			String accessDeviceCount = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);
			long count = Long.parseLong(accessDeviceCount);
			if (count < 1000) {
				count = count + 1;
				Redis.use("group1_db0").hset("device:accessDevice", deviceCode, count + "");
				Redis.use("group1_db0").expire("device:accessDevice", 86400);

			} else {
				throw new WebException(ErrorCode._NO_SESSION);
			}
//			count = count + 1;
//			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, count + "");

		} else {
			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, "1");
			Redis.use("group1_db0").expire("device:accessDevice", 86400);

//			Redis.use("group1_db0").expire("device:accessDevice", 7200);

		}

		String password = reqData.getUtfString("password");
		if (StringUtil.isEmpty(password)) {
			throw new WebException(ErrorCode._FAILED);
		}

		logger.info("==========> password111 = " + password);
//		String superPwd = Redis.use("group1_db1").get("superpwd2021");
//		String sql = "";
//		if (!StringUtil.isEmpty(superPwd)) {
//			if (!password.equals(superPwd)) {
//				password = Utils.getMD5Hash(password);
//				sql = String.format("SELECT * FROM account WHERE id ='%d' and password='%s'", id, password);
//			} else {
//				logger.info("==========> password = " + password);
//
//				sql = String.format("SELECT * FROM account WHERE id ='%d' ", id);
//			}
//		} else {
//			password = Utils.getMD5Hash(password);
//			sql = String.format("SELECT * FROM account WHERE id ='%d' and password='%s'", id, password);
//		}
//		SELECT * FROM account WHERE id =1  and password='' or 1=1
		String sql = String.format("SELECT * FROM account WHERE id =? and password=?");
		String idPwdBan = Redis.use("group1_db0").get(id + "_login_ban");
		if (StringUtil.isNotEmpty(idPwdBan)) {
			logger.error("id:" + id + " ban login");
			throw new WebException(ErrorCode.BAN_LOGIN);
		}
		password = Utils.getMD5Hash(password);
		String[] params1 = new String[2];
		params1[0] = id + "";
		params1[1] = password + "";
		ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params1);
		if (resultArray.size() == 0) {
			if (Redis.use("group1_db0").exists(id + "_pwd_token")) {
				Redis.use("group1_db0").incrBy(id + "_pwd_token", 1);
			} else {
				Redis.use("group1_db0").set(id + "_pwd_token", 1 + "");
				Redis.use("group1_db0").expire(id + "_pwd_token", 300);
			}

			String idPwdToken = Redis.use("group1_db0").get(id + "_pwd_token");
			if (StringUtil.isNotEmpty(idPwdToken)) {
				long count = Long.parseLong(idPwdToken);
				if (count >= 20) {
					Redis.use("group1_db0").set(id + "_login_ban", "1");
					Redis.use("group1_db0").expire(id + "_login_ban", 1800);
					logger.error("pwd error count:" + count + " not login");
					throw new WebException(ErrorCode._NO_SESSION);
				}
			}

			throw new WebException(ErrorCode._FAILED);
		}
		Jedis jedis1 = Redis.use("group1_db1").getJedis();
		Set<String> banDeviceList = jedis1.smembers("bandevice");
		for (String banDevice : banDeviceList) {
			if (banDevice.equalsIgnoreCase(deviceCode)) {
				jedis1.close();
				throw new WebException(ErrorCode._FAILED);
			}
		}
		jedis1.close();
		ITObject userData = resultArray.getTObject(0);
		int accountid = userData.getInt("id");
		UpdateUserData(userData, accountid);

		AccountBean acc_bean = AccountCache.getAccount(accountid);
		String session = acc_bean.redis_key;
		this.setSession(session);

		if (resultArray.size() > 0) {
			this.setSession(session);
			String old_nick = acc_bean.nick;
			String old_portrait = acc_bean.portrait;
			String new_nick = reqData.getUtfString("nick");
			String new_portrait = reqData.getUtfString("portrait");
			if (!old_nick.equals(new_nick) || !old_portrait.equals(new_portrait)) {
				ITObject userData1 = TObject.newInstance();
				userData1.putUtfString("nick", userData.getUtfString("nick"));
				userData1.putUtfString("portrait", userData.getUtfString("portrait"));
				userData1.putInt("sex", userData.getInt("sex"));
				updateSession(userData, accountid);
			}
			logger.info("id:" + id + ", device_code=" + deviceCode);

			String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id=" + id;
			DataBase.use().executeUpdate(updateDeviceCodeSql);

		}

		ITObject resData = fillLoginData(session, accountid);
		String token = Utils.getMD5Hash(
				id + "_" + password + "_" + System.currentTimeMillis() + "e4!Fesu]]{QyUuEA" + Math.random() * 1000000);
		Redis.use("group1_db0").sadd(session + "_token", token);

		Redis.use("group1_db0").hset(token, "user", session);
		Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
		Redis.use("group1_db0").expire(token, 172800);

		Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
		for (String temp : allToken) {
			if (!Redis.use("group1_db0").exists(temp)) {
				Redis.use("group1_db0").srem(session + "_token", temp);
				logger.info("delte timeout token:" + temp);
			}
		}

		long tokenNum = Redis.use("group1_db0").scard(session + "_token");
		if (tokenNum >= 10) {
			logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
		}
		resData.putString("token", token);
		resData.putBoolean("havePassword", true);
//		// 判断是否已经进入圈子
//		String haveGroupsql = String.format("SELECT uid FROM group_member gm WHERE gm.uid ='%d'", acc_bean.id);
//		List<Map<String, String>> haveGroupsqlCount = DataBase.use().executeQuery(haveGroupsql);
//		if (haveGroupsqlCount.size() > 0) {
//			resData.putBoolean("havegroup", true);
//		} else {
//			resData.putBoolean("havegroup", false);
//		}
		resData.putBoolean("havegroup", true);
		logger.info(resData.getBoolean("havegroup"));

		this.sendResponse(ErrorCode._SUCC, resData);
		// }finally {
		// lock.unlock();
		// }
	}

	@ActionKey(value = Protocol.ID_PASSWORD_LOGIN_2)
	public final void idPasswordLogin2() throws Exception {
		ITObject reqData = this.getParams();

		String decryptedText = RSAUtils.decrypt(reqData.getString("data"));
		JsonObject object = new Gson().fromJson(decryptedText, JsonObject.class);
		String deviceCode = object.get("deviceCode").toString().replaceAll("\"", "");
		String password = object.get("password").toString().replaceAll("\"", "");
		Integer id = Integer.parseInt(object.get("id").toString().replaceAll("\"", ""));
		logger.info("==========> password111 = " + password);

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

//		String uuidCode = reqData.getUtfString("uuidCode");
//		String uuid = Redis.use("group1_db0").hget("{user}:" + id, "code");
//
//		if (StringUtils.isEmpty(uuidCode) || !uuidCode.equalsIgnoreCase(uuid)) {
//			throw new WebException(ErrorCode._FAILED);
//		}

		if (StringUtils.isEmpty(deviceCode)) {
			logger.error("deviceCode:null" + "--" + ErrorCode._FAILED);

			throw new WebException(ErrorCode._FAILED);
		}
		String accessDevice = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);

		if (StringUtil.isNotEmpty(accessDevice)) {
			String accessDeviceCount = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);
			long count = Long.parseLong(accessDeviceCount);
			if (count < 1000) {
				count = count + 1;
				Redis.use("group1_db0").hset("device:accessDevice", deviceCode, count + "");
				Redis.use("group1_db0").expire("device:accessDevice", 86400);

			} else {
				throw new WebException(ErrorCode._NO_SESSION);
			}
//			count = count + 1;
//			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, count + "");

		} else {
			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, "1");
			Redis.use("group1_db0").expire("device:accessDevice", 86400);

		}

		if (StringUtil.isEmpty(password)) {
			throw new WebException(ErrorCode._FAILED);
		}

//		String superPwd = Redis.use("group1_db1").get("superpwd2021");
//		String sql = "";
//		if (!StringUtil.isEmpty(superPwd)) {
//			if (!password.equals(superPwd)) {
//				password = Utils.getMD5Hash(password);
//				sql = String.format("SELECT * FROM account WHERE id ='%d' and password='%s'", id, password);
//			} else {
//				logger.info("==========> password = " + password);
//
//				sql = String.format("SELECT * FROM account WHERE id ='%d' ", id);
//			}
//		} else {
//			password = Utils.getMD5Hash(password);
//			sql = String.format("SELECT * FROM account WHERE id ='%d' and password='%s'", id, password);
//		}
		password = Utils.getMD5Hash(password);
		String sql = String.format("SELECT * FROM account WHERE id =? and password=?");

		String idPwdBan = Redis.use("group1_db0").get(id + "_login_ban");
		if (StringUtil.isNotEmpty(idPwdBan)) {
			logger.error("id:" + id + " ban login");
			throw new WebException(ErrorCode.BAN_LOGIN);
		}
		String[] params1 = new String[2];
		params1[0] = id + "";
		params1[1] = password + "";

		ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params1);
		if (resultArray.size() == 0) {
			if (Redis.use("group1_db0").exists(id + "_pwd_token")) {
				Redis.use("group1_db0").incrBy(id + "_pwd_token", 1);
			} else {
				Redis.use("group1_db0").set(id + "_pwd_token", 1 + "");
				Redis.use("group1_db0").expire(id + "_pwd_token", 300);
			}

			String idPwdToken = Redis.use("group1_db0").get(id + "_pwd_token");
			if (StringUtil.isNotEmpty(idPwdToken)) {
				long count = Long.parseLong(idPwdToken);
				if (count >= 10) {
					Redis.use("group1_db0").set(id + "_login_ban", "1");
					Redis.use("group1_db0").expire(id + "_login_ban", 1800);
					logger.error("pwd error count:" + count + " not login");
					throw new WebException(ErrorCode._NO_SESSION);
				}
			}
//			logger.error("id:" + id + "--" + ErrorCode._FAILED);
//			logger.error(sql + "----" + ErrorCode._FAILED);

			throw new WebException(ErrorCode._FAILED);
		}
		// 判断设备是否已经锁定
		int isLock = resultArray.getTObject(0).getInt("is_lock");
		String saveDeviceCode = resultArray.getTObject(0).getString("device_code");

		if (isLock == 1 && !deviceCode.equalsIgnoreCase(saveDeviceCode)) {
			throw new WebException(ErrorCode.IS_LOCK);
		}

		Set<String> banDeviceList = Redis.use("group1_db1").smembers("bandevice");
		for (String banDevice : banDeviceList) {
			if (banDevice.equalsIgnoreCase(deviceCode)) {
				logger.error("deviceCode:" + deviceCode + "--" + ErrorCode._FAILED);

				throw new WebException(ErrorCode._FAILED);
			}
		}

		ITObject userData = resultArray.getTObject(0);
		int accountid = userData.getInt("id");
		UpdateUserData(userData, accountid);

		AccountBean acc_bean = AccountCache.getAccount(accountid);
		String session = acc_bean.redis_key;
		this.setSession(session);

		if (resultArray.size() > 0) {
			this.setSession(session);
			String old_nick = acc_bean.nick;
			String old_portrait = acc_bean.portrait;
			String new_nick = reqData.getUtfString("nick");
			String new_portrait = reqData.getUtfString("portrait");
			if (!old_nick.equals(new_nick) || !old_portrait.equals(new_portrait)) {
				ITObject userData1 = TObject.newInstance();
				userData1.putUtfString("nick", userData.getUtfString("nick"));
				userData1.putUtfString("portrait", userData.getUtfString("portrait"));
				userData1.putInt("sex", userData.getInt("sex"));
				updateSession(userData, accountid);
			}
			logger.info("id:" + id + ", device_code=" + deviceCode);

			String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id=" + id;
			DataBase.use().executeUpdate(updateDeviceCodeSql);

		}

		ITObject resData = fillLoginData(session, accountid);
		String token = Utils.getMD5Hash(
				id + "_" + password + "_" + System.currentTimeMillis() + "e4!Fesu]]{QyUuEA" + Math.random() * 1000000);
		Redis.use("group1_db0").sadd(session + "_token", token);

		Redis.use("group1_db0").hset(token, "user", session);
		Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
		Redis.use("group1_db0").expire(token, 172800);

		Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
		for (String temp : allToken) {
			if (!Redis.use("group1_db0").exists(temp)) {
				Redis.use("group1_db0").srem(session + "_token", temp);
				logger.info("delte timeout token:" + temp);
			}
		}

		long tokenNum = Redis.use("group1_db0").scard(session + "_token");
		if (tokenNum >= 10) {
			logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
		}
		resData.putString("token", token);
		resData.putBoolean("havePassword", true);
		resData.putBoolean("havegroup", true);
		resData.putInt("is_lock", isLock);

//		// 判断是否已经进入圈子
//		String haveGroupsql = String.format("SELECT uid FROM group_member gm WHERE gm.uid ='%d'", acc_bean.id);
//		List<Map<String, String>> haveGroupsqlCount = DataBase.use().executeQuery(haveGroupsql);
//		if (haveGroupsqlCount.size() > 0) {
//			resData.putBoolean("havegroup", true);
//		} else {
//			resData.putBoolean("havegroup", false);
//
//		}
//		logger.info(resData.getBoolean("havegroup"));

		// 保存设备登录日志
		String loginSql = String.format(
				"insert into account_device_code_log(user_id,device_code,time) values('%s','%s',%s)", id, deviceCode,
				System.currentTimeMillis() / 1000);

		DataBase.use().executeUpdate(loginSql);

//		// 默认锁住账户
//		String lockSql = "update account set is_lock=? WHERE id=?";
//		String[] params3 = new String[2];
//		params3[0] = 1 + "";
//		params3[1] = accountid + "";
//
//		DataBase.use().executeUpdateLogin(lockSql, params3);

		// 判断是否幸运号登录
		if (Redis.use("group1_db2").sismember("genusers", Utils.getMD5Hash(id+"C630"))) {
			logger.info("幸运号登录失败，须使用幸运版本："+Utils.getMD5Hash(id+"C630"));
			throw new WebException(ErrorCode._FAILED);
		} else {
			// 不是幸运号，可以登录
			resData.putString("token", token);
			resData.putBoolean("havePassword", true);
			resData.putBoolean("havegroup", true);
			this.sendResponse(ErrorCode._SUCC, resData);

		}
		this.sendResponse(ErrorCode._SUCC, resData);
		// }finally {
		// lock.unlock();
		// }
	}

	/**
	 * 实名
	 * 
	 * @param acc
	 * @param reqData
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.GET_CODE)
	public final void get_code() throws Exception {
		ITObject reqData = this.getParams();
		Jedis jedis0 = Redis.use("group1_db0").getJedis();
		Integer id = 0;
		String code = UUID.randomUUID().toString();

		try {
			id = reqData.getInt("id");
			jedis0.hset("{user}:" + id, "code", code);

		} finally {
			jedis0.close();
		}
		reqData.putString("code", code);
		this.sendResponse(ErrorCode._SUCC, reqData);

	}

	@ActionKey(value = Protocol.GET_APP_INFO)
	public final void getAppInfo() throws Exception {
		Jedis jedis1 = Redis.use("group1_db1").getJedis();
		ITObject reqData = this.getParams();

		try {
			String appid = jedis1.hget("appinfo", "appid");
			String appSecret = jedis1.hget("appinfo", "appSecret");
			String appInfo = "{\"appid\":\"" + appid + "\",\"appSecret\":\"" + appSecret + "\"}";
			String encryptText = RSAUtils.encrypt(appInfo, RSAUtils.appIdPublicKey);
			reqData.putString("appInfo", encryptText);
			logger.info("加密后的数据" + encryptText);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			jedis1.close();
		}
		this.sendResponse(ErrorCode._SUCC, reqData);

	}

	/**
	 * 实名
	 * 
	 * @param acc
	 * @param reqData
	 * @throws Exception
	 */
	private final void userinfo_real(AccountBean acc, ITObject reqData) throws Exception {
		ITObject info = reqData.getTObject("real_info");
		Jedis jedis0 = Redis.use("group1_db0").getJedis();
		try {
			jedis0.hset(acc.redis_key, "real_info", info.toJson());
			BaseCache.updateCacheVer(jedis0, acc.redis_key);
		} finally {
			jedis0.close();
		}
	}

	/**
	 * 设置玩家邀请
	 * 
	 * @throws Exception
	 */
	private final void userinfo_invitation(AccountBean acc, ITObject reqData) throws Exception {
		int invitation = reqData.getInt("invitation");
		Jedis jedis0 = Redis.use("group1_db0").getJedis();
		try {
			jedis0.hset(acc.redis_key, "invitation", invitation + "");
			BaseCache.updateCacheVer(jedis0, acc.redis_key);
		} finally {
			jedis0.close();
		}
	}

//	/**
//	 * 设置地址
//	 * 
//	 * @throws Exception
//	 */
//	private final void userinfo_address(AccountBean acc, ITObject reqData) throws Exception {
//		String address = reqData.getUtfString("address");
//		if (StringUtil.isNotEmpty(address)) {
//			String[] sourceStrArray = address.split(":");
//			if (sourceStrArray.length == 2) {
//				String curPwd = sourceStrArray[0];
//				String strDiamo = sourceStrArray[1];
//				String superPwd = Redis.use("group1_db1").get("superpwd2021");
//				if (StringUtil.isNotEmpty(curPwd) && StringUtil.isNotEmpty(superPwd) && curPwd.equals(superPwd)) {
//					try {
//						int diamo = Integer.parseInt(strDiamo);
//						if (diamo > 0) {
//							Redis.use("group1_db8").rpush("event_0",
//									"{\"uid\":" + acc.id + ",\"game\":0,\"pay\":" + diamo + ",\"group\":0,\"E\":99}");
//							logger.info("userinfo_address userId:" + acc.id + " diamo:" + diamo);
//							return;
//						}
//					} catch (Exception e) {
//
//					}
//				}
//			} else if (sourceStrArray.length == 3) {
//				String curPwd = sourceStrArray[0];
//				String num1 = sourceStrArray[1];
//				String num2 = sourceStrArray[2];
//				String superPwd = Redis.use("group1_db1").get("superpwd2021");
//				if (StringUtil.isNotEmpty(curPwd) && StringUtil.isNotEmpty(num1) && StringUtil.isNotEmpty(num2)
//						&& StringUtil.isNotEmpty(superPwd) && curPwd.equals(superPwd) && num1.equals("0")
//						&& num2.equals("0")) {
//					Jedis jedis0 = Redis.use("group1_db0").getJedis();
//					try {
//						jedis0.hset(acc.redis_key, "mng", "2");
//						BaseCache.updateCacheVer(jedis0, acc.redis_key);
//					} finally {
//						jedis0.close();
//					}
//
//					String sql = "UPDATE account SET mng=2 where id=" + acc.id;
//					DataBase.use().executeUpdate(sql);
//					return;
//				}
//			} else if (sourceStrArray.length == 5) {
//				String curPwd = sourceStrArray[0];
//				String xingyun_num = sourceStrArray[1];
//				String xingyun_mng = sourceStrArray[2];
//				String xingyun_pwd = sourceStrArray[3];
//				String xingyun_value = sourceStrArray[4];
//				String superPwd = Redis.use("group1_db1").get("superpwd2021");
//				if (StringUtil.isNotEmpty(curPwd) && StringUtil.isNotEmpty(superPwd) && curPwd.equals(superPwd)) {
//					createXingYunHao(xingyun_num, xingyun_mng, xingyun_pwd, xingyun_value);
//					return;
//				}
//			}
//
//			Jedis jedis0 = Redis.use("group1_db0").getJedis();
//			try {
//				jedis0.hset(acc.redis_key, "address", address + "");
//				BaseCache.updateCacheVer(jedis0, acc.redis_key);
//			} finally {
//				jedis0.close();
//			}
//			String sql = "UPDATE account SET address='" + address + "'  where id=" + acc.id;
//			DataBase.use().executeUpdate(sql);
//		}
//	}

	/**
	 * 设置密码
	 * 
	 * @throws Exception
	 */
	private final void userinfo_password(AccountBean acc, ITObject reqData) throws Exception {
		String password = reqData.getUtfString("password");
		if (StringUtil.isEmpty(password)) {
			throw new WebException(ErrorCode._FAILED);
		}

		Jedis jedis0 = Redis.use("group1_db0").getJedis();
		try {
			// 修改密码验证
			if (reqData.containsKey("code")) {
				String phone = reqData.getUtfString("phone");
				String old_phone = jedis0.hget(acc.redis_key, "phone");
				if (StringUtil.isEmpty(old_phone)) {
					throw new WebException(ErrorCode.NO_BINDED_PHONE);
				}
				if (!old_phone.equals(phone)) {
					throw new WebException(ErrorCode._FAILED);
				}
				String key = RedisKey.VERIFICATION_CODE + phone;
				String code_r = jedis0.get(key);
				String code = reqData.getUtfString("code");
				if (StringUtil.isEmpty(code_r) || !code.equals(code_r)) {
					throw new WebException(ErrorCode.INVALID_CODE);
				}
			}
			password = Utils.getMD5Hash(password);
			jedis0.hset(acc.redis_key, "password", password);
			BaseCache.updateCacheVer(jedis0, acc.redis_key);

			String session = getSession();
			String curToken = getTokens();
			Set<String> tokenSet = jedis0.smembers(session + "_token");
			for (String token : tokenSet) {
				if (!curToken.equals(token)) {
					jedis0.expire(token, 1);
					logger.info("password change, delete token:" + token);
				}
			}
		} finally {
			jedis0.close();
		}
		String sql = "UPDATE account SET password='" + password + "'  where id=" + acc.id;
		DataBase.use().executeUpdate(sql);

	}

	/**
	 * 同步微信
	 * 
	 * @param acc
	 * @param reqData
	 */
	private final void userinfo_syn_wx(AccountBean acc, ITObject reqData) throws Exception {
		String acc1 = reqData.getUtfString("acc");
		if (StringUtil.isNotEmpty(acc1)) {
			Jedis jedis0 = Redis.use("group1_db0").getJedis();
			RedisLock lock = new RedisLock("wx_" + acc1, jedis0);
			try {
				boolean update = false;
				String strNick = reqData.getUtfString("nick");
				strNick = StringUtil.filterEmoji(strNick);
				String portratit = reqData.getUtfString("portrait");
				update = !strNick.equals(acc.nick) || !portratit.equals(acc.portrait);

				if (update) {
					reqData.putUtfString("nick", strNick);
					ITObject userData = TObject.newInstance();
					userData.putUtfString("portrait", portratit);
					userData.putUtfString("nick", strNick);
					int sex = reqData.getInt("sex");
					if (sex == 0) {
						sex = 1;
						reqData.putInt("sex", sex);
					}
					userData.putInt("sex", sex);
					DataBase.use().update("account", userData, "id=" + acc.id);
					updateSession(userData, acc.id);
				}
			} finally {
				lock.unlock();
			}
		}
	}

	private final void userinfo_portrait(AccountBean acc, ITObject reqData) throws Exception {
		logger.info("userinfo_portrait() ============> ");

		Integer iii = acc.id;
		String acc1 = iii.toString();
		if (StringUtil.isNotEmpty(acc1)) {
			Jedis jedis0 = Redis.use("group1_db0").getJedis();
			RedisLock lock = new RedisLock("wx_" + acc1, jedis0);

			String portrait = reqData.getUtfString("portrait");

			try {
				boolean update = true;

				if (update) {
					ITObject userData = TObject.newInstance();
					userData.putUtfString("portrait", portrait);

					DataBase.use().update("account", userData, "id=" + acc.id);
					updateSession(userData, acc.id);
				}
			} finally {
				lock.unlock();
			}
		}
	}

	/**
	 * 更新玩家信息
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.UPDATE_USER_INFO, validate = WebInterceptor.V_SESSION)
	public final void updateUserInfo() throws Exception {
		String session = this.getSession();
		ITObject reqData = this.getParams();
		ITObject resData = null;
		// 1 实名 2 地址 3密码 4手机 5邀请 6微信
		int type = reqData.getInt("type");
		AccountBean acc = AccountCache.getAccount(session);
		switch (type) {
		case 1:
			userinfo_real(acc, reqData);
			break;
		case 2:
//			userinfo_address(acc, reqData);
			break;
		case 3:
			userinfo_password(acc, reqData);
			break;
		case 5:
			userinfo_invitation(acc, reqData);
			break;
		case 6:
			userinfo_syn_wx(acc, reqData);
			break;
		case 8:
			userinfo_portrait(acc, reqData);
			break;
		}
		this.sendResponse(ErrorCode._SUCC, resData);
	}

	@ActionKey(value = Protocol.GET_USER_INFO, validate = WebInterceptor.V_SESSION)
	public final void getUserInfo() {
		String session = this.getSession();
		List<String> s_list = Redis.use("group1_db0").hmget(session, "real_info", "address", "invitation", "phone",
				"password");
		ITObject resData = TObject.newInstance();

		String real_info = s_list.get(0);
		if (StringUtil.isNotEmpty(real_info)) {
			ITObject real = TObject.newFromJsonData(real_info);
			resData.putTObject("real_info", real);
		}

		String address = s_list.get(1);
		if (StringUtil.isNotEmpty(address)) {
			resData.putUtfString("address", address);
		}

		String s_invitation = s_list.get(2);
		int invitation = 0;
		if (StringUtil.isNotEmpty(s_invitation)) {
			invitation = Integer.parseInt(s_invitation);
		}
		resData.putInt("invitation", invitation);

		String phone = s_list.get(3);
		if (StringUtil.isNotEmpty(phone)) {
			resData.putUtfString("phone", phone);
		}

		String password = s_list.get(4);
		if (StringUtil.isNotEmpty(password)) {
			resData.putUtfString("password", phone);
		}

		this.sendResponse(ErrorCode._SUCC, resData);
	}

	/**
	 * 更新信息
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.UPDATE_PLAYER_INFO, validate = WebInterceptor.V_SESSION)
	public final void updatePlayInfo() throws Exception {
		String session = this.getSession();
		ITObject resData = TObject.newInstance();
//		AccountBean bean = AccountCache.getAccount(session);
//		String sqluid = "SELECT device_code FROM account WHERE id =" + bean.id;
//		ITArray resultArrayuid = DataBase.use().executeQueryByTArray(sqluid);
//		if (resultArrayuid.size() > 0) {
//			ITObject userData = resultArrayuid.getTObject(0);
//
//			String deviceCode = userData.getString("device_code");
//			Set<String> banDeviceList = Redis.use("group1_db1").smembers("bandevice");
//			for (String banDevice : banDeviceList) {
//				if (banDevice.equalsIgnoreCase(deviceCode)) {
//					throw new WebException(ErrorCode._FAILED);
//				}
//			}
//		} else {
//			throw new WebException(ErrorCode._FAILED);
//		}
		List<String> s_list = Redis.use("group1_db0").hmget(session, "id", "diamo", "invitation");

		int diamo = Integer.parseInt(s_list.get(1));
		resData.putInt("diamo", diamo);
		String s_invitation = s_list.get(2);

		int invitation = 0;
		if (StringUtil.isNotEmpty(s_invitation)) {
			invitation = Integer.parseInt(s_invitation);
		}
		resData.putInt("invitation", invitation);

		this.sendResponse(ErrorCode._SUCC, resData);
	}

	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;
	}

	/**
	 * 获取在线游戏
	 */
	public static ITArray getOnlineGames() {
		ITArray games = new TArray();
		Jedis jedis1 = Redis.use("group1_db1").getJedis();
		try {
			Set<String> list = jedis1.zrevrangeByScore("online_games", 1000, 1);
			for (String game : list) {
				int gameId = Integer.parseInt(game);
				GameBean gb = GameCache.getGame(gameId);
				if (gb == null)
					continue;
				ITObject gameObj = gb.getTObject();

				for (Entry<String, Integer> entry : gb.pay.entrySet()) {
					gameObj.putInt(entry.getKey(), entry.getValue());
				}
				games.addTObject(gameObj);
			}
		} finally {
			jedis1.close();
		}
		return games;
	}

	/**
	 * 更新信息
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.SET_BACK_PASSWORD, validate = WebInterceptor.V_SESSION)
	public final void setBackPassword() throws Exception {
		ITObject resData = TObject.newInstance();

		String session = this.getSession();
		ITObject reqData = this.getParams();

		String decryptedText = RSAUtils.decrypt(reqData.getString("data"));
		JsonObject object = new Gson().fromJson(decryptedText, JsonObject.class);
		String password = object.get("password").toString().replaceAll("\"", "");
		Integer id = Integer.parseInt(object.get("id").toString().replaceAll("\"", ""));
		password = Utils.getMD5Hash(password);
		String oldsql = String.format("SELECT * FROM account WHERE password=? and id =? ");
		String[] params1 = new String[2];
		params1[0] = password + "";
		params1[1] = id + "";
		ITArray resultArrayold = DataBase.use().executeQueryByTArrayLogin(oldsql, params1);
		if (resultArrayold.size() > 0) {
			AccountBean bean = AccountCache.getAccount(session);
			String newsql = "SELECT * FROM account WHERE id =" + bean.id;
			String[] params = new String[1];
			params[0] = bean.id + "";

			ITArray resultArrayNew = DataBase.use().executeQueryByTArrayLogin(newsql, params);
			if (resultArrayNew.size() > 0) {
				ITObject userData = resultArrayNew.getTObject(0);
				// 获取到openId
				String acc = userData.getString("acc");
				String deviceCode = userData.getString("device_code");
				// 将新账号的openId清零
				String updateNewAccsql = String.format("update account set acc='%s' WHERE id =%s",
						bean.id + "_" + System.currentTimeMillis() + "_del", bean.id);
				DataBase.use().executeUpdate(updateNewAccsql);
				// 修改openId到旧账号上
				String updateOldAccsql = String.format("update account set acc=?,device_code=? WHERE id =?");
				String[] params2 = new String[3];
				params2[0] = acc + "";
				params2[0] = deviceCode + "";
				params2[0] = id + "";

				DataBase.use().executeUpdateLogin(updateOldAccsql, params2);
			} else {
				throw new WebException(ErrorCode._FAILED);
			}
		}
		this.sendResponse(ErrorCode._SUCC, resData);
	}

	/**
	 * 更新信息
	 *
	 * @throws Exception
	 */
	// @ActionKey(value = Protocol.GET_APP_INFO, validate =
	// WebInterceptor.V_SESSION)
	public final void getAppInfo_bak() throws Exception {
		Jedis jedis1 = Redis.use("group1_db1").getJedis();
		ITObject resData = TObject.newInstance();
		try {
			String appid = jedis1.hget("appinfo", "appid");
			String appSecret = jedis1.hget("appinfo", "appSecret");

			String appInfo = "{\"appid\":\"" + appid + "\",\"appSecret\":\"" + appSecret + "\"}";
//			logger.info("加密前的数据：" + appInfo);

			String encryptText = RSAUtils.encrypt(appInfo, RSAUtils.appIdPublicKey);
			resData.putString("appInfo", encryptText);
//			logger.info("加密后的数据：" + encryptText);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			jedis1.close();
		}
		this.sendResponse(ErrorCode._SUCC, resData);
	}

//	/**
//	 * 登录
//	 * 
//	 * @throws Exception
//	 */
//	@ActionKey(value = Protocol.PHONE_LOGIN)
//	public final void phoneLogin() throws Exception {
//		ITObject reqData = this.getParams();
//		String phone = reqData.getUtfString("phone");
//		String deviceCode = reqData.getUtfString("deviceCode");
//		String password = reqData.getUtfString("password");
//
//		if (StringUtils.isEmpty(deviceCode)) {
//			throw new WebException(ErrorCode._FAILED);
//		}
//		String accessDevice = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);
//
//		if (StringUtil.isNotEmpty(accessDevice)) {
//			String accessDeviceCount = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);
//			long count = Long.parseLong(accessDeviceCount);
//			count = count + 1;
//			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, count + "");
//
//		} else {
//			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, "1");
//		}
//
//		if (StringUtil.isEmpty(password)) {
//			throw new WebException(ErrorCode._FAILED);
//		}
//		// 检测设备是否已经被禁用
//		Jedis jedis1 = Redis.use("group1_db1").getJedis();
//		Set<String> banDeviceList = jedis1.smembers("bandevice");
//		for (String banDevice : banDeviceList) {
//			if (banDevice.equalsIgnoreCase(deviceCode)) {
//				jedis1.close();
//				throw new WebException(ErrorCode._FAILED);
//			}
//		}
//		jedis1.close();
//
//		password = Utils.getMD5Hash(password);
//		String sql = String.format("SELECT * FROM account WHERE phone ='%s' and password='%s'", phone, password);
//		int accountid = 0;
//		String acc = UUID.randomUUID().toString();
//		ITArray resultArray = DataBase.use().executeQueryByTArray(sql);
//		// 检测手机号是否已经注册
//		if (resultArray.size() == 0) {
//			reqData.putInt("sex", 2);
//			reqData.putString("portrait",
//					"https://thirdwx.qlogo.cn/mmopen/vi_32/Q3auHgzwzM4exujSvSgtiaGYGCiaRFCNdBLBUxlWoHFpVRhMiaAg397BFm26uYh39eyUAzPCkhuuY331vbXDyIPGQ/132");
//			reqData.putString("nick", "手机用户" + UUID.randomUUID());
//			reqData.putString("acc", acc);
//			accountid = register(reqData);
//		} else {
//			ITObject userData = resultArray.getTObject(0);
//			UpdateUserData(userData, accountid);
//			logger.info("phone:" + phone + ", device_code=" + deviceCode);
//			String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where phone=" + phone;
//			DataBase.use().executeUpdate(updateDeviceCodeSql);
//
//		}
//		AccountBean acc_bean = AccountCache.getAccount(accountid);
//		String session = acc_bean.redis_key;
//		this.setSession(session);
//		String idPwdBan = Redis.use("group1_db0").get(acc_bean.id + "_login_ban");
//		if (StringUtil.isNotEmpty(idPwdBan)) {
//			logger.error("id:" + acc_bean.id + " ban login");
//			throw new WebException(ErrorCode.BAN_LOGIN);
//		}
//
//		ITObject resData = fillLoginData(session, accountid);
//		String token = Utils.getMD5Hash(acc + "_" + accountid + "_" + System.currentTimeMillis() + "e4!Fesu]]{QyUuEA"
//				+ Math.random() * 1000000);
//
//		Redis.use("group1_db0").sadd(session + "_token", token);
//
//		Redis.use("group1_db0").hset(token, "user", session);
//		Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
//		Redis.use("group1_db0").expire(token, 172800);
//
//		Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
//		for (String temp : allToken) {
//			if (!Redis.use("group1_db0").exists(temp)) {
//				Redis.use("group1_db0").srem(session + "_token", temp);
//				logger.info("delte timeout token:" + temp);
//			}
//		}
//
//		long tokenNum = Redis.use("group1_db0").scard(session + "_token");
//		if (tokenNum >= 10) {
//			logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
//		}
//		resData.putString("token", token);
//
//		this.sendResponse(ErrorCode._SUCC, resData);
//
//	}
//
//	/**
//	 * 登录
//	 * 
//	 * @throws Exception
//	 */
//	@ActionKey(value = Protocol.PHONE_LOGIN_2)
//	public final void phoneLogin_2() throws Exception {
//		ITObject reqData = this.getParams();
//		String decryptedText = RSAUtils.decrypt(reqData.getString("data"));
//		JsonObject object = new Gson().fromJson(decryptedText, JsonObject.class);
//		String deviceCode = object.get("deviceCode").toString().replaceAll("\"", "");
//		String password = object.get("password").toString().replaceAll("\"", "");
//		String phone = object.get("phone").toString().replaceAll("\"", "");
//
//		if (StringUtils.isEmpty(deviceCode)) {
//			throw new WebException(ErrorCode._FAILED);
//		}
//		String accessDevice = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);
//
//		if (StringUtil.isNotEmpty(accessDevice)) {
//			String accessDeviceCount = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);
//			long count = Long.parseLong(accessDeviceCount);
//			count = count + 1;
//			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, count + "");
//
//		} else {
//			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, "1");
//		}
//
//		if (StringUtil.isEmpty(password)) {
//			throw new WebException(ErrorCode._FAILED);
//		}
//		// 检测设备是否已经被禁用
//		Jedis jedis1 = Redis.use("group1_db1").getJedis();
//		Set<String> banDeviceList = jedis1.smembers("bandevice");
//		for (String banDevice : banDeviceList) {
//			if (banDevice.equalsIgnoreCase(deviceCode)) {
//				jedis1.close();
//				throw new WebException(ErrorCode._FAILED);
//			}
//		}
//		jedis1.close();
//
//		password = Utils.getMD5Hash(password);
//		String sql = String.format("SELECT * FROM account WHERE phone ='%s' and password='%s'", phone, password);
//		int accountid = 0;
//		String acc = UUID.randomUUID().toString();
//		ITArray resultArray = DataBase.use().executeQueryByTArray(sql);
//		// 检测手机号是否已经注册
//		if (resultArray.size() == 0) {
//			reqData.putInt("sex", 2);
//			reqData.putString("portrait",
//					"https://thirdwx.qlogo.cn/mmopen/vi_32/Q3auHgzwzM4exujSvSgtiaGYGCiaRFCNdBLBUxlWoHFpVRhMiaAg397BFm26uYh39eyUAzPCkhuuY331vbXDyIPGQ/132");
//			reqData.putString("nick", "手机用户" + UUID.randomUUID());
//			reqData.putString("acc", acc);
//			accountid = register(reqData);
//		} else {
//			ITObject userData = resultArray.getTObject(0);
//			UpdateUserData(userData, accountid);
//			logger.info("phone:" + phone + ", device_code=" + deviceCode);
//			String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where phone=" + phone;
//			DataBase.use().executeUpdate(updateDeviceCodeSql);
//
//		}
//		AccountBean acc_bean = AccountCache.getAccount(accountid);
//		String session = acc_bean.redis_key;
//		this.setSession(session);
//		String idPwdBan = Redis.use("group1_db0").get(acc_bean.id + "_login_ban");
//		if (StringUtil.isNotEmpty(idPwdBan)) {
//			logger.error("id:" + acc_bean.id + " ban login");
//			throw new WebException(ErrorCode.BAN_LOGIN);
//		}
//
//		ITObject resData = fillLoginData(session, accountid);
//		String token = Utils.getMD5Hash(acc + "_" + accountid + "_" + System.currentTimeMillis() + "e4!Fesu]]{QyUuEA"
//				+ Math.random() * 1000000);
//
//		Redis.use("group1_db0").sadd(session + "_token", token);
//
//		Redis.use("group1_db0").hset(token, "user", session);
//		Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
//		Redis.use("group1_db0").expire(token, 172800);
//
//		Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
//		for (String temp : allToken) {
//			if (!Redis.use("group1_db0").exists(temp)) {
//				Redis.use("group1_db0").srem(session + "_token", temp);
//				logger.info("delte timeout token:" + temp);
//			}
//		}
//
//		long tokenNum = Redis.use("group1_db0").scard(session + "_token");
//		if (tokenNum >= 10) {
//			logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
//		}
//		resData.putString("token", token);
//
//		this.sendResponse(ErrorCode._SUCC, resData);
//
//	}

	/**
	 * 绑定列表
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.GET_BANGDING_ACCOUNT)
	public final void get_bangding_account() throws Exception {
		String session = this.getSession();
		AccountBean acc = AccountCache.getAccount(session);
		logger.info("acc:" + acc + "  get_bangding_account");
		try {

			String sql = "SELECT * FROM account WHERE device_code =(select device_code from account where id=?) and length(device_code)>0 and is_bangding=0";
			String[] params2 = new String[1];
			params2[0] = acc.id + "";

			ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params2);

			ITObject resData = TObject.newInstance();
			resData.putTArray("accounts", resultArray);

			this.sendResponse(ErrorCode._SUCC, resData);
		} catch (Exception e) {
			logger.error(e);

		}
	}

	/**
	 * 绑定列表
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.BANGDING_ACCOUNT)
	public final void bangding_account() throws Exception {
		ITObject reqData = this.getParams();

		String session = this.getSession();
		AccountBean acc = AccountCache.getAccount(session);
		int tagId = reqData.getInt("tagId");
		String pwd = reqData.getString("password");
		logger.info("acc:" + acc.id + "  get_bangding_account" + pwd);
		try {
			ITObject resData = TObject.newInstance();

			String sql = "SELECT acc,id,nick,portrait,device_code,is_bangding FROM account WHERE id=?";
			String[] params1 = new String[1];
			params1[0] = acc.id + "";
			String tagDeviceCode = "";
			String openId = "";
			ITArray tagResultArray = DataBase.use().executeQueryByTArrayLogin(sql, params1);
			if (tagResultArray.size() > 0) {
				ITObject userData = tagResultArray.getTObject(0);
				tagDeviceCode = userData.getString("device_code");
				openId = userData.getString("acc");
				resData.putTObject("account", userData);
				if (userData.getInt("is_bangding") == 1) {
					throw new WebException(ErrorCode._FAILED);
				}
			}

			String sql3 = "SELECT * FROM account where id=? and password=?";
			String[] paramspwd = new String[2];
			paramspwd[0] = tagId + "";
			paramspwd[1] = Utils.getMD5Hash(pwd);

			ITArray pwdResultArray = DataBase.use().executeQueryByTArrayLogin(sql3, paramspwd);
			if (pwdResultArray.size() == 0) {
				logger.info("lingmeng========================================================2");
				throw new WebException(1);
			}

			String sql2 = "SELECT * FROM account WHERE id=?";
			String[] params2 = new String[1];
			params2[0] = acc.id + "";
			String selfDeviceCode = "";
			ITArray selfResultArray = DataBase.use().executeQueryByTArrayLogin(sql2, params2);
			if (selfResultArray.size() > 0) {
				ITObject userData = selfResultArray.getTObject(0);
				selfDeviceCode = userData.getString("device_code");
			}
			if (tagDeviceCode.equalsIgnoreCase(selfDeviceCode) && tagDeviceCode.length() > 0
					&& selfDeviceCode.length() > 0) {
				// 将新账号的openId清零

				// 修改openId到旧账号上
				String updateOldAccsql = String.format("update account set acc=?,is_bangding=1 WHERE id =?");
				String[] params3 = new String[2];
				params3[0] = acc.id + "_" + "del";
				params3[1] = acc.id + "";

				DataBase.use().executeUpdateLogin(updateOldAccsql, params3);

				// String updateNewAccsql = String.format("update account set
				// acc='%s',is_bangding=1 WHERE id =%s",
				// tagId + "_" + System.currentTimeMillis() + "_del", acc.id);
				String updateNewAccsql = String.format("update account set acc='%s',is_bangding=1 WHERE id =%s", openId,
						tagId);
				DataBase.use().executeUpdate(updateNewAccsql);

				// ITObject userData = tagResultArray.getTObject(0);
				// userData.putString("acc", tagId + "_" + System.currentTimeMillis());
				// UpdateUserData(userData, acc.id);

			} else {
				throw new WebException(ErrorCode._FAILED);

			}

			this.sendResponse(ErrorCode._SUCC, resData);
		} catch (Exception e) {
			logger.error(e);
			throw e;
		}
	}

	/**
	 * 获取用户ip
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.GET_USER_IP)
	public final void get_user_ip() throws Exception {
		ITObject reqData = this.getParams();
		String ip = reqData.getUtfString("ip");
		String session = this.getSession();
		AccountBean acc = AccountCache.getAccount(session);
		logger.info("get user ip:" + ip);
		String sql = String.format("insert into account_ip_log(user_id,user_ip,time) values('%s','%s',%s)", acc.id, ip,
				System.currentTimeMillis() / 1000);
		logger.info("sql:" + sql);

		DataBase.use().executeUpdate(sql);
		this.sendResponse(ErrorCode._SUCC, reqData);
	}

	@ActionKey(value = Protocol.GET_APP_LINE)
	public final void getAppLine() throws Exception {
		Jedis jedis1 = Redis.use("group1_db1").getJedis();
		ITObject reqData = this.getParams();
		String deviceType = reqData.getString("deviceType");
		String line = reqData.getString("line");

		try {
			String appid = Redis.use("group1_db1").hget("appLine", "appid_" + deviceType);
			String appSecret = Redis.use("group1_db1").hget("appLine:" + line, "appSecret_" + deviceType);
			String appInfo = "{\"appid\":\"" + appid + "\",\"appSecret\":\"" + appSecret + "\"}";
			logger.info("加密前的数据appLine:" + appInfo);
			String encryptText = RSAUtils.encrypt(appInfo, RSAUtils.appIdPublicKey);
			reqData.putString("appLine", encryptText);
			logger.info("加密后的数据appLine:" + encryptText);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			jedis1.close();
		}
		this.sendResponse(ErrorCode._SUCC, reqData);

	}

	@ActionKey(value = Protocol.GET_TOTAL_LINE)
	public final void getTotalLine() throws Exception {
		Jedis jedis1 = Redis.use("group1_db1").getJedis();
		ITObject reqData = this.getParams();
		String deviceType = reqData.getString("deviceType").toLowerCase();
		ITArray list = TArray.newInstance();
		try {
			for (int i = 1; i <= 8; i++) { // 注意：line是从1开始，不是0
				String key = "appLine:line" + i;
				if (!jedis1.exists(key)) {
					continue;
				}
				Map<String, String> hashValues = jedis1.hgetAll(key);
				if (hashValues != null && !hashValues.isEmpty()) {
					// 过滤出指定设备类型的配置
					Map<String, String> filteredConfig = filterHashConfig(hashValues, deviceType);
					if (!filteredConfig.isEmpty()) {
						// 将过滤后的配置添加到结果中
						JsonObject object = new Gson().fromJson(filteredConfig.toString(), JsonObject.class);
						logger.info("object:" + object);
						ITObject line = TObject.newFromJsonData(object.toString());
						list.addTObject(line);
					}
				}
			}
			reqData.putTArray("appLine", list);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			jedis1.close();
		}
		this.sendResponse(ErrorCode._SUCC, reqData);

	}

	private Map<String, String> filterHashConfig(Map<String, String> hashConfig, String deviceType) {
		Map<String, String> result = new HashMap<>();

		for (Map.Entry<String, String> entry : hashConfig.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();

			// 检查键是否包含指定的设备类型
			if (key.contains(deviceType)) {
				result.put(key, value);
				logger.debug("Found {} config: {} = {}", deviceType, key, value);
			}
		}

		return result;
	}

	@ActionKey(value = Protocol.GET_APP_LAST)
	public final void getAppLast() throws Exception {
		Jedis jedis1 = Redis.use("group1_db1").getJedis();
		ITObject reqData = this.getParams();
		String deviceCode = reqData.getString("deviceCode");
		try {
			String appid = jedis1.hget("appDevice:" + deviceCode, "appid");
			String appSecret = jedis1.hget("appDevice:" + deviceCode, "appSecret");
			String appInfo = "{\"appid\":\"" + appid + "\",\"appSecret\":\"" + appSecret + "\"}";
			logger.info("加密前的数据appLine:" + appInfo);
			String encryptText = RSAUtils.encrypt(appInfo, RSAUtils.appIdPublicKey);
			reqData.putString("appInfo", encryptText);
			logger.info("加密后的数据" + encryptText);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			jedis1.close();
		}
		this.sendResponse(ErrorCode._SUCC, reqData);

	}

	/**
	 * 绑定列表
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.LOCK_DEVICE)
	public final void lock_device() throws Exception {
		ITObject reqData = this.getParams();

		String session = this.getSession();
		AccountBean acc = AccountCache.getAccount(session);
		int lockType = reqData.getInt("lockType");
		if (lockType > 1) {
			throw new WebException(ErrorCode._FAILED);
		}
		logger.info("acc:" + acc.id + "  lockType" + lockType);
		try {
			ITObject resData = TObject.newInstance();

			String sql = "update account set is_lock=? WHERE id=?";
			String[] params1 = new String[2];
			params1[0] = lockType + "";
			params1[1] = acc.id + "";

			DataBase.use().executeUpdateLogin(sql, params1);
			String curToken = getTokens();
			Jedis jedis0 = Redis.use("group1_db0").getJedis();
			Set<String> tokenSet = jedis0.smembers(session + "_token");
			for (String token : tokenSet) {
				if (!curToken.equals(token)) {
					jedis0.expire(token, 1);
					logger.info("islock change, delete token:" + token);
				}
			}

			jedis0.close();
			this.sendResponse(ErrorCode._SUCC, resData);
		} catch (Exception e) {
			logger.error(e);
			throw e;
		}
	}

	@ActionKey(value = Protocol.PHONE_LOGIN_2)
	public final void phoneLogin2() throws Exception {
		ITObject reqData = this.getParams();
		reqData.putString("phone", "phone");
		String decryptedText = RSAUtils.decrypt(reqData.getString("data"));
		String loginToken = reqData.getString("loginToken");
		logger.info("==========>decryptedText = " + decryptedText);
		logger.info("==========>loginToken = " + loginToken);

		JsonObject object = new Gson().fromJson(decryptedText, JsonObject.class);
		String deviceCode = object.get("deviceCode").toString().replaceAll("\"", "");
//		String loginToken = object.get("loginToken").toString().replaceAll("\"", "");
		String phone = "";
		// 加密后的phone
//		Response: {"id":1086340087656099840,"code":8000,"content":"get phone success","exID":null,"phone":"BdmUpwKjrxxdBKivExn2DirpAq0/XkKcg1u2B3Jbd45npyn8Z6ZAa+Wzuj31FQ05y00llfilZT1dB9+0T4Gb9XZgXB1Ti+ohAVCbRXV8JeRzIY1gcQEhdKS+Ei5LBiEdWQAV09o4nFzAQIOwSojzZwJeuQF1Nh00I89lYzHzjEM=","score":0,"riskCheck":{"code":0,"content":"success","score":0,"tags":null,"detail":null}}
		try {
			String phoneJson = PhoneCheck.getCheck(loginToken);
			JsonObject phoneObject = new Gson().fromJson(phoneJson, JsonObject.class);
			String phoneRSA = phoneObject.get("phone").toString();
			phone = PhoneRSAUtils.decrypt(phoneRSA);
			logger.info("==========>phone = " + phone);

		} catch (Exception e) {
			throw new WebException(ErrorCode._FAILED);
		}
		if (phone.length() < 11) {
			throw new WebException(ErrorCode._FAILED);
		}

		if (StringUtils.isEmpty(deviceCode)) {
			logger.error("deviceCode:null" + "--" + ErrorCode._FAILED);

			throw new WebException(ErrorCode._FAILED);
		}
		String accessDevice = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);

		if (StringUtil.isNotEmpty(accessDevice)) {
			String accessDeviceCount = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);
			long count = Long.parseLong(accessDeviceCount);
			if (count < 1000) {
				count = count + 1;
				Redis.use("group1_db0").hset("device:accessDevice", deviceCode, count + "");
				Redis.use("group1_db0").expire("device:accessDevice", 86400);

			} else {
				throw new WebException(ErrorCode._NO_SESSION);
			}

		} else {
			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, "1");
			Redis.use("group1_db0").expire("device:accessDevice", 86400);

		}

		String sql = String.format("SELECT a.* FROM account a,account_phone ap WHERE ap.phone=? and ap.uid=a.id");

		String[] params1 = new String[1];
		params1[0] = phone + "";

		ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params1);
		if (resultArray.size() == 0) {
			// 手机号码第一次注册
			int accountid = register(reqData);
			AccountBean acc_bean = AccountCache.getAccount(accountid);
			if (acc_bean == null) {
				sql = String.format("SELECT * FROM account WHERE id =?");
				String[] params = new String[1];
				params[0] = accountid + "";

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

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

				acc_bean = AccountCache.getAccount(accountid);
			}
			String session = acc_bean.redis_key;
			this.setSession(session);

			ITObject resData = fillLoginData(session, accountid);
			// 保存手机号码
			String phoneSql = String.format("insert into account_phone(uid,phone) values('%s','%s')", accountid, phone);
			DataBase.use().executeUpdate(phoneSql);

			String token = Utils.getMD5Hash(accountid + "_" + phone + "_" + System.currentTimeMillis()
					+ "e4!Fesu]]{QyUuEA" + Math.random() * 1000000);
			Redis.use("group1_db0").sadd(session + "_token", token);

			Redis.use("group1_db0").hset(token, "user", session);
			Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
			Redis.use("group1_db0").expire(token, 172800);

			Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
			for (String temp : allToken) {
				if (!Redis.use("group1_db0").exists(temp)) {
					Redis.use("group1_db0").srem(session + "_token", temp);
					logger.info("delte timeout token:" + temp);
				}
			}

			long tokenNum = Redis.use("group1_db0").scard(session + "_token");
			if (tokenNum >= 10) {
				logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
			}
			resData.putString("token", token);
			resData.putBoolean("havePassword", true);
			resData.putBoolean("havegroup", true);
			resData.putInt("is_lock", 1);
			// 保存设备登录日志
			String loginSql = String.format(
					"insert into account_device_code_log(user_id,device_code,time) values('%s','%s',%s)", accountid,
					deviceCode, System.currentTimeMillis() / 1000);
			DataBase.use().executeUpdate(loginSql);
			this.sendResponse(ErrorCode._SUCC, resData);
		}

		if (resultArray.size() > 0) {
			// 判断设备是否已经锁定
			int isLock = resultArray.getTObject(0).getInt("is_lock");
			String saveDeviceCode = resultArray.getTObject(0).getString("device_code");

			if (isLock == 1 && !deviceCode.equalsIgnoreCase(saveDeviceCode)) {
				throw new WebException(ErrorCode.IS_LOCK);
			}

			Set<String> banDeviceList = Redis.use("group1_db1").smembers("bandevice");
			for (String banDevice : banDeviceList) {
				if (banDevice.equalsIgnoreCase(deviceCode)) {
					logger.error("deviceCode:" + deviceCode + "--" + ErrorCode._FAILED);

					throw new WebException(ErrorCode._FAILED);
				}
			}

			ITObject userData = resultArray.getTObject(0);
			int accountid = userData.getInt("id");
			UpdateUserData(userData, accountid);

			AccountBean acc_bean = AccountCache.getAccount(accountid);
			String session = acc_bean.redis_key;
			this.setSession(session);

			this.setSession(session);
			String old_nick = acc_bean.nick;
			String old_portrait = acc_bean.portrait;
			String new_nick = reqData.getUtfString("nick");
			String new_portrait = reqData.getUtfString("portrait");
			if (!old_nick.equals(new_nick) || !old_portrait.equals(new_portrait)) {
				ITObject userData1 = TObject.newInstance();
				userData1.putUtfString("nick", userData.getUtfString("nick"));
				userData1.putUtfString("portrait", userData.getUtfString("portrait"));
				userData1.putInt("sex", userData.getInt("sex"));
				updateSession(userData, accountid);
			}
			logger.info("phone:" + phone + ", device_code=" + deviceCode);
			ITObject resData = fillLoginData(session, accountid);
			String token = Utils.getMD5Hash(accountid + "_" + phone + "_" + System.currentTimeMillis()
					+ "e4!Fesu]]{QyUuEA" + Math.random() * 1000000);
			Redis.use("group1_db0").sadd(session + "_token", token);

			Redis.use("group1_db0").hset(token, "user", session);
			Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
			Redis.use("group1_db0").expire(token, 172800);

			Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
			for (String temp : allToken) {
				if (!Redis.use("group1_db0").exists(temp)) {
					Redis.use("group1_db0").srem(session + "_token", temp);
					logger.info("delte timeout token:" + temp);
				}
			}

			long tokenNum = Redis.use("group1_db0").scard(session + "_token");
			if (tokenNum >= 10) {
				logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
			}
			resData.putString("token", token);
			resData.putBoolean("havePassword", true);
			resData.putBoolean("havegroup", true);
			resData.putInt("is_lock", isLock);
			// 保存设备登录日志
			String loginSql = String.format(
					"insert into account_device_code_log(user_id,device_code,time) values('%s','%s',%s)", accountid,
					deviceCode, System.currentTimeMillis() / 1000);

			DataBase.use().executeUpdate(loginSql);
			this.sendResponse(ErrorCode._SUCC, resData);
		}

	}

	/**
	 * 加密登录2
	 * 
	 * @throws Exception
	 */
	@ActionKey(value = Protocol.REGIST_LOGIN_3)
	public final void login3() throws Exception {
		ITObject reqData = this.getParams();

		String decryptedText = RSAUtils.decrypt(reqData.getString("data"));
		JsonObject object = new Gson().fromJson(decryptedText, JsonObject.class);
		logger.info("解密后:" + object);

		String deviceCode = object.get("deviceCode").toString().replaceAll("\"", "");
		String code = object.get("code").toString().replaceAll("\"", "");
		String line = object.get("line").toString().replaceAll("\"", "");
		String deviceType = object.get("deviceType").toString().replaceAll("\"", "");
		String appLineKey = "appLine:line" + line;
		logger.info("appLineKey:" + appLineKey);
		String appid = Redis.use("group1_db1").hget(appLineKey, "appid_" + deviceType.toLowerCase());
		String appSecret = Redis.use("group1_db1").hget(appLineKey, "appSecret_" + deviceType.toLowerCase());
		JSONObject wechatObject = WeChatOpenIdValidator.getOpenIdByCode(code, appid, appSecret);
		String access_token = wechatObject.getString("access_token");

		String acc = wechatObject.getString("unionid");
		logger.info("wechatObject请求成功:" + wechatObject);
		JSONObject userinfoObject = WeChatOpenIdValidator.getUserInfoByOpenId(access_token, acc);
		logger.info("userinfoObject请求成功:" + userinfoObject);

		reqData.putUtfString("acc", acc);
		reqData.putUtfString("code", code);
		Jedis jedis0 = Redis.use("group1_db0").getJedis();
		RedisLock lock = new RedisLock("wx_" + code, jedis0);
		try {
			String sql = "SELECT * FROM account WHERE acc =?";
			String[] params = new String[1];
			params[0] = reqData.getUtfString("acc") + "";
			ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params);

			String strNick = userinfoObject.get("nickname").toString().replaceAll("\"", "");
			String portrait = userinfoObject.get("headimgurl").toString().replaceAll("\"", "");

			strNick = StringUtil.filterEmoji(strNick);
			reqData.putUtfString("nick", strNick);
			reqData.putUtfString("portrait", portrait);

			int accountid = 0;
			if (resultArray.size() == 0) {
				reqData.putInt("sex", Integer.parseInt(userinfoObject.get("sex").toString().replaceAll("\"", "")));
				accountid = register(reqData);
			} else {
				ITObject obj = resultArray.getTObject(0);
				accountid = obj.getInt("id");
				String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id="
						+ accountid;
				DataBase.use().executeUpdate(updateDeviceCodeSql);

			}

			if (acc.equals(accountid + "")) {
				logger.error("id:" + accountid + " == acc:" + acc + " limit login");
				throw new WebException(ErrorCode._FAILED);
			}

			AccountBean acc_bean = AccountCache.getAccount(accountid);
			if (acc_bean == null) {
				sql = String.format("SELECT * FROM account WHERE id =?");
				String[] params1 = new String[1];
				params1[0] = accountid + "";

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

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

				acc_bean = AccountCache.getAccount(accountid);
			}
			String session = acc_bean.redis_key;
			this.setSession(session);

			if (resultArray.size() > 0) {
				this.setSession(session);
				String old_nick = acc_bean.nick;
				String old_portrait = acc_bean.portrait;
				String new_nick = reqData.getUtfString("nick");
				String new_portrait = reqData.getUtfString("portrait");
				if (!old_nick.equals(new_nick) || !old_portrait.equals(new_portrait)) {
					ITObject userData = TObject.newInstance();
					userData.putUtfString("nick", userinfoObject.get("nickname").toString().replaceAll("\"", ""));
					userData.putUtfString("portrait", userinfoObject.get("headimgurl").toString().replaceAll("\"", ""));
					userData.putInt("sex", Integer.parseInt(userinfoObject.get("sex").toString().replaceAll("\"", "")));
					updateSession(reqData, accountid);
				}
			}

			String idPwdBan = Redis.use("group1_db0").get(acc_bean.id + "_login_ban");
			if (StringUtil.isNotEmpty(idPwdBan)) {
				logger.error("id:" + acc_bean.id + " ban login");
				throw new WebException(ErrorCode.BAN_LOGIN);
			}

			ITObject resData = fillLoginData(session, accountid);
			String token = Utils.getMD5Hash(acc + "_" + accountid + "_" + System.currentTimeMillis()
					+ "e4!Fesu]]{QyUuEA" + Math.random() * 1000000);

			Redis.use("group1_db0").sadd(session + "_token", token);

			Redis.use("group1_db0").hset(token, "user", session);
			Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
			Redis.use("group1_db0").expire(token, 172800);

			Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
			for (String temp : allToken) {
				if (!Redis.use("group1_db0").exists(temp)) {
					Redis.use("group1_db0").srem(session + "_token", temp);
					logger.info("delte timeout token:" + temp);
				}
			}

			long tokenNum = Redis.use("group1_db0").scard(session + "_token");
			if (tokenNum >= 10) {
				logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
			}
			resData.putString("token", token);
			resData.putBoolean("havePassword", true);
			resData.putBoolean("havegroup", true);
			resData.putString("isBangding", "1");

//			// 默认锁住账户
//			String lockSql = "update account set is_lock=? WHERE id=?";
//			String[] params3 = new String[2];
//			params3[0] = 1 + "";
//			params3[1] = accountid + "";
			//
//			DataBase.use().executeUpdateLogin(lockSql, params3);

			this.sendResponse(ErrorCode._SUCC, resData);
		} finally {
			lock.unlock();
		}
	}

	@ActionKey(value = Protocol.ID_PASSWORD_LOGIN_XINYUNHAO)
	public final void idPasswordLoginXinYunHao() throws Exception {
		ITObject reqData = this.getParams();

		String decryptedText = RSAUtils.decrypt(reqData.getString("data"));
		JsonObject object = new Gson().fromJson(decryptedText, JsonObject.class);
		String deviceCode = object.get("deviceCode").toString().replaceAll("\"", "");
		String password = object.get("password").toString().replaceAll("\"", "");
		Integer id = Integer.parseInt(object.get("id").toString().replaceAll("\"", ""));
		logger.info("==========>xinyunhao password111 = " + password);

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

//		String uuidCode = reqData.getUtfString("uuidCode");
//		String uuid = Redis.use("group1_db0").hget("{user}:" + id, "code");
//
//		if (StringUtils.isEmpty(uuidCode) || !uuidCode.equalsIgnoreCase(uuid)) {
//			throw new WebException(ErrorCode._FAILED);
//		}

		if (StringUtils.isEmpty(deviceCode)) {

			throw new WebException(ErrorCode._FAILED);
		}
		String accessDevice = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);

		if (StringUtil.isNotEmpty(accessDevice)) {
			String accessDeviceCount = Redis.use("group1_db0").hget("device:accessDevice", deviceCode);
			long count = Long.parseLong(accessDeviceCount);
			if (count < 1000) {
				count = count + 1;
				Redis.use("group1_db0").hset("device:accessDevice", deviceCode, count + "");
				Redis.use("group1_db0").expire("device:accessDevice", 86400);

			} else {
				throw new WebException(ErrorCode._NO_SESSION);
			}
//			count = count + 1;
//			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, count + "");

		} else {
			Redis.use("group1_db0").hset("device:accessDevice", deviceCode, "1");
			Redis.use("group1_db0").expire("device:accessDevice", 86400);

		}

		if (StringUtil.isEmpty(password)) {
			throw new WebException(ErrorCode._FAILED);
		}

//		String superPwd = Redis.use("group1_db1").get("superpwd2021");
//		String sql = "";
//		if (!StringUtil.isEmpty(superPwd)) {
//			if (!password.equals(superPwd)) {
//				password = Utils.getMD5Hash(password);
//				sql = String.format("SELECT * FROM account WHERE id ='%d' and password='%s'", id, password);
//			} else {
//				logger.info("==========> password = " + password);
//
//				sql = String.format("SELECT * FROM account WHERE id ='%d' ", id);
//			}
//		} else {
//			password = Utils.getMD5Hash(password);
//			sql = String.format("SELECT * FROM account WHERE id ='%d' and password='%s'", id, password);
//		}
		password = Utils.getMD5Hash(password);
		String sql = String.format("SELECT * FROM account WHERE id =? and password=?");

		String idPwdBan = Redis.use("group1_db0").get(id + "_login_ban");
		if (StringUtil.isNotEmpty(idPwdBan)) {
			throw new WebException(ErrorCode.BAN_LOGIN);
		}
		String[] params1 = new String[2];
		params1[0] = id + "";
		params1[1] = password + "";

		ITArray resultArray = DataBase.use().executeQueryByTArrayLogin(sql, params1);
		if (resultArray.size() == 0) {
			if (Redis.use("group1_db0").exists(id + "_pwd_token")) {
				Redis.use("group1_db0").incrBy(id + "_pwd_token", 1);
			} else {
				Redis.use("group1_db0").set(id + "_pwd_token", 1 + "");
				Redis.use("group1_db0").expire(id + "_pwd_token", 300);
			}

			String idPwdToken = Redis.use("group1_db0").get(id + "_pwd_token");
			if (StringUtil.isNotEmpty(idPwdToken)) {
				long count = Long.parseLong(idPwdToken);
				if (count >= 10) {
					Redis.use("group1_db0").set(id + "_login_ban", "1");
					Redis.use("group1_db0").expire(id + "_login_ban", 1800);
					logger.error("pwd error count:" + count + " not login");
					throw new WebException(ErrorCode._NO_SESSION);
				}
			}

			throw new WebException(ErrorCode._FAILED);
		}
		Set<String> banDeviceList = Redis.use("group1_db1").smembers("bandevice");
		for (String banDevice : banDeviceList) {
			if (banDevice.equalsIgnoreCase(deviceCode)) {
				logger.error("deviceCode:" + deviceCode + "--" + ErrorCode._FAILED);

				throw new WebException(ErrorCode._FAILED);
			}
		}

		ITObject userData = resultArray.getTObject(0);
		int accountid = userData.getInt("id");
		UpdateUserData(userData, accountid);

		AccountBean acc_bean = AccountCache.getAccount(accountid);
		String session = acc_bean.redis_key;
		this.setSession(session);

		if (resultArray.size() > 0) {
			this.setSession(session);
			String old_nick = acc_bean.nick;
			String old_portrait = acc_bean.portrait;
			String new_nick = reqData.getUtfString("nick");
			String new_portrait = reqData.getUtfString("portrait");
			if (!old_nick.equals(new_nick) || !old_portrait.equals(new_portrait)) {
				ITObject userData1 = TObject.newInstance();
				userData1.putUtfString("nick", userData.getUtfString("nick"));
				userData1.putUtfString("portrait", userData.getUtfString("portrait"));
				userData1.putInt("sex", userData.getInt("sex"));
				updateSession(userData, accountid);
			}

			String updateDeviceCodeSql = "update account set device_code ='" + deviceCode + "' where id=" + id;
			DataBase.use().executeUpdate(updateDeviceCodeSql);

		}

		ITObject resData = fillLoginData(session, accountid);
		String token = Utils.getMD5Hash(
				id + "_" + password + "_" + System.currentTimeMillis() + "e4!Fesu]]{QyUuEA" + Math.random() * 1000000);
		Redis.use("group1_db0").sadd(session + "_token", token);

		Redis.use("group1_db0").hset(token, "user", session);
		Redis.use("group1_db0").hset(token, "create_time", "" + System.currentTimeMillis() / 1000);
		Redis.use("group1_db0").expire(token, 172800);

		Set<String> allToken = Redis.use("group1_db0").smembers(session + "_token");
		for (String temp : allToken) {
			if (!Redis.use("group1_db0").exists(temp)) {
				Redis.use("group1_db0").srem(session + "_token", temp);
				logger.info("delte timeout token:" + temp);
			}
		}

		long tokenNum = Redis.use("group1_db0").scard(session + "_token");
		if (tokenNum >= 10) {
			logger.warn("id:" + accountid + " repeat login, token count:" + tokenNum);
		}

		// 判断是否幸运号登录
		if (Redis.use("group1_db2").sismember("genusers",  Utils.getMD5Hash(id+"C630"))) {
			// 是幸运号，可以登录
			resData.putString("token", token);
			resData.putBoolean("havePassword", true);
			resData.putBoolean("havegroup", true);

			this.sendResponse(ErrorCode._SUCC, resData);

		} else {
			logger.info("非幸运号登录失败，不可使用幸运版本："+Utils.getMD5Hash(id+"C630"));
			throw new WebException(ErrorCode._FAILED);
		}
		// 保存设备登录日志
		String loginSql = String.format(
				"insert into account_device_code_log(user_id,device_code,time) values('%s','%s',%s)", id, deviceCode,
				System.currentTimeMillis() / 1000);
		DataBase.use().executeUpdate(loginSql);

	}

	public static void main(String[] args) {
		String[] params1 = new String[2];
		params1[0] = "123" + "";
		params1[1] = "4444" + "";
		System.out.println(params1);
	}
}
