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.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 java.sql.SQLException;
import java.util.*;

public class JiQiRens {

    // 扣点点玩家手牌
    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();


    //圈子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
                        System.out.println("6666666666666666666666666666666666666");
                        if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) {
                            System.out.println("playetid +++++++++++++" + playerId);
                            System.out.println("5555555555555555555555555555555555555");
                            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);
                                System.out.println("token ++++++++++++++++++++++" + token);
                            }
                        } else {
                            System.out.println("4777777777777777777777777");
                            object = accountBusiness.idPasswordLogin(playerId, password);
                            ITObject validate = TObject.newInstance();
                            validate.putString("token", object.getString("token"));
                            token = object.getString("token");
                            session = accountBusiness.getSession();
                        }


                        System.out.println("session" + session);
                        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);

                    }
                }

                String leftover_robot = jedis11.hget(playKey, "leftover_robot");
                if (Integer.parseInt(leftover_robot) > 0) {
                    String[] playerIds = null;
                    for (String id : roomIds) {
                        String roomId = id.substring(id.indexOf(":") + 1);
                        roomKey = "room:" + roomId;
                        if (jedis0.exists(roomKey)) {
                            String players = jedis0.hget(roomKey, "players");

                            if (players != null) {
                                players = players.substring(1, players.length() - 1);

                                playerIds = players.split(",");

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

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

                                String roomIdgpid = null;
                                if (leftover_robot1 != null) {
                                    if (playerIds.length == 2 && Integer.parseInt(leftover_robot1) > 0) {
                                        roomKey = "room:" + roomId;
                                        System.out.println("roomKey+++++ " + roomKey);
                                        roomIdgpid = jedis0.hget(roomKey, "gpid");
                                    }

                                    boolean isnull=false;
                                    for (String s : roomIds) {
                                        String roomId1 = s.substring(s.indexOf(":") + 1);
                                        String roomKey1 = "room:" + roomId1;
                                        String players1 = jedis0.hget(roomKey1, "players");
                                        if (Integer.parseInt(leftover_robot1) > 0 && players1.equals("[]")) {
                                            roomKey = "room:" + roomId;
                                            System.out.println("roomKey+++++ " + roomKey);
                                            roomIdgpid = jedis0.hget(roomKey, "gpid");
                                            if (Integer.parseInt(gpid) == Integer.parseInt(roomIdgpid)){
                                                isnull=true;
                                            }
                                        }
                                    }



                                    if (playerIds.length == 2 && Integer.parseInt(leftover_robot1) > 0 && Integer.parseInt(gpid) == Integer.parseInt(roomIdgpid) && wanfaId.equals("") && !isnull) {
                                        ITObject object = null;
                                        AccountBusiness accountBusiness = null;
                                        accountBusiness = new AccountBusiness();
                                        // 登录获取session跟token
                                        System.out.println("6666666666666666666666666666666666666");
                                        if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) {
                                            System.out.println("playetid +++++++++++++" + playerId);
                                            System.out.println("5555555555555555555555555555555555555");
                                            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);
                                                System.out.println("token ++++++++++++++++++++++" + token);
                                            }
                                        } else {
                                            System.out.println("4777777777777777777777777");
                                            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(roomIdgpid), session, "Android", false);

                                        String game = jedis0.hget(String.valueOf(roomkey), "game");
//                                      ITObject game_info = roomInfo.getTObject("game_info");
//                                      Integer game_id = game_info.getInt("game_id");
                                        wanfaId = String.valueOf(game);
                                        System.out.println("===========wanfaId55555555555========" + wanfaId);
                                    }
                                }
                            }
                        }
                    }



                    //真人等机器人游戏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) {
                                System.out.println("===========playerIds.length============" + playerIds.length);
                                System.out.println("--------------robotIdsList---------" + robotIdsList);
                                System.out.println("--------------playerIds-----------" + Arrays.toString(playerIds));
                                System.out.println("ssssssss " + s);
                                if (leftover_robot1 != null) {
                                    if (playerIds.length == 1 && !robotIdsList.contains(Integer.parseInt(s)) && Integer.parseInt(leftover_robot1) > 0) {
                                        System.out.println("---------------进入---------------");
                                        wanfaId = jedis0.hget(roomKey, "game");
                                        System.out.println("===========wanfaId4444444========" + wanfaId);
                                    }
                                }
                            }
                        }
                    }

//                if (!client.isConnected()) {
//                    if (wanfaId == null) {
//                    wanfaId = "10";
//                 }
                    System.out.println("wwwwwwwww" + wanfaId);

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

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

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


                    System.out.println("这里是连接+++++++++9999999999999999999999999999999999999999999++++" + wanfaId);


                    //这里是机器人主动进入空房间
                    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 leftover_robot1 = jedis11.hget(playKey2, "leftover_robot");
                            String roomPidKey = null;
                            if (jedis0.hget(roomKey, "players") == null || jedis0.hget(roomKey, "players").equals("[]")) {
                                System.out.println("这里是机器人主动进入空房间11111");

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

                            String players = jedis0.hget(roomKey, "players");
                            System.out.println("这里是机器人主动进入空房间2222");
                            if (leftover_robot1 != null) {
                                if ((players == null || players.equals("[]")) && Integer.parseInt(gpid) == Integer.parseInt(Objects.requireNonNull(roomPidKey)) && Integer.parseInt(leftover_robot1) > 0) {
                                    System.out.println("这里是机器人主动进入空房间4444");
                                    ITObject object = null;
                                    AccountBusiness accountBusiness = null;
                                    accountBusiness = new AccountBusiness();
                                    // 登录获取session跟token
                                    System.out.println("6666666666666666666666666666666666666");
                                    if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) {
                                        System.out.println("playetid +++++++++++++" + playerId);
                                        System.out.println("5555555555555555555555555555555555555");
                                        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);
                                            System.out.println("token ++++++++++++++++++++++" + token);
                                        }
                                    } else {
                                        System.out.println("4777777777777777777777777");
                                        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) {
                            System.out.println("监听 ++++++++++++++++++++++++++++++++++++++++++++");
                            // 获取 msg
                            Message message = (Message) event.getParameter("msg");
                            if (message == null) {
                                return;
                            }

                            ITObject param = message.param;
                            System.out.println("param+++++++++++++++++++" + param);
                            //回调协议号
                            String command = message.command;
                            System.out.println("command ++++++++++++++" + 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");
                                        System.out.println("跑的快seat1 77777777777777777777777777" + seat1);
                                        System.out.println("跑的快palyer6666666666666666666666666" + player);
                                        if (seat1 != null) {
                                            huNanPaoDeKuai.seat = seat1;
                                        }

                                        //出牌
                                        huNanPaoDeKuai.outCard(client);
                                    } else if ("2007".equalsIgnoreCase(command)) { //结算准备
                                        //type为1 为大结算  type为0为小结算
                                        Integer type = param.getInt("type");
                                        System.out.println("type ++++++++++++++++++++++++" + 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)) {
                                        for (int i = 0; i < 7; i++) {
                                            sleepTime(1000);
                                            if (i == 6) {
                                                System.out.println("跑得快发起 1005");
                                                ITObject params = TObject.newInstance();
                                                String[] playerIds2 = null;
                                                Set<String> roomIds = jedis0.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;
                                                    System.out.println("roomKey +++++++++++++++++" + roomKey);
                                                    if (jedis0.hget(roomKey, "players") != null) {
                                                        String players = jedis0.hget(roomKey, "players");
                                                        if (!players.equals("[]")) {
                                                            players = players.substring(1, players.length() - 1);
                                                            playerIds2 = players.split(",");
                                                            System.out.println("playerIds2 ++++++===========" + Arrays.toString(playerIds2));

                                                            if (playerIds2.length == 1) {
                                                                for (String s : playerIds2) {
                                                                    if (robotIdsList.contains(Integer.parseInt(s))) { //房间里的人是机器人
                                                                        String gpid = jedis0.hget(roomKey, "gpid");
                                                                        String gpId = jedis0.hget(roomKey, "group");
                                                                        String key = "g{" + gpId + "}:play:" + gpid;
                                                                        if (!players.equals("[]")) {
                                                                            System.out.println("roomKey ++++" + roomKey);
                                                                            System.out.println("gpid ++++++" + gpid);
                                                                            System.out.println("groupid ++++++" + gpId);
                                                                            System.out.println("key +++++++" + key);
                                                                            System.out.println("===================清空机器人准备时间超过六秒的房间 8888888888888888");

                                                                            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 -> {
                                                                                System.out.println("操作成功: " + response.returnCode);
                                                                            });

                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                        }
                                        ready();
                                    } 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 ("22".equalsIgnoreCase(wanfaId)) { //湖南红中麻将
                                    System.out.println("command" + command);
                                    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();
                                        System.out.println("红中结算");
                                        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);
                                                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();
                                            }
                                        }
                                        ready();
                                    } 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);
                                                        }
                                                    }
                                                }
                                            }
                                        }
//                                        } catch (SQLException e) {
//                                            System.out.println("恢复机器人账户失败" + e);
//                                        } finally {
//                                            jedis11s.close();
//                                        }
                                    }else if ("2009".equalsIgnoreCase(command)) {
                                        for (int i = 0; i < 7; i++) {
                                            sleepTime(1000);
                                            if (i == 6) {
                                                System.out.println("红中发起 1005");
                                                ITObject params = TObject.newInstance();
                                                String[] playerIds2 = null;
                                                Set<String> roomIds = jedis0.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;
                                                    System.out.println("roomKey +++++++++++++++++" + roomKey);
                                                    if (jedis0.hget(roomKey, "players") != null) {
                                                        String players = jedis0.hget(roomKey, "players");
                                                        if (!players.equals("[]")) {
                                                            players = players.substring(1, players.length() - 1);
                                                            playerIds2 = players.split(",");
                                                            System.out.println("playerIds2 ++++++===========" + Arrays.toString(playerIds2));

                                                            if (playerIds2.length == 1) {
                                                                for (String s : playerIds2) {
                                                                    if (robotIdsList.contains(Integer.parseInt(s))) { //房间里的人是机器人
                                                                        String gpid = jedis0.hget(roomKey, "gpid");
                                                                        String gpId = jedis0.hget(roomKey, "group");
                                                                        String key = "g{" + gpId + "}:play:" + gpid;
                                                                        if (!players.equals("[]")) {
                                                                            System.out.println("roomKey ++++" + roomKey);
                                                                            System.out.println("gpid ++++++" + gpid);
                                                                            System.out.println("groupid ++++++" + gpId);
                                                                            System.out.println("key +++++++" + key);
                                                                            System.out.println("===================清空机器人准备时间超过六秒的房间 8888888888888888");

                                                                            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 -> {
                                                                                System.out.println("操作成功: " + response.returnCode);
                                                                            });

                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                        }
                                        ready();
                                    }
                                }
                                else if ("17".equalsIgnoreCase(wanfaId)) {  //字牌放炮罚
                                    System.out.println("放炮罚command  " + command);
                                    if ("811".equalsIgnoreCase(command)) {  //初始化手牌
                                        huNanFangPaoFa.cardInHead(command, message, client);
                                        System.out.println("字牌放炮罚 初始化手牌");
                                    } 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)) { //放跑提示
                                        System.out.println("放跑提示");
                                        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);
                                            System.out.println("放炮罚：恢复机器人账户 " + playerId + "使用状态为0");
                                        } catch (SQLException e) {
                                            System.out.println(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);
                                            System.out.println("转转麻将：恢复机器人账户 " + playerId + "使用状态为0");
                                        } catch (SQLException e) {
                                            System.out.println(e);
                                        }
                                    }
                                }
                                else if ("10".equalsIgnoreCase(wanfaId)) {
                                    //长沙麻将
                                    System.out.println("11111-----------command" + command);
                                    if ("811".equalsIgnoreCase(command)) {//初始化收手牌
                                        huNanChangSha.cardInHead(command, message, client);
                                    }
                                    else if ("812".equalsIgnoreCase(command)) {//出牌广播
                                        HuNanChangSha.drawCard(command, message);
                                    }
                                    else if ("819".equalsIgnoreCase(command)) {//摸牌
                                        huNanChangSha.getCard(command, message);
                                    }
                                    else if ("813".equalsIgnoreCase(command)) {//出牌提示
                                        System.out.println("出牌++++++++++++++++++++++++");
                                        huNanChangSha.outCard(client);
                                    }
                                    else if ("814".equalsIgnoreCase(command)) {//放招提示
                                        huNanChangSha.actionCard(param, client);
                                    }
                                    else if ("2009".equalsIgnoreCase(command)) {
                                        for (int i = 0; i < 7; i++) {
                                            sleepTime(1000);
                                            if (i == 6) {
                                                System.out.println("长沙发起 1005");
                                                ITObject params = TObject.newInstance();
                                                String[] playerIds2 = null;
                                                Set<String> roomIds = jedis0.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;
                                                    System.out.println("roomKey +++++++++++++++++" + roomKey);
                                                    if (jedis0.hget(roomKey, "players") != null) {
                                                        String players = jedis0.hget(roomKey, "players");
                                                        if (!players.equals("[]")) {
                                                            players = players.substring(1, players.length() - 1);
                                                            playerIds2 = players.split(",");
                                                            System.out.println("playerIds2 ++++++===========" + Arrays.toString(playerIds2));

                                                            if (playerIds2.length == 1) {
                                                                for (String s : playerIds2) {
                                                                    if (robotIdsList.contains(Integer.parseInt(s))) { //房间里的人是机器人
                                                                        String gpid = jedis0.hget(roomKey, "gpid");
                                                                        String gpId = jedis0.hget(roomKey, "group");
                                                                        String key = "g{" + gpId + "}:play:" + gpid;
                                                                        if (!players.equals("[]")) {
                                                                            System.out.println("roomKey ++++" + roomKey);
                                                                            System.out.println("gpid ++++++" + gpid);
                                                                            System.out.println("groupid ++++++" + gpId);
                                                                            System.out.println("key +++++++" + key);
                                                                            System.out.println("===================清空机器人准备时间超过六秒的房间 8888888888888888");

                                                                            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 -> {
                                                                                System.out.println("操作成功: " + response.returnCode);
                                                                            });

                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                            }
                                        }
                                    }
                                    else if ("817".equalsIgnoreCase(command)) {//结算
                                        huNanChangSha.getChangShaCardInhand().clear();
                                        huNanChangSha.getChuGuoCardInhand().clear();
                                        huNanChangSha.getpongGroup().clear();
                                        huNanChangSha.getchowGroup().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);
                                                    }
                                                }

                                                System.out.println("长沙麻将：恢复机器人数量 9++++9999999999  " + key);
                                                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);
                                                System.out.println("value------" + value);
                                                // 如果找到了对应的 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();;


                                        System.out.println("count ------ 12346540908786384637785385378 --------------count" + count);
                                        ready();
                                        //写定时器

                                    }
                                    else if ("815".equalsIgnoreCase(command)) { //服务器通知客户端有玩家执行了操作
                                        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;
                                            System.out.println("rid---------" + rid);
                                            if (jedis0.hget(roomKey, "players") != null) {
                                                String players = jedis0.hget(roomKey, "players");
                                                System.out.println("players +++ " + players);
                                                if (!players.equals("[]")) {
                                                    players = players.substring(1, players.length() - 1);
                                                    playerIds = players.split(",");
                                                    System.out.println("playerIds ++++" + Arrays.toString(playerIds));
                                                    for (String pyids : playerIds) {
                                                        System.out.println("pyids+++   " + pyids);
                                                        System.out.println("Integer.parseInt(pyids)------------" + Integer.parseInt(pyids));
                                                        System.out.println("playerId--------" + playerId);
                                                        if (Integer.parseInt(pyids) == playerId) {
                                                            jedis0.del(roomId);
                                                        }
                                                    }
                                                }
                                            }
                                        }

//                                            String sql = String.format("UPDATE `account` SET start = %d WHERE id = %d", 0, playerId);
//                                            DataBase.use().executeUpdate(sql);
//                                            System.out.println("长沙麻将：恢复机器人账户 " + playerId + "使用状态为0");
//                                        } catch (SQLException e) {
//                                            System.out.println(e);
//                                        }
                                    }
                                    else if ("825".equalsIgnoreCase(command)) {
                                        ITObject params = TObject.newInstance();
                                        params.putInt("qi", 0);
                                        params.putInt("id", 1);
                                        client.send("612", params, response -> {
                                            System.out.println("操作成功: " + response.returnCode);
                                        });
                                    }
                                    else if ("822".equalsIgnoreCase(command)) {
                                        ITObject params = TObject.newInstance();
                                        params.putInt("qi", 0);
                                        params.putInt("id", 1);
                                        client.send("612", params, response -> {
                                            System.out.println("操作成功: " + response.returnCode);
                                        });
                                    }
                                    else if ("835".equalsIgnoreCase(command)) { //听牌天听
                                        ITObject params = TObject.newInstance();
                                        params.putInt("qi", 0);
                                        params.putInt("id", 1);
                                        client.send("612", params, response -> {
                                            System.out.println("操作成功: " + response.returnCode);
                                        });

                                    }

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

                            IEventListener() {
                                @Override
                                public void handleEvent(Event event) {
                                    SocketCode code = (SocketCode) event.getParameter("code");
                                    if (code == SocketCode.Connect) {
                                        System.out.println("连接成功");
                                    } else {
                                        System.out.println("连接失败");
                                    }
                                }
                            });


                    //这里是机器人主动找真人房间进入
                    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 = String.format("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
                                                System.out.println("6666666666666666666666666666666666666");
                                                if (jedis0.keys("{user}:" + playerId + "_token").size() != 0) {
                                                    System.out.println("playetid +++++++++++++" + playerId);
                                                    System.out.println("5555555555555555555555555555555555555");
                                                    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);
                                                        System.out.println("token ++++++++++++++++++++++" + token);
                                                    }
                                                } else {
                                                    System.out.println("4777777777777777777777777");
                                                    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已经过去七秒
                                                System.out.println(System.currentTimeMillis());
                                                //判断准备时间，只是要取出准备时间超过七秒的房间
                                                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();  //准备
                }
            }


        } finally {
//            System.out.println("关闭连接----------------------");
            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");
            System.out.println("座位号:" + param.getInt("seat") + "的用户出牌:" + param.getInt("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;
            }
            System.out.println("出牌权转移到座位号:" + param.getInt("seat") + "的用户");
//			{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}
            System.out.println("轮到座位号:" + param.getInt("seat") + "的用户摸牌" + ",牌为：" + param.getInt("card"));
            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);
                System.out.println("机器人:" + param.getInt("seat") + "为庄家，需要出牌" + ",牌为：" + cardInhand.get(0));

            }
            System.out.println("机器人:" + param.getInt("seat") + "初始化手牌" + ",牌为：" + cardInhand.toString());

        }
        return null;
    }

    /**
     * 出牌方法
     *
     * @param command 协议号
     * @param message 消息对象
     * @param wanfaId 玩法ID
     * @return
     */
    public String outCard(String command, Message message, String wanfaId) {
        //todo 根据房间的玩法id 调不同的业务服务 出牌 碰杠

//        String paoDeKuaiOutCard = paoDeKuaiSuanFa.paoDeKuaiOutCardSuanFa(cardInhand, card);//跑得快出牌
//        System.out.println("跑得快出牌" + paoDeKuaiOutCard);
//        if ("22".equalsIgnoreCase(wanfaId)) { //红中
//            String hongZhongOutCard = hongZhongSuanFa.hongZhongOutCardSuanFa(cardInhand, card); //红中出牌
//            System.out.println("红中出牌" + hongZhongOutCard);
//        }


        ITObject params = TObject.newInstance();
        params.putString("session", session + "," + token);
        params.putInt("card1", 0);
        params.putInt("card", cardInhand.get(0));
        cardInhand.remove(0);
        System.out.println("目前剩余手牌：" + cardInhand.toString());
        client.send("611", params, response -> {
            System.out.println("出牌成功: " + response.returnCode);
        });
        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);
            System.out.println("id ++ " + id);
            System.out.println("type ++ " + type);
        }
        //弃 是根据算法选择是否要弃掉 不进行碰杠胡
        //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);
            System.out.println("删除碰的牌");
//            Global.logger.info("删除碰的牌");
            //执行胡牌
        } else if (type == 6) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            System.out.println("执行胡牌");
            //执行吃杠
        } else if (type == 3) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(cardInhand, opcard, 3);
            System.out.println("执行吃杠");
            //执行自杠
        } else if (type == 4) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(cardInhand, opcard, 4);
            System.out.println("执行自杠");
            // 碰后补杠
        } else if (type == 5) {
            params.putString("session", session + "," + token);
            params.putInt("qi", 0);
            params.putInt("id", 1);
            Util.removeCard(cardInhand, opcard, 1);
            System.out.println("执行碰后补杠");
        }

//        cardInhand.remove(0);
//        cardInhand.remove(1);
        System.out.println("执行id为：" + 0 + "的操作");

        client.send("612", params, response -> {
            System.out.println("操作成功: " + response.returnCode);
        });
        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 -> {
            System.out.println("操作成功: " + response.returnCode);
        });
    }


    /**
     * 准备方法
     *
     * @return
     */
    public String ready() {
        try {
            // 添加1秒延迟
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        cardInhand = new ArrayList<Integer>();
//        HuNanHongZhong.hongZhongCardInhand();
//        HuNanFangPaoFa.fangPaoFaCardInhand();
        System.out.println("准备1111");
        ITObject params = TObject.newInstance();
        params.putString("session", session + "," + token);

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

            @Override
            public void action(MessageResponse messageResponse) {
                System.out.println("准备成功: ");

                System.out.println(messageResponse);
                System.out.println(messageResponse.returnCode);
                System.out.println(messageResponse.messageData.param);
            }
        });
        return null;
    }


    /**
     * 加入房间方法
     *
     * @return
     */
    public String joinRoom(int playerId) {
        try {
            // 1添加2秒延迟
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ITObject params = TObject.newInstance();
        params.putString("session", session + "," + token);

        System.out.println("进入房间");
        System.out.println("session00000    +++" + session + "," + token);
        client.send("1002", params, response -> {
            System.out.println("进入房间成功: " + response.returnCode);
            System.out.println(response.returnCode);
            System.out.println(response.messageData.param);
            ITObject obj = response.messageData.param.getTObject("tableInfo");

//            ITArray array = obj.getTArray("playerData");

//            for (int i = 0; i < array.size(); i++) {
//                System.out.println("座位准备" + array.getTObject(i).getInt("seat"));
//                if (playerId == array.getTObject(i).getInt("aid")) {
////                    HuNanHongZhong.playerId = array.getTObject(i).getInt("aid");
////                    HuNanZhuanZhuan.seat = array.getTObject(i).getInt("seat"); //湖南转转麻将
////                    HuNanFangPaoFa.seat = array.getTObject(i).getInt("seat"); //字牌放炮罚
////                    HuNanPaoDeKuai.seat = array.getTObject(i).getInt("seat"); //跑得快
////                    HuNanChangSha.seat = array.getTObject(i).getInt("seat");
//
//                }
//            }
        });
        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();
//            }
//        }
//    }
}
