package hunan;


import com.game.Util;
import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TObject;
import com.taurus.core.events.Event;
import com.taurus.core.events.IEventListener;
import com.taurus.core.plugin.database.DataBase;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.util.ICallback;
import com.taurus.core.util.Logger;
import com.taurus.core.util.StringUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import taurus.client.*;
import taurus.client.business.AccountBusiness;
import taurus.client.business.GroupRoomBusiness;
import taurus.util.ChangShaSuanFaTest;
import taurus.util.TinHuChi;


import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

public class JiQiRens {


    private final static Logger log;

    static {
        log = Logger.getLogger(JiQiRens.class);
    }


    // 扣点点玩家手牌
    public static List<Integer> cardInhand = new ArrayList<Integer>();

    //使用数量
    public static Map<Integer, Integer> count = new HashMap<Integer, Integer>();

    //扣点点别人打的牌
    private String card = "";

    // 玩家座位号
    public static int seat = 0;
    // 玩家ID
    // 登录密码
    public static String password = "123456";
    // 会话标识
    private String session = "";
    // 访问令牌
    public String token = "";
    // 玩法ID
    public String wanfaId = "";

    public int tuichutime = 0;

    // 客户端连接对象
    private TaurusClient client = null;

    private HuNanHongZhong huNanHongZhong = new HuNanHongZhong();

    private HuNanZhuanZhuan huNanZhuanZhuan = new HuNanZhuanZhuan();

    private HuNanFangPaoFa huNanFangPaoFa = new HuNanFangPaoFa();

    private HuNanPaoDeKuai huNanPaoDeKuai = new HuNanPaoDeKuai();

    private HuNanChangSha huNanChangSha = new HuNanChangSha();

   // private HuNanChangShaNew huNanChangShaNew = new HuNanChangShaNew();//新的机器人处理对象


    private TinHuChi tinHuChi = new TinHuChi();


    private Map<Integer, List<Integer>> playerOutcardsMap = new HashMap<>();


    private Map<Integer, List<Integer>> playerchisMap = new HashMap<>();

    private Map<Integer, List<Integer>> playerpengsMap = new HashMap<>();

    private Map<Integer, List<Integer>> playermingsMap = new HashMap<>();

    private Map<Integer, List<Integer>> playerzisMap = new HashMap<>();



    //圈子id
//    public static int groupId = 0;

    //房间id
//    public static String roomId = "";


    /**
     * TCP测试方法，用于建立客户端连接并处理游戏事件
     *
     * @throws Exception
     */
    public void tcp_test(int playerId, Integer pid, int groupId) throws Exception {
        Jedis jedis11 = Redis.use("group1_db11").getJedis();
        Jedis jedis0 = Redis.use().getJedis();
        String playKey = "g{" + groupId + "}:play:" + pid;


        try {
            Set<String> roomIds = jedis0.keys("room:*");
//            Set<String> roomIds = scanRooms(jedis0, "room:*");
            String roomKey = "";
            if (jedis11.hget(playKey, "leftover_robot") != null) {
                if (wanfaId.equals("")) {
                    Boolean is_match = false;
                    for (String id : roomIds) {
                        String roomId = id.substring(id.indexOf(":") + 1);
                        roomKey = "room:" + roomId;
                        String gpid = jedis0.hget(roomKey, "gpid");
                        String players = jedis0.hget(roomKey, "players");

                        if (gpid != null) {
                            if (Integer.parseInt(gpid) == pid) {
                                is_match = true;
                            }
//                            if (players.equals("[]")) {
//                                is_match = false;
//                            }
                        }
                    }
                    if (roomIds.size() == 0 || !is_match) {
                        ITObject object = null;
                        AccountBusiness accountBusiness = null;
                        accountBusiness = new AccountBusiness();
                        // 登录获取session跟token

                        if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) {


                            Set<String> keys1 = jedis0.keys("{user}:" + playerId + "_token");
                            if (keys1 == null) {
                                object = accountBusiness.idPasswordLogin(playerId, password);
                                ITObject validate = TObject.newInstance();
                                validate.putString("token", object.getString("token"));
                                token = object.getString("token");
                                session = accountBusiness.getSession();
                            } else {
                                Set<String> keys = jedis0.smembers("{user}:" + playerId + "_token");
                                List<String> keyList = new ArrayList<>(keys);
                                session = "{user}:" + playerId;
                                token = keyList.get(0);

                            }
                        } else {

                            object = accountBusiness.idPasswordLogin(playerId, password);
                            ITObject validate = TObject.newInstance();
                            validate.putString("token", object.getString("token"));
                            token = object.getString("token");
                            session = accountBusiness.getSession();
                        }



                        Object room = GroupRoomBusiness.matchRoom(groupId, pid, session, "Android", false);
                        String game = jedis0.hget(String.valueOf(room), "game");
//                        ITObject game_info = roomInfo.getTObject("game_info");
//                        Integer game_id = game_info.getInt("game_id");
                        wanfaId = String.valueOf(game);

                    }
                }
                //满人房间玩法
                List<String> manrenwanfa = new ArrayList<>();

                String[] playerIds2 = null;
                for (String id : roomIds) {
                    String roomId = id.substring(id.indexOf(":") + 1);
                    String roomKeys = "room:" + roomId;
                    if (jedis0.hget(roomKeys, "players") != null) {
                        String players = jedis0.hget(roomKeys, "players");
                        String players1 = players.substring(1, players.length() - 1);
                        playerIds2 = players1.split(",");
                        if (playerIds2.length == 2) {
                            manrenwanfa.add(jedis0.hget(roomKeys, "gpid"));
                        }
                    }
                }


                List<List<String>> xuyaojianlifangjian = new ArrayList<>();
                for (String id : roomIds) {
                    String roomId = id.substring(id.indexOf(":") + 1);
                    String roomKeys = "room:" + roomId;
                    if (jedis0.hget(roomKeys, "players") != null && jedis0.hget(roomKeys, "gpid") != null) {
                        String gpid = jedis0.hget(roomKeys, "gpid");
                        String players = jedis0.hget(roomKeys, "players");
                        if (players.equals("[]")) {
                            xuyaojianlifangjian.add(Arrays.asList(gpid, players));
                        } else {
                            String players1 = players.substring(1, players.length() - 1);
                            String[] playerIds9 = players1.split(",");
                            xuyaojianlifangjian.add(Arrays.asList(gpid, String.valueOf(playerIds9.length)));
                        }
                    }

                    if ( jedis0.hget(roomKeys, "gpid") != null){
                        String gpid = jedis0.hget(roomKeys, "gpid");
                        if (jedis0.hget(roomKeys, "players") == null) {
                            xuyaojianlifangjian.add(Arrays.asList(gpid, "5"));

                        }
                    }

                }



                Set<String> excludedKeys = xuyaojianlifangjian.stream()
                        .filter(list -> {
                            String value = list.get(1);
                            return value.equals("[]") || value.equals("1") || value.equals("5");
                        })
                        .map(list -> list.get(0))
                        .collect(Collectors.toSet());


                List<List<String>> filteredResult = xuyaojianlifangjian.stream()
                        .filter(list -> manrenwanfa.contains(list.get(0)))
                        .filter(list -> !excludedKeys.contains(list.get(0)))
                        .collect(Collectors.toList());


                List<String> keys10 = filteredResult.stream()
                        .map(list -> list.get(0))  // 获取每个list的第一个元素（key）
                        .collect(Collectors.toList());






                List<Integer> robotIdsList1 = new ArrayList<>();

                String sql3 = String.format("SELECT id FROM `account` WHERE jiqiren=9998 and start = 0");
                ITArray robotId3 = DataBase.use().executeQueryByTArray(sql3);

                for (int j = 0; j < robotId3.size(); j++) {
                    robotIdsList1.add(robotId3.getTObject(j).getInt("id"));
                }


                int userIndex = 0;
                for (String s : keys10) {

                    String groupKeys = "g{" + groupId + "}:play:" + s;
                    if (jedis11.hget(groupKeys, "leftover_robot") != null) {
                        String shengyu = jedis11.hget(groupKeys, "leftover_robot");
                        if (Integer.parseInt(shengyu) > 0 && userIndex < robotIdsList1.size()) {
                            Integer playerid = robotIdsList1.get(userIndex);
                            userIndex++;

                            ITObject object = null;
                            AccountBusiness accountBusiness = null;
                            accountBusiness = new AccountBusiness();

                            // 登录获取session跟token
                            if (jedis0.keys("{user}:" + playerid + "_token").size() != 0) {
                                Set<String> keys1 = jedis0.keys("{user}:" + playerid + "_token");
                                if (keys1 == null) {
                                    object = accountBusiness.idPasswordLogin(playerid, password);
                                    ITObject validate = TObject.newInstance();
                                    validate.putString("token", object.getString("token"));
                                    token = object.getString("token");
                                    session = accountBusiness.getSession();
                                } else {
                                    Set<String> keys = jedis0.smembers("{user}:" + playerid + "_token");
                                    List<String> keyList = new ArrayList<>(keys);
                                    session = "{user}:" + playerid;
                                    token = keyList.get(0);
                                }
                            } else {
                                object = accountBusiness.idPasswordLogin(playerid, password);
                                ITObject validate = TObject.newInstance();
                                validate.putString("token", object.getString("token"));
                                token = object.getString("token");
                                session = accountBusiness.getSession();
                            }


                            Object roomkey = GroupRoomBusiness.matchRoom(groupId, Integer.parseInt(s), session, "Android", false);
                            String game = jedis0.hget(String.valueOf(roomkey), "game");
                            wanfaId = String.valueOf(game);
                        }
                    }
                }

                String[] playerIds = null;
                String leftover_robot = jedis11.hget(playKey, "leftover_robot");
                if (Integer.parseInt(leftover_robot) > 0) {




                    //真人等机器人游戏id赋值
                    for (String id : roomIds) {
                        String roomId = id.substring(id.indexOf(":") + 1);
                        roomKey = "room:" + roomId;

                        String players = jedis0.hget(roomKey, "players");
                        String gpid = jedis0.hget(roomKey, "gpid");

                        String roKey = "g{" + groupId + "}:play:" + gpid;
                        String leftover_robot1 = jedis11.hget(roKey, "leftover_robot");

                        if (players != null && !players.equals("[]")) {
                            players = players.substring(1, players.length() - 1);
                            playerIds = players.split(",");
                            List<Integer> robotIdsList = new ArrayList<>();
                            //拿到所有的机器人
                            String sql2 = String.format("SELECT id FROM `account` WHERE jiqiren=9998");
                            ITArray robotId2 = DataBase.use().executeQueryByTArray(sql2);

                            for (int j = 0; j < robotId2.size(); j++) {
                                robotIdsList.add(robotId2.getTObject(j).getInt("id"));
                            }
                            for (String s : playerIds) {

                                if (leftover_robot1 != null) {
                                    if (playerIds.length == 1 && !robotIdsList.contains(Integer.parseInt(s)) && Integer.parseInt(leftover_robot1) > 0) {

                                        wanfaId = jedis0.hget(roomKey, "game");

                                    }
                                }
                            }
                        }
                    }


                    if (wanfaId.equals("")) {
                        for (String id : roomIds) {
                            String roomId = id.substring(id.indexOf(":") + 1);
                            String roomKeys1 = "room:" + roomId;
                            if (jedis0.hget(roomKeys1, "gpid") != null) {
                                String gpid = jedis0.hget(roomKeys1, "gpid");

                                if (pid == Integer.parseInt(gpid)) {
                                    wanfaId = jedis0.hget(roomKeys1, "game");
                                }
                            }
                        }
                    }

                    System.out.println(wanfaId);
                    if ("22".equalsIgnoreCase(wanfaId)) { //湖南红中麻将
                        client = new TaurusClient("8.138.242.190:6421", "game", TaurusClient.ConnectionProtocol.Tcp);
                    }

                    if ("10".equalsIgnoreCase(wanfaId)) {
                        client = new TaurusClient("127.0.0.1:6311", "game", TaurusClient.ConnectionProtocol.Tcp);
                    }
//
                    if ("66".equalsIgnoreCase(wanfaId)) {
                        client = new TaurusClient("8.138.242.190:6841", "game", TaurusClient.ConnectionProtocol.Tcp);
                    }
                    client.connect();
//                }

                    //连接根据不同的玩法id 配置不同的连接


                    //这里是机器人主动进入空房间
                    Set<String> roomIds1 = jedis0.keys("room:*");


                    for (String id : roomIds1) {
                        String roomId = id.substring(id.indexOf(":") + 1);
                        roomKey = "room:" + roomId;
                        if (jedis0.hget(roomKey, "gpid") != null) {
                            String gpid = jedis0.hget(roomKey, "gpid");
                            String playKey2 = "g{" + groupId + "}:play:" + gpid;

                            String roomPidKey = null;
                            boolean flag = false;
                            if (jedis0.hget(roomKey, "players") == null) {


                                roomKey = "room:" + roomId;
                                roomPidKey = jedis0.hget(roomKey, "gpid");

                                if (jedis0.hget(roomKey, "game") != null) {
                                    String gameId = jedis0.hget(roomKey, "game");

                                    if (wanfaId.equals(gameId)) {

                                        flag = true;
                                    }
                                }
                            }

                            String players = jedis0.hget(roomKey, "players");


                            if (jedis11.hget(playKey2, "leftover_robot") != null) {
                                String leftover_robot1 = jedis11.hget(playKey2, "leftover_robot");
                                if (players == null && Integer.parseInt(roomPidKey) == pid && Integer.parseInt(leftover_robot1) > 0 && flag) {


                                    ITObject object = null;
                                    AccountBusiness accountBusiness = null;
                                    accountBusiness = new AccountBusiness();
                                    // 登录获取session跟token
                                    if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) {
                                        Set<String> keys1 = jedis0.keys("{user}:" + playerId + "_token");
                                        if (keys1 == null) {
                                            object = accountBusiness.idPasswordLogin(playerId, password);
                                            ITObject validate = TObject.newInstance();
                                            validate.putString("token", object.getString("token"));
                                            token = object.getString("token");
                                            session = accountBusiness.getSession();
                                        } else {
                                            Set<String> keys = jedis0.smembers("{user}:" + playerId + "_token");
                                            List<String> keyList = new ArrayList<>(keys);
                                            session = "{user}:" + playerId;
                                            token = keyList.get(0);
                                        }
                                    } else {
                                        object = accountBusiness.idPasswordLogin(playerId, password);
                                        ITObject validate = TObject.newInstance();
                                        validate.putString("token", object.getString("token"));
                                        token = object.getString("token");
                                        session = accountBusiness.getSession();
                                    }

                                    String group = jedis0.hget(roomKey, "group");
                                    ITObject roomInfos = GroupRoomBusiness.joinRoom(Integer.parseInt(group), roomKey, session, null);
                                    joinRoom(playerId); //进入房间
                                    ready();  //准备
                                    String playKey1 = "g{" + groupId + "}:play:" + roomPidKey;


//                                    //增加使用数量
                                    Integer key = Integer.valueOf(roomPidKey);

                                    count.put(key, count.getOrDefault(key, 0) + 1);


                                    jedis11.hincrBy(playKey1, "leftover_robot", -1);
                                    String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 1, playerId);
                                    DataBase.use().executeUpdate(sql);


                                }
                            }
                        }


                        roomKey = "room:" + roomId;
                        if (jedis0.hget(roomKey, "gpid") != null) {
                            String gpid = jedis0.hget(roomKey, "gpid");
                            String playKey2 = "g{" + groupId + "}:play:" + gpid;

                            String roomPidKey = null;
                            boolean flag = false;
                            if (jedis0.hget(roomKey, "players") != null) {
                                if (jedis0.hget(roomKey, "players").equals("[]")) {

                                    roomKey = "room:" + roomId;
                                    roomPidKey = jedis0.hget(roomKey, "gpid");
                                    if (jedis0.hget(roomKey, "game") != null) {

                                        String gameId = jedis0.hget(roomKey, "game");
                                        if (wanfaId.equals(gameId)) {
                                            flag = true;
                                        }
                                    }
                                }
                                String players = jedis0.hget(roomKey, "players");


                                if (jedis11.hget(playKey2, "leftover_robot") != null) {
                                    String leftover_robot1 = jedis11.hget(playKey2, "leftover_robot");
                                    if (players.equals("[]") && Integer.parseInt(roomPidKey) == pid && Integer.parseInt(leftover_robot1) > 0 && flag) {

                                        ITObject object = null;
                                        AccountBusiness accountBusiness = null;
                                        accountBusiness = new AccountBusiness();
                                        // 登录获取session跟token
                                        if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) {
                                            Set<String> keys1 = jedis0.keys("{user}:" + playerId + "_token");
                                            if (keys1 == null) {
                                                object = accountBusiness.idPasswordLogin(playerId, password);
                                                ITObject validate = TObject.newInstance();
                                                validate.putString("token", object.getString("token"));
                                                token = object.getString("token");
                                                session = accountBusiness.getSession();
                                            } else {
                                                Set<String> keys = jedis0.smembers("{user}:" + playerId + "_token");
                                                List<String> keyList = new ArrayList<>(keys);
                                                session = "{user}:" + playerId;
                                                token = keyList.get(0);

                                            }
                                        } else {
                                            object = accountBusiness.idPasswordLogin(playerId, password);
                                            ITObject validate = TObject.newInstance();
                                            validate.putString("token", object.getString("token"));
                                            token = object.getString("token");
                                            session = accountBusiness.getSession();
                                        }

                                        String group = jedis0.hget(roomKey, "group");
                                        ITObject roomInfos = GroupRoomBusiness.joinRoom(Integer.parseInt(group), roomKey, session, null);
                                        joinRoom(playerId); //进入房间
                                        ready();  //准备
                                        String playKey1 = "g{" + groupId + "}:play:" + roomPidKey;


//                                    //增加使用数量
                                        Integer key = Integer.valueOf(roomPidKey);

                                        count.put(key, count.getOrDefault(key, 0) + 1);


                                        jedis11.hincrBy(playKey1, "leftover_robot", -1);
                                        String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 1, playerId);
                                        DataBase.use().executeUpdate(sql);


                                    }
                                }

                            }

                        }


                    }

                    // 添加事件监听器处理网络消息
                    client.addEventListener(TaurusClient.NetClientEvent.OnEvent, new IEventListener() {
                        @Override
                        public void handleEvent(Event event) {

                            // 获取 msg
                            Message message = (Message) event.getParameter("msg");
                            if (message == null) {
                                return;
                            }

                            ITObject param = message.param;

                            //回调协议号
                            String command = message.command;

                            //根据玩法id 调用不同的回调
                            if (StringUtil.isNotEmpty(command)) {
                                if ("93".equalsIgnoreCase(wanfaId)) { //扣点点
                                    if ("812".equalsIgnoreCase(command)) { //出牌广播
                                        sleepTime(1000);
                                        drawCard(command, message);
                                    } else if ("820".equalsIgnoreCase(command)) {
                                        changePlayer(command, message);
                                    } else if ("819".equalsIgnoreCase(command)) { //摸牌
                                        getCard(command, message);
                                    } else if ("811".equalsIgnoreCase(command)) { //初始化手牌
                                        cardInHead(command, message, wanfaId);
                                    } else if ("813".equalsIgnoreCase(command)) { //出牌，牌权
                                        sleepTime(2000);
                                        outCard(command, message, wanfaId);
                                    } else if ("817".equalsIgnoreCase(command)) {
                                        ready();
                                        //杠碰胡通知协议
                                    } else if ("814".equalsIgnoreCase(command)) {
                                        sleepTime(2000);
                                        actionCard(param);
                                        //doGang杠后补牌 补杠事件
                                    } else if ("838".equalsIgnoreCase(command)) {
                                        sleepTime(2000);
                                        buGang(param);
                                    }
                                } else if ("66".equalsIgnoreCase(wanfaId)) {//跑的快
                                    if ("2011".equalsIgnoreCase(command)) { //跑的快 初始化手牌
                                        huNanPaoDeKuai.paoDeKuaiCardInHead(param, client);
                                    } else if ("2021".equalsIgnoreCase(command)) {    //出牌广播
                                        huNanPaoDeKuai.paoDekuaiChupaiGuangBo(param);
                                    } else if ("2004".equalsIgnoreCase(command)) { //出牌提示事件，牌权
                                        Integer player = param.getInt("player");
                                        Integer seat1 = param.getInt("seat");

                                        if (seat1 != null) {
                                            huNanPaoDeKuai.seat = seat1;
                                        }

                                        //出牌
                                        huNanPaoDeKuai.outCard(client);
                                    } else if ("2007".equalsIgnoreCase(command)) { //结算准备
                                        //type为1 为大结算  type为0为小结算
                                        Integer type = param.getInt("type");

                                        if (type == 0) {
                                            huNanPaoDeKuai.getSeatRemainHistory().clear();
                                            huNanPaoDeKuai.getPaoDekuaiCardInhand().clear();
                                            ITArray card_list = huNanPaoDeKuai.getCard_list().getTArray("card_list");
                                            card_list.clear();
                                            ready();
                                        }

                                        if (type == 1) {
                                            Jedis jedis11s = Redis.use("group1_db11").getJedis();
                                            try {
                                                String key = "g{" + groupId + "}:play:" + pid;
                                                jedis11s.hincrBy(key, "leftover_robot", 1);
                                                String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId);
                                                try {
                                                    DataBase.use().executeUpdate(sql);
                                                } catch (SQLException e) {
                                                    e.printStackTrace();
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            } finally {
                                                jedis11s.close();
                                            }
                                        }

                                    } else if ("2009".equalsIgnoreCase(command)) {
                                        Jedis jedis21 = Redis.use().getJedis();
                                        sleepTime(3000);

                                        ITObject params = TObject.newInstance();
                                        String[] playerIds2 = null;


                                        Set<String> roomIds = jedis21.keys("room:*");
                                        String roomKey = "";
                                        //拿到所有的机器人
                                        List<Integer> robotIdsList = new ArrayList<>();
                                        String sql2 = "SELECT id FROM `account` WHERE jiqiren=9998";
                                        ITArray robotId2 = null;
                                        try {
                                            robotId2 = DataBase.use().executeQueryByTArray(sql2);
                                        } catch (SQLException e) {
                                            e.printStackTrace();
                                        }
                                        for (int j = 0; j < Objects.requireNonNull(robotId2).size(); j++) {
                                            robotIdsList.add(robotId2.getTObject(j).getInt("id"));
                                        }


                                        for (String roomId : roomIds) {
                                            String roomId1 = roomId.substring(roomId.indexOf(":") + 1);
                                            roomKey = "room:" + roomId1;

                                            if (jedis21.hget(roomKey, "players") != null) {
                                                String players = jedis21.hget(roomKey, "players");
                                                if (!players.equals("[]")) {
                                                    players = players.substring(1, players.length() - 1);
                                                    playerIds2 = players.split(",");


                                                    if (playerIds2.length == 1) {
                                                        for (String s : playerIds2) {
                                                            if (robotIdsList.contains(Integer.parseInt(s))) { //房间里的人是机器人
                                                                String gpid = jedis21.hget(roomKey, "gpid");
                                                                String gpId = jedis21.hget(roomKey, "group");
                                                                String key = "g{" + gpId + "}:play:" + gpid;
                                                                if (!players.equals("[]") && pid == Integer.parseInt(gpid)) {


                                                                    if (JiQiRens.count != null && JiQiRens.count.containsKey(Integer.parseInt(gpid))) {
                                                                        Integer currentValue = JiQiRens.count.get(Integer.parseInt(gpid));
                                                                        if (currentValue > 0) {
                                                                            JiQiRens.count.put(Integer.parseInt(gpid), currentValue - 1);
                                                                        }
                                                                    }


                                                                    Jedis jedis20 = Redis.use("group1_db11").getJedis();

                                                                    jedis20.hincrBy(key, "leftover_robot", 1);
                                                                    jedis20.close();
                                                                    String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, Integer.parseInt(s));

                                                                    try {
                                                                        DataBase.use().executeUpdate(sql);
                                                                    } catch (SQLException e) {
                                                                        e.printStackTrace();
                                                                    }

                                                                    client.send("1005", params, response -> {

                                                                    });

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        jedis21.close();

                                    } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用
                                        Set<String> roomIds = scanRooms(jedis0, "room:*");
                                        String[] playerIds = null;
                                        for (String roomId : roomIds) {
                                            String rid = roomId.substring(roomId.indexOf(":") + 1);
                                            String roomKey = "room:" + rid;
                                            if (jedis0.hget(roomKey, "players") != null) {
                                                String players = jedis0.hget(roomKey, "players");
                                                if (!players.equals("[]")) {
                                                    players = players.substring(1, players.length() - 1);
                                                    playerIds = players.split(",");
                                                    for (String pyids : playerIds) {
                                                        if (Integer.parseInt(pyids) == playerId) {
                                                            jedis0.del(roomId);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } else if ("2031".equalsIgnoreCase(command)) {
                                        ITObject params = TObject.newInstance();
                                        params.putInt("id", 0);
                                        client.send("1015", params, response -> {

                                        });

                                    }
                                } else if ("22".equalsIgnoreCase(wanfaId)) { //湖南红中麻将

                                    if ("812".equalsIgnoreCase(command)) { //出牌广播
                                        HuNanHongZhong.drawCard(command, message);
                                    } else if ("811".equalsIgnoreCase(command)) {//初始化手牌
                                        huNanHongZhong.cardInHead(command, message, client);
                                    } else if ("819".equalsIgnoreCase(command)) { //摸牌
                                        huNanHongZhong.getCard(command, message);
                                    } else if ("813".equalsIgnoreCase(command)) { //出牌，牌权
                                        huNanHongZhong.outCard(client);
                                    } else if ("817".equalsIgnoreCase(command)) {//结算
                                        huNanHongZhong.getHongZhongCardInhand().clear();
                                        huNanHongZhong.getChuGuoCardInhand().clear();

                                        Integer type = param.getInt("type");
                                        if (type == 1 || type == 2) { //为1为大结算 为2为解散
                                            Jedis jedis11s = Redis.use("group1_db11").getJedis();
                                            try {
                                                String key = "g{" + groupId + "}:play:" + pid;
                                                jedis11s.hincrBy(key, "leftover_robot", 1);
//
                                                if (count != null && count.containsKey(pid)) {
                                                    Integer currentValue = count.get(pid);
                                                    if (currentValue > 0) {
                                                        count.put(pid, currentValue - 1);
                                                    }
                                                }


                                                String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId);
                                                try {
                                                    DataBase.use().executeUpdate(sql);
                                                } catch (SQLException e) {
                                                    e.printStackTrace();
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            } finally {
                                                jedis11s.close();
                                            }

                                            if (count != null && count.containsKey(pid)) {
                                                Integer value = count.get(pid);

                                                // 如果找到了对应的 pid
                                                String shangxianRobot = jedis11.hget(playKey, "shangxian_robot");
                                                String leftoverRobot = jedis11.hget(playKey, "leftover_robot");

                                                if (shangxianRobot != null && leftoverRobot != null) {
                                                    if (value == 0) {
                                                        jedis11.hset(playKey, "leftover_robot", shangxianRobot);
                                                    }
                                                }
                                            }
                                        }
//                                        playerState.pongGroups.clear();;
//                                        playerState.handCards.clear();
//                                        playerState.chiGroups.clear();
//                                        playerState.gangGroups.clear();;


                                        ready();
                                    } else if ("2009".equalsIgnoreCase(command)) {
                                        Jedis jedis21 = Redis.use().getJedis();
                                        sleepTime(3000);
                                        ITObject params = TObject.newInstance();
                                        String[] playerIds2 = null;


                                        Set<String> roomIds = jedis21.keys("room:*");
                                        String roomKey = "";
                                        //拿到所有的机器人
                                        List<Integer> robotIdsList = new ArrayList<>();
                                        String sql2 = "SELECT id FROM `account` WHERE jiqiren=9998";
                                        ITArray robotId2 = null;
                                        try {
                                            robotId2 = DataBase.use().executeQueryByTArray(sql2);
                                        } catch (SQLException e) {
                                            e.printStackTrace();
                                        }
                                        for (int j = 0; j < Objects.requireNonNull(robotId2).size(); j++) {
                                            robotIdsList.add(robotId2.getTObject(j).getInt("id"));
                                        }


                                        for (String roomId : roomIds) {
                                            String roomId1 = roomId.substring(roomId.indexOf(":") + 1);
                                            roomKey = "room:" + roomId1;

                                            if (jedis21.hget(roomKey, "players") != null) {
                                                String players = jedis21.hget(roomKey, "players");
                                                if (!players.equals("[]")) {
                                                    players = players.substring(1, players.length() - 1);
                                                    playerIds2 = players.split(",");


                                                    if (playerIds2.length == 1) {
                                                        for (String s : playerIds2) {
                                                            if (robotIdsList.contains(Integer.parseInt(s))) { //房间里的人是机器人
                                                                String gpid = jedis21.hget(roomKey, "gpid");
                                                                String gpId = jedis21.hget(roomKey, "group");
                                                                String key = "g{" + gpId + "}:play:" + gpid;
                                                                if (!players.equals("[]") && pid == Integer.parseInt(gpid)) {


                                                                    if (JiQiRens.count != null && JiQiRens.count.containsKey(Integer.parseInt(gpid))) {
                                                                        Integer currentValue = JiQiRens.count.get(Integer.parseInt(gpid));
                                                                        if (currentValue > 0) {
                                                                            JiQiRens.count.put(Integer.parseInt(gpid), currentValue - 1);
                                                                        }
                                                                    }


                                                                    Jedis jedis20 = Redis.use("group1_db11").getJedis();

                                                                    jedis20.hincrBy(key, "leftover_robot", 1);
                                                                    jedis20.close();
                                                                    String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, Integer.parseInt(s));

                                                                    try {
                                                                        DataBase.use().executeUpdate(sql);
                                                                    } catch (SQLException e) {
                                                                        e.printStackTrace();
                                                                    }

                                                                    client.send("1005", params, response -> {

                                                                    });

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        jedis21.close();

                                    } else if ("814".equalsIgnoreCase(command)) {//杠碰胡通知协议
//                            sleepTime(2000);
                                        huNanHongZhong.actionCard(param, client);
                                    } else if ("820".equalsIgnoreCase(command)) {
                                        HuNanHongZhong.changePlayer(command, message);
                                    } else if ("815".equalsIgnoreCase(command)) { //服务器通知客户端有玩家执行了操作
                                        huNanHongZhong.shanchuchuguopai(param);
                                    } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用
//                                        Jedis jedis11s = Redis.use("group1_db11").getJedis();
//                                        try {
//                                            String key = "g{" + groupId + "}:play:" + pid;
//                                            jedis11s.hincrBy(key, "leftover_robot", 1);
//                                            String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId);
//                                            DataBase.use().executeUpdate(sql);
                                        Set<String> roomIds = scanRooms(jedis0, "room:*");
                                        String[] playerIds = null;
                                        for (String roomId : roomIds) {
                                            String rid = roomId.substring(roomId.indexOf(":") + 1);
                                            String roomKey = "room:" + rid;
                                            if (jedis0.hget(roomKey, "players") != null) {
                                                String players = jedis0.hget(roomKey, "players");
                                                if (!players.equals("[]")) {
                                                    players = players.substring(1, players.length() - 1);
                                                    playerIds = players.split(",");
                                                    for (String pyids : playerIds) {
                                                        if (Integer.parseInt(pyids) == playerId) {
                                                            jedis0.del(roomId);
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                } else if ("17".equalsIgnoreCase(wanfaId)) {  //字牌放炮罚

                                    if ("811".equalsIgnoreCase(command)) {  //初始化手牌
                                        huNanFangPaoFa.cardInHead(command, message, client);

                                    } else if ("819".equalsIgnoreCase(command)) { //摸牌
                                        huNanFangPaoFa.getCard(command, message);
                                    } else if ("813".equalsIgnoreCase(command)) {  //出牌 牌权
                                        sleepTime(1500);
                                        huNanFangPaoFa.outCard(client);
                                    } else if ("812".equalsIgnoreCase(command)) {  //出牌广播
                                        HuNanFangPaoFa.drawCard(command, message);
                                    } else if ("814".equalsIgnoreCase(command)) { //可执行的 操作 吃碰 偎提胡
                                        huNanFangPaoFa.actionCard(param, client);
                                    } else if ("817".equalsIgnoreCase(command)) { //结算
                                        huNanFangPaoFa.getFangPaoFaCardInhand().clear();
                                        ready();
                                    } else if ("822".equalsIgnoreCase(command)) { //放跑提示

                                        HuNanFangPaoFa.fangPaoTipEvent(message, client);
                                    } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用
                                        try {
                                            String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId);
                                            DataBase.use().executeUpdate(sql);

                                        } catch (SQLException e) {

                                        }
                                    }
                                } else if ("108".equalsIgnoreCase(wanfaId)) {//转转麻将
                                    if ("811".equalsIgnoreCase(command)) {//初始化收手牌
                                        huNanZhuanZhuan.cardInHead(command, message, client);
                                    } else if ("812".equalsIgnoreCase(command)) {//出牌广播
                                        HuNanZhuanZhuan.drawCard(command, message);
                                    } else if ("819".equalsIgnoreCase(command)) {//摸牌

                                        huNanZhuanZhuan.getCard(command, message);
                                    } else if ("813".equalsIgnoreCase(command)) {//出牌提示
//                                        sleepTime(1500);
                                        huNanZhuanZhuan.outCard(client);
                                    } else if ("814".equalsIgnoreCase(command)) {//放招提示
                                        huNanZhuanZhuan.actionCard(param, client);
                                    } else if ("817".equalsIgnoreCase(command)) {//结算
                                        huNanZhuanZhuan.getZhuanZhuanCardInhand().clear();
                                        huNanZhuanZhuan.getZhuanZhuanchuguopai().clear();
                                        ready();
                                    } else if ("815".equalsIgnoreCase(command)) { //服务器通知客户端有玩家执行了操作
                                        huNanZhuanZhuan.shanchuchuguopai(param);
                                    } else if ("820".equalsIgnoreCase(command)) {//换牌提示
                                        HuNanZhuanZhuan.changePlayer(command, message);
                                    } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用
                                        try {
                                            String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId);
                                            DataBase.use().executeUpdate(sql);
                                        } catch (SQLException e) {

                                        }
                                    }
                                } else if ("10".equalsIgnoreCase(wanfaId)) {
                                    //长沙麻将 机器人处理事件

                                    //[TCP->822] data:{"tip_list":[{"type":8,"id":1,"opcard":[],"weight":8,"card":0}],"types":[{"type":21,"value":1}]}
                                    //板胡Event [TCP->823] data:{"type":8,"seat":1,"data":[{"opcard":[204,204,204,108,108,108],"type":21,"value":1}]}
                                    if ("811".equalsIgnoreCase(command)) {//初始化收手牌
                                        huNanChangSha.cardInHead(command, message, client);
                                    } else if ("812".equalsIgnoreCase(command)) {//出牌广播
                                        //{"opzicards":[{"opzicards":[],"playerId":101555}],"opmingcards":[{"opmingcards":[],"playerId":101555}],"outcard_map":[{"outcards":[209,205],"playerId":101555},{"outcards":[],"playerId":112233}],"card":205,"opchicards":[{"opchicards":[105,103],"playerId":101555}],"oppengcards":[{"oppengcards":[],"playerId":101555}],"seat":1}
                                        ITArray outcard_map = param.getTArray("outcard_map");
                                        ITArray opchicards = param.getTArray("opchicards");
                                        ITArray oppengcards = param.getTArray("oppengcards");
                                        ITArray opmingcards = param.getTArray("opmingcards");
                                        ITArray opzicards = param.getTArray("opzicards");

                                        // 清空旧数据，用新数据完全覆盖
                                        playerOutcardsMap.clear();
                                        playerchisMap.clear();
                                        playerpengsMap.clear();
                                        playermingsMap.clear();
                                        playerzisMap.clear();
                                        //出过的牌
                                        if (outcard_map != null) {
                                            for (int i = 0; i < outcard_map.size(); i++) {
                                                ITObject playerData = outcard_map.getTObject(i);
                                                int playerId = playerData.getInt("playerId");
                                                ITArray outcardsArray = playerData.getTArray("outcards");

                                                // 转换为List<Integer>
                                                List<Integer> outcardsList = new ArrayList<>();
                                                for (int j = 0; j < outcardsArray.size(); j++) {
                                                    outcardsList.add(outcardsArray.getInt(j));
                                                }

                                                // 存储到Map中（覆盖旧数据）
                                                playerOutcardsMap.put(playerId, outcardsList);

                                            }
                                        }

                                        //吃的牌
                                        if (opchicards != null) {
                                            for (int i = 0; i < opchicards.size(); i++) {
                                                ITObject playerData = opchicards.getTObject(i);
                                                int playerId = playerData.getInt("playerId");
                                                ITArray outchiArray = playerData.getTArray("opchicards");

                                                List<Integer> outchiList = new ArrayList<>();
                                                for (int j = 0; j < outchiArray.size(); j++) {
                                                    outchiList.add(outchiArray.getInt(j));
                                                }
                                                playerchisMap.put(playerId, outchiList);
                                            }
                                        }

                                        //碰的牌
                                        if (oppengcards != null) {
                                            for (int i = 0; i < oppengcards.size(); i++) {
                                                ITObject playerData = oppengcards.getTObject(i);
                                                int playerId = playerData.getInt("playerId");
                                                ITArray outpengArray = playerData.getTArray("oppengcards");

                                                List<Integer> outpengList = new ArrayList<>();
                                                for (int j = 0; j < outpengArray.size(); j++) {
                                                    outpengList.add(outpengArray.getInt(j));
                                                }
                                                playerpengsMap.put(playerId, outpengList);
                                            }
                                        }

                                        //明杠的牌
                                        if (opmingcards != null) {
                                            for (int i = 0; i < opmingcards.size(); i++) {
                                                ITObject playerData = opmingcards.getTObject(i);
                                                int playerId = playerData.getInt("playerId");
                                                ITArray outmingArray = playerData.getTArray("opmingcards");

                                                List<Integer> outmingList = new ArrayList<>();
                                                for (int j = 0; j < outmingArray.size(); j++) {
                                                    outmingList.add(outmingArray.getInt(j));
                                                }
                                                playermingsMap.put(playerId, outmingList);
                                            }
                                        }

                                        //暗杠的牌
                                        if (opzicards != null) {
                                            for (int i = 0; i < opzicards.size(); i++) {
                                                ITObject playerData = opzicards.getTObject(i);
                                                int playerId = playerData.getInt("playerId");
                                                ITArray outziArray = playerData.getTArray("opzicards");

                                                List<Integer> outziList = new ArrayList<>();
                                                for (int j = 0; j < outziArray.size(); j++) {
                                                    outziList.add(outziArray.getInt(j));
                                                }
                                                playerzisMap.put(playerId, outziList);
                                            }
                                        }

                                        HuNanChangSha.drawCard(command, message);
                                    } else if ("819".equalsIgnoreCase(command)) {
                                        //摸牌
                                        huNanChangSha.getCard(command, message);
                                    } else if ("813".equalsIgnoreCase(command)) {//出牌提示
                                        huNanChangSha.outCard(client,playerOutcardsMap,playerchisMap,playerpengsMap,playermingsMap,playerzisMap);
                                    } else if ("814".equalsIgnoreCase(command)) {
                                        //放招提示
                                        huNanChangSha.actionCard(param, client);

                                    } else if ("2009".equalsIgnoreCase(command)) {
                                        Jedis jedis22 = Redis.use().getJedis();
                                        sleepTime(3000);

                                        ITObject params = TObject.newInstance();
                                        String[] playerIds2 = null;


                                        Set<String> roomIds = jedis22.keys("room:*");
                                        String roomKey = "";
                                        //拿到所有的机器人
                                        List<Integer> robotIdsList = new ArrayList<>();
                                        String sql2 = "SELECT id FROM `account` WHERE jiqiren=9998";
                                        ITArray robotId2 = null;
                                        try {
                                            robotId2 = DataBase.use().executeQueryByTArray(sql2);
                                        } catch (SQLException e) {
                                            e.printStackTrace();
                                        }
                                        for (int j = 0; j < Objects.requireNonNull(robotId2).size(); j++) {
                                            robotIdsList.add(robotId2.getTObject(j).getInt("id"));
                                        }


                                        for (String roomId : roomIds) {
                                            String roomId1 = roomId.substring(roomId.indexOf(":") + 1);
                                            roomKey = "room:" + roomId1;

                                            if (jedis22.hget(roomKey, "players") != null) {
                                                String players = jedis22.hget(roomKey, "players");
                                                if (!players.equals("[]")) {
                                                    players = players.substring(1, players.length() - 1);
                                                    playerIds2 = players.split(",");


                                                    if (playerIds2.length == 1) {
                                                        for (String s : playerIds2) {
                                                            if (robotIdsList.contains(Integer.parseInt(s))) { //房间里的人是机器人
                                                                String gpid = jedis22.hget(roomKey, "gpid");
                                                                String gpId = jedis22.hget(roomKey, "group");
                                                                String key = "g{" + gpId + "}:play:" + gpid;
                                                                if (!players.equals("[]") && pid == Integer.parseInt(gpid)) {


                                                                    if (JiQiRens.count != null && JiQiRens.count.containsKey(Integer.parseInt(gpid))) {
                                                                        Integer currentValue = JiQiRens.count.get(Integer.parseInt(gpid));
                                                                        if (currentValue > 0) {
                                                                            JiQiRens.count.put(Integer.parseInt(gpid), currentValue - 1);
                                                                        }
                                                                    }

                                                                    Jedis jedis20 = Redis.use("group1_db11").getJedis();

                                                                    jedis20.hincrBy(key, "leftover_robot", 1);
                                                                    jedis20.close();
                                                                    String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, Integer.parseInt(s));

                                                                    try {
                                                                        DataBase.use().executeUpdate(sql);
                                                                    } catch (SQLException e) {
                                                                        e.printStackTrace();
                                                                    }

                                                                    client.send("1005", params, response -> {

                                                                    });

                                                                }
                                                            }
                                                        }

                                                    }
                                                }
                                            }
                                        }

                                        jedis22.close();
                                    } else if ("817".equalsIgnoreCase(command)) {//结算
                                        huNanChangSha.getChangShaCardInhand().clear();
                                        huNanChangSha.getChuGuoCardInhand().clear();
                                        huNanChangSha.getpongGroup().clear();
                                        huNanChangSha.getchowGroup().clear();
                                        TinHuChi.lastTingCount = 0;
                                        TinHuChi.isMoreThanLast = false;
                                        ChangShaSuanFaTest.isTin=false;
                                        ChangShaSuanFaTest.isChi=false;
                                        ChangShaSuanFaTest.isPeng=false;
                                        ChangShaSuanFaTest.tinCards.clear();
                                        Integer type = param.getInt("type");
                                        if (type == 1 || type == 2) { //为1为大结算 为2为解散
                                            Jedis jedis11s = Redis.use("group1_db11").getJedis();
                                            try {
                                                String key = "g{" + groupId + "}:play:" + pid;
                                                jedis11s.hincrBy(key, "leftover_robot", 1);
//
                                                if (count != null && count.containsKey(pid)) {
                                                    Integer currentValue = count.get(pid);
                                                    if (currentValue > 0) {
                                                        count.put(pid, currentValue - 1);
                                                    }
                                                }


                                                String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId);
                                                try {
                                                    DataBase.use().executeUpdate(sql);
                                                } catch (SQLException e) {
                                                    e.printStackTrace();
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            } finally {
                                                jedis11s.close();
                                            }

                                            if (count != null && count.containsKey(pid)) {
                                                Integer value = count.get(pid);

                                                // 如果找到了对应的 pid
                                                Jedis jedis12 = Redis.use("group1_db11").getJedis();

                                                String shangxianRobot = jedis12.hget(playKey, "shangxian_robot");
                                                String leftoverRobot = jedis12.hget(playKey, "leftover_robot");

                                                if (shangxianRobot != null && leftoverRobot != null) {
                                                    if (value == 0) {
                                                        jedis12.hset(playKey, "leftover_robot", shangxianRobot);
                                                    }
                                                }
                                                jedis12.close();
                                            }
                                        }
//                                        playerState.pongGroups.clear();;
//                                        playerState.handCards.clear();
//                                        playerState.chiGroups.clear();
//                                        playerState.gangGroups.clear();;


                                        ready();
                                        //写定时器

                                    } else if ("815".equalsIgnoreCase(command)) { //服务器通知客户端有玩家执行了操作
                                        //[TCP->815] data:{"playerid":101555,"card":104,"opcard":[105,103],"from_seat":2,"type":1,"opengang":false}
                                        huNanChangSha.shanchuchuguopai(param);
                                    } else if ("820".equalsIgnoreCase(command)) {//换牌提示
                                        huNanChangSha.changePlayer(command, message);
                                    } else if ("2008".equalsIgnoreCase(command)) { //解散房间时候恢复机器人账号可以使用
//                                        Jedis jedis11s = Redis.use("group1_db11").getJedis();
//                                        String key = "g{" + groupId + "}:play:" + pid;
//
//                                        jedis11s.hincrBy(key, "leftover_robot", 1);
//                                        jedis11s.close();
//                                        try {
//
                                        Set<String> roomIds = scanRooms(jedis0, "room:*");
                                        String[] playerIds = null;
                                        for (String roomId : roomIds) {
                                            String rid = roomId.substring(roomId.indexOf(":") + 1);
                                            String roomKey = "room:" + rid;

                                            if (jedis0.hget(roomKey, "players") != null) {
                                                String players = jedis0.hget(roomKey, "players");

                                                if (!players.equals("[]")) {
                                                    players = players.substring(1, players.length() - 1);
                                                    playerIds = players.split(",");

                                                    for (String pyids : playerIds) {

                                                        if (Integer.parseInt(pyids) == playerId) {
                                                            jedis0.del(roomId);
                                                        }
                                                    }
                                                }
                                            }
                                        }


                                    } else if ("825".equalsIgnoreCase(command)) {
                                        ITObject params = TObject.newInstance();
                                        params.putInt("qi", 0);
                                        params.putInt("id", 1);
                                        client.send("612", params, response -> {

                                        });
                                    } else if ("822".equalsIgnoreCase(command)) {
                                        ITObject params = TObject.newInstance();
                                        //params.putInt("qi", 0);
                                        params.putInt("id", 1);
                                        //[TCP->822] data:{"tip_list":[{"type":8,"id":1,"opcard":[],"weight":8,"card":0}],"types":[{"type":21,"value":1}]}
                                        //板胡Event [TCP->823] data:{"type":8,"seat":1,"data":[{"opcard":[204,204,204,108,108,108],"type":21,"value":1}]}

                                        client.send("612", params, response -> {

                                        });
                                    } else if ("835".equalsIgnoreCase(command)) { //听牌天听
                                        ITObject params = TObject.newInstance();
                                        params.putInt("qi", 0);
                                        params.putInt("id", 1);
                                        client.send("612", params, response -> {

                                        });

                                    }


                                    //END 长沙麻将
                                }
                            }
                        }
                    });
                    // 添加连接状态监听器
                    client.addEventListener(TaurusClient.NetClientEvent.Connect, new

                            IEventListener() {
                                @Override
                                public void handleEvent(Event event) {
                                    SocketCode code = (SocketCode) event.getParameter("code");
                                    if (code == SocketCode.Connect) {

                                    } else {
//
                                        //重连

//                                        if ("22".equalsIgnoreCase(wanfaId)) { //湖南红中麻将
//                                            client = new TaurusClient("8.138.242.190:6421", "game", TaurusClient.ConnectionProtocol.Tcp);
//                                        }
//
//                                        if ("10".equalsIgnoreCase(wanfaId)) {
//                                            client = new TaurusClient("127.0.0.1:6311", "game", TaurusClient.ConnectionProtocol.Tcp);
//                                        }
////
//                                        if ("66".equalsIgnoreCase(wanfaId)) {
//                                            client = new TaurusClient("8.138.242.190:6841", "game", TaurusClient.ConnectionProtocol.Tcp);
//                                        }
//                                        client.connect();

                                    }
                                }
                            });


                    //这里是机器人主动找真人房间进入
                    for (String id : roomIds) {
                        String roomId = id.substring(id.indexOf(":") + 1);
                        roomKey = "room:" + roomId;
                        if (jedis0.hget(roomKey, "gpid") != null) {
                            String gpid = jedis0.hget(roomKey, "gpid");
                            String players1 = jedis0.hget(roomKey, "players");

                            if (players1 != null && !players1.equals("[]")) {

                                String players = jedis0.hget(roomKey, "players");
                                players = players.substring(1, players.length() - 1);

                                String[] playerIds1 = players.split(",");

                                String sql2 = "SELECT id FROM `account` WHERE jiqiren=9998";
                                ITArray robotId2 = DataBase.use().executeQueryByTArray(sql2);

                                String maxPlayers = jedis0.hget(roomKey, "maxPlayers");
                                if (Integer.parseInt(maxPlayers) == 2) {
                                    if (playerIds1.length == 1) {
                                        //循环playerIds
                                        for (int i = 0; i < playerIds1.length; i++) {
                                            String playeid = playerIds1[i];
                                            List<Integer> robotIdsList = new ArrayList<>();

                                            for (int j = 0; j < robotId2.size(); j++) {
                                                robotIdsList.add(robotId2.getTObject(j).getInt("id"));
                                            }

                                            roomKey = "room:" + roomId;
                                            String gpid2 = jedis0.hget(roomKey, "gpid");
                                            String playKey2 = "g{" + groupId + "}:play:" + gpid2;
                                            String leftover_robot1 = jedis11.hget(playKey2, "leftover_robot");

                                            if (!robotIdsList.contains(Integer.parseInt(playeid)) && Integer.parseInt(gpid2) == pid && Integer.parseInt(leftover_robot1) > 0) {
                                                ITObject object = null;
                                                AccountBusiness accountBusiness = null;
                                                accountBusiness = new AccountBusiness();
                                                // 登录获取session跟token

                                                if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) {

                                                    Set<String> keys1 = jedis0.keys("{user}:" + playerId + "_token");
                                                    if (keys1 == null) {
                                                        object = accountBusiness.idPasswordLogin(playerId, password);
                                                        ITObject validate = TObject.newInstance();
                                                        validate.putString("token", object.getString("token"));
                                                        token = object.getString("token");
                                                        session = accountBusiness.getSession();
                                                    } else {
                                                        Set<String> keys = jedis0.smembers("{user}:" + playerId + "_token");
                                                        List<String> keyList = new ArrayList<>(keys);
                                                        session = "{user}:" + playerId;
                                                        token = keyList.get(0);

                                                    }
                                                } else {

                                                    object = accountBusiness.idPasswordLogin(playerId, password);
                                                    ITObject validate = TObject.newInstance();
                                                    validate.putString("token", object.getString("token"));
                                                    token = object.getString("token");
                                                    session = accountBusiness.getSession();
                                                }


                                                String readyTime = jedis0.hget(roomKey, "readyTime");
//                                                long readyTime1 = Long.parseLong(readyTime);
                                                //判断如果readyTime已经过去七秒

                                                //判断准备时间，只是要取出准备时间超过七秒的房间
//                                                if (System.currentTimeMillis() - readyTime1 > 1000) {
                                                String roomKey1 = "room:" + roomId;
                                                String group = jedis0.hget(roomKey1, "group");
                                                ITObject roomInfos = GroupRoomBusiness.joinRoom(Integer.parseInt(group), roomKey1, session, null);
                                                joinRoom(playerId); //进入房间
                                                ready();  //准备
                                                String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 1, playerId);
                                                DataBase.use().executeUpdate(sql);
                                                String playKey1 = "g{" + groupId + "}:play:" + pid;

                                                //增加使用数量
                                                Integer key = Integer.valueOf(pid);

                                                count.put(key, count.getOrDefault(key, 0) + 1);

                                                jedis11.hincrBy(playKey1, "leftover_robot", -1);
//                                                }
                                            }

                                        }
                                    }
                                }
                            }
                        }

                    }


//                    ready();  //准备
                }
            }


        } catch (Exception e) {

            e.printStackTrace();
        } finally {

            jedis11.close();
            jedis0.close();
        }

    }


    /**
     * 出牌广播协议 812
     *
     * @param command 协议号
     * @param message 消息对象
     * @return
     */
    public String drawCard(String command, Message message) {
        if (command.equalsIgnoreCase("812")) {
            ITObject param = message.param;
            if (param == null) {
                return null;
            }
            card = param.getString("card");

        }
        return null;
    }

    /**
     * 位置转换协议 820
     *
     * @param command 协议号
     * @param message 消息对象
     * @return
     */
    public static String changePlayer(String command, Message message) {
        if (command.equalsIgnoreCase("820")) {
            ITObject param = message.param;
            if (param == null) {
                return null;
            }

//			{seat=2}

        }
        return null;
    }

    /**
     * 摸牌协议 819
     *
     * @param command 协议号
     * @param message 消息对象
     * @return
     */
    public static String getCard(String command, Message message) {
        if (command.equalsIgnoreCase("819")) {
            ITObject param = message.param;
            if (param == null) {
                return null;
            }
//            {seat=2, Ishupai=0, isBaoTing=-1, tingcard=0, isgang=0, card=101, left_count=106}

            if (param.getInt("seat") != null && seat == param.getInt("seat")) {
                cardInhand.add(param.getInt("card"));
//                cardInhand.add(104);
            }
        }
        return null;
    }

    /**
     * 扣点点 初始化手牌协议 811
     *
     * @param command 协议号
     * @param message 消息对象
     * @param wanfaId 玩法ID
     * @return
     */
    public String cardInHead(String command, Message message, String wanfaId) {
        if (command.equalsIgnoreCase("811")) {
            ITObject param = message.param;
            if (param == null) {
                return null;
            }
//            {bank_seat=1, laiziCard=0, laiziCard2=0, laiziCard2Before=0, jing=0, laiziCardBefore=0, card_list=[101, 103, 104, 201, 204, 207, 208, 209, 307, 309, 501, 502, 503]}
            ITArray cardList = param.getTArray("card_list");
            for (int i = 0; i < cardList.size(); i++) {
                cardInhand.add(cardList.getInt(i));
            }
            if (cardInhand.size() > 13) {
                outCard(command, message, wanfaId);


            }


        }
        return null;
    }

    /**
     * 出牌方法
     *
     * @param command 协议号
     * @param message 消息对象
     * @param wanfaId 玩法ID
     * @return
     */
    public String outCard(String command, Message message, String wanfaId) {




        ITObject params = TObject.newInstance();
        params.putString("session", session + "," + token);
        params.putInt("card1", 0);
        params.putInt("card", cardInhand.get(0));
        cardInhand.remove(0);

        client.send("611", params, response -> {

        });
        return null;
    }

    /**
     * 处理杠碰胡操作
     *
     * @param param 消息参数
     * @return
     */
    public String actionCard(ITObject param) {
        //获取碰杠胡参数 type  和id 后续算法接入，是否能让碰和杠
        ITArray tipList = param.getTArray("tip_list");
        int id = 0;
        int type = 0;
        int opcard = 0;
        ITObject params = TObject.newInstance();
        if (tipList != null && tipList.size() > 0) {
            TObject firstTip = (TObject) tipList.get(0).getObject();
            id = firstTip.getInt("id");
            type = firstTip.getInt("type");
            opcard = firstTip.getTArray("opcard").getInt(0);


        }
        //弃 是根据算法选择是否要弃掉 不进行碰杠胡
        //params.putInt("qi", 0);
        //params.putInt("id", 0);

        //执行碰牌
        if (type == 2) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(cardInhand, opcard, 2);

//            Global.logger.info("删除碰的牌");
            //执行胡牌
        } else if (type == 6) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);

            //执行吃杠
        } else if (type == 3) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(cardInhand, opcard, 3);

            //执行自杠
        } else if (type == 4) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(cardInhand, opcard, 4);

            // 碰后补杠
        } else if (type == 5) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(cardInhand, opcard, 1);

        }

//        cardInhand.remove(0);
//        cardInhand.remove(1);


        client.send("612", params, response -> {

        });
        return null;
    }

    // 优化方案：使用 scan 替代 keys
    public Set<String> scanRooms(Jedis jedis, String pattern) {
        Set<String> keys = new HashSet<>();
        String cursor = "0";
        ScanParams scanParams = new ScanParams().match(pattern).count(100);

        do {
            ScanResult<String> scanResult = jedis.scan(cursor, scanParams);
            keys.addAll(scanResult.getResult());
            cursor = String.valueOf(scanResult.getCursor());
        } while (!cursor.equals("0"));

        return keys;
    }

    /**
     * 处理补杠操作
     *
     * @param param 消息参数
     */
    public void buGang(ITObject param) {
        Integer card = param.getInt("card");
        ITObject params = TObject.newInstance();
        params.putInt("card", card);
        client.send("839", params, response -> {

        });
    }


    /**
     * 准备方法
     *
     * @return
     */
    public String ready() {
        try {
            // 添加1秒延迟
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        cardInhand = new ArrayList<Integer>();
//        HuNanHongZhong.hongZhongCardInhand();
//        HuNanFangPaoFa.fangPaoFaCardInhand();

        ITObject params = TObject.newInstance();
        params.putString("session", session + "," + token);

        client.send("1003", params, new ICallback<MessageResponse>() {

            @Override
            public void action(MessageResponse messageResponse) {


            }
        });
        return null;
    }


    /**
     * 加入房间方法
     *
     * @return
     */
    public String joinRoom(int playerId) {
        try {
            // 添加2秒延迟
            Thread.sleep(5000);

            ITObject params = TObject.newInstance();
            params.putString("session", session + "," + token);

            client.send("1002", params, response -> {
                ITObject obj = response.messageData.param.getTObject("tableInfo");
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 线程休眠方法
     *
     * @param time 休眠时间(毫秒)
     */
    public static void sleepTime(int time) {
        try {
            // 添加延迟
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 程序入口点
     *
     * @param args
     * @throws Exception
     */
//    public static void main(String[] args) throws Exception {
//        try {
//            PluginService.me().loadConfig();
//        } catch (Exception e1) {
//            e1.printStackTrace();
//        }
//
////		NetManager.debug_print = false;
////		NetManager.TIMEOUT_TIME = 10;
////		NetManager.VERSION = 10;
//
//        tcp_test();
//
//
//        while (true) {
//            NetManager.processEvents();
//            try {
//                Thread.sleep(8);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
//    }
}
