package robot.mj;

import com.data.cache.BaseCache;
import com.data.cache.GroupCache;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TObject;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * 房间创建器 - 统一处理房间创建逻辑
 */
public class RoomCreator {
    private static final Logger log = LoggerFactory.getLogger(RoomCreator.class);

    /**
     * 在Redis中创建房间
     * 
     * @param groupId 群组ID
     * @param wanfaId 玩法ID
     */
    public static RoomInfo createRoomInRedis(int groupId, int wanfaId, int robotId) {
        try {
            Jedis jedis0 = Redis.use("group1_db0").getJedis();
            Jedis jedis11 = Redis.use("group1_db11").getJedis();
            
            try {
                //从free_room队列获取房间ID
                String newRoomId = Redis.use("group1_db1").rpop("free_room");
                if (StringUtil.isEmpty(newRoomId)) {
                    log.error("没有可用的房间ID，free_room队列为空");
                    return null;
                }
                //Redis.use("group1_db1").lpush("free_room", newRoomId);
                
                String roomKey = "room:" + newRoomId;
                
                //获取群组信息
                String groupKey = "group:" + groupId;
                Map<String, String> groupInfo = jedis11.hgetAll(groupKey);
                //不存在则创建默认群组信息
                if (groupInfo.isEmpty()) {
                    log.warn("群组信息不存在，群组ID: {}，正在创建默认群组信息", groupId);
                    createDefaultGroupInfo(jedis11, groupId);
                    groupInfo = jedis11.hgetAll(groupKey);
                }

                //确保游戏配置存在
                String gameConfigKey = "game:" + wanfaId;
                Map<String, String> gameInfo = jedis0.hgetAll(gameConfigKey);
                //不存在则创建跑得快的默认游戏配置
                if (gameInfo.isEmpty()) {
                    log.warn("游戏配置不存在，玩法ID: {}，正在创建跑得快默认游戏配置", wanfaId);
                    createDefaultGameConfig(jedis0, wanfaId);
                    gameInfo = jedis0.hgetAll(gameConfigKey);
                }
                
                //获取玩法配置
                String playKey = "g{" + groupId + "}:play:" + wanfaId;
                Map<String, String> playConfig = jedis11.hgetAll(playKey);
                //不存在则创建跑得快的默认玩法配置
                if (playConfig.isEmpty()) {
                    log.warn("玩法配置不存在，群组ID: {}, 玩法ID: {}，正在创建跑得快默认配置", groupId, wanfaId);
                    createDefaultChangshaMajiangConfig(jedis11, groupId, wanfaId);
                    playConfig = jedis11.hgetAll(playKey);
                }
                
                //构建房间信息
                Map<String, String> roomMap = new HashMap<>();
                
                //基础房间信息
                roomMap.put("AA", "0");                          //AA支付标志
                roomMap.put("agent", "1");                       //代理标志
                roomMap.put("dismiss_time", "30");               //解散时间
                roomMap.put("gpid", String.valueOf(wanfaId));    //玩法ID
                roomMap.put("group", String.valueOf(groupId));   //群组ID
                roomMap.put("hpOnOff", "1"); //体力开关
                roomMap.put("hp_times", "1000"); //体力次数
                roomMap.put("id", newRoomId);                    //房间ID
                roomMap.put("kick_time", "30");                  //踢出时间
                roomMap.put("owner", "{user}:" + robotId);       //房间所有者
                roomMap.put("maxPlayers", "2"); //最大玩家数
                roomMap.put("opt", "2"); //选项
                roomMap.put("pay", "0"); //支付金额
                roomMap.put("payer", String.valueOf(robotId));                   //支付者ID
                roomMap.put("rewardType", "0"); //奖励类型
                roomMap.put("rewardValueType", "0"); //奖励值类型
                roomMap.put("seats", "[1]");                      //房间状态
                roomMap.put("status", "0");                      //房间状态
                roomMap.put("times", "4"); //局数
                roomMap.put("xipai_rewardType", "3"); //洗牌奖励类型
                roomMap.put("xipai_rewardValueType", "1"); //洗牌奖励值类型

                //如果有体力配置
                String hpConfig = playConfig.get("hpConfig");
                if (hpConfig != null) {
                    roomMap.put("limitInRoom", "1");             //房间内限制
                }
            
                //处理玩法选项配置
                String playConfigJson = playConfig.getOrDefault("config", "{}");
                ITObject configData = TObject.newFromJsonData(playConfigJson);
            
                //原逻辑删除了字段
                configData.del("opt");
                configData.del("AA");
            
                //将处理后的配置数据存储到options字段
                roomMap.put("options", configData.toJson());     //选项配置
                roomMap.put("game", String.valueOf(wanfaId));    //游戏ID
                roomMap.put("open", "1");                       //开放状态
                roomMap.put("round", "0");                      //回合数
                roomMap.put("create_time", String.valueOf(System.currentTimeMillis() / 1000)); //创建时间
                roomMap.put("cache_ver", "1");                  //缓存版本
                roomMap.put("players", "[]");                   //玩家列表
                roomMap.put("fake_existTime", "30");            //fake存在时间

                //设置房间信息
                jedis0.hmset(roomKey, roomMap);
                
                //更新剩余机器人数量
                String leftoverRobotStr = jedis11.hget(playKey, "leftover_robot");
                int leftoverRobot = leftoverRobotStr != null ? Integer.parseInt(leftoverRobotStr) : 0;
                if (leftoverRobot > 0) {
                    jedis11.hincrBy(playKey, "leftover_robot", -1);
                }
                
                //将房间添加到群组房间列表
                String groomsKey = "g{" + groupId + "}:rooms";
                jedis11.zadd(groomsKey, wanfaId * 10000 + 1101, roomKey);
                
                //更新群组的缓存版本 确保客户端能够获取到最新的群组信息
                String groupKeyForUpdate = GroupCache.genKey(groupId);
                BaseCache.updateCacheVer(jedis11, groupKeyForUpdate);

                //创建并返回房间信息
                RoomInfo roomInfo = new RoomInfo();
                roomInfo.setRoomId(roomKey);
                roomInfo.setGroupId(groupId);
                roomInfo.setWanfaId(wanfaId);
                roomInfo.setServerIp(Config.GAME_SERVER_HOST);
                roomInfo.setServerPort(getGamePortForWanfa(wanfaId));
                
                log.info("成功创建机器人房间: {}, 群组: {}, 玩法: {}", roomKey, groupId, wanfaId);
                return roomInfo;
            } finally {
                jedis0.close();
                jedis11.close();
            }
        } catch (Exception e) {
            log.error("创建房间时发生错误", e);
            return null;
        }
    }

    /**
     * 根据玩法ID获取游戏服务器端口
     */
    private static int getGamePortForWanfa(int wanfaId) {
        switch (wanfaId) {
            case 10: //跑得快
                return 6841;
            default:
                return 6841;
        }
    }

    /**
     * 为跑得快创建默认玩法配置
     */
    private static void createDefaultChangshaMajiangConfig(Jedis jedis11, int groupId, int wanfaId) {
        try {
            log.info("为群组 {} 和跑得快玩法 {} 创建默认玩法配置", groupId, wanfaId);
            
            String playKey = "g{" + groupId + "}:play:" + wanfaId;
            
            Map<String, String> defaultConfig = new HashMap<>();
            defaultConfig.put("opt", "1");
            defaultConfig.put("groupId", String.valueOf(groupId));
            defaultConfig.put("id", String.valueOf(wanfaId));
            defaultConfig.put("gameId", String.valueOf(wanfaId));
            defaultConfig.put("name", "跑得快-机器人专用");
            defaultConfig.put("deskId", "0");
            defaultConfig.put("maxPlayers", "4");
            defaultConfig.put("hpOnOff", "0");
            defaultConfig.put("rewardType", "0");
            defaultConfig.put("rewardValueType", "0");
            defaultConfig.put("xipai_rewardType", "0");
            defaultConfig.put("xipai_rewardValueType", "0");
            defaultConfig.put("hp_times", "0");
            defaultConfig.put("ban", "0");
            defaultConfig.put("robot_room", "1");
            defaultConfig.put("shangxian_robot", "10"); //限制机器人数量
            defaultConfig.put("leftover_robot", "10"); //设置剩余机器人数量
            defaultConfig.put("reward", "0");
            defaultConfig.put("xipai_reward", "100");
            defaultConfig.put("anchou_reward", "1");
            defaultConfig.put("mark", "0");
            defaultConfig.put("cache_ver", "1");
            
            //跑得快配置选项
            defaultConfig.put("config", "{\"maxPlayers\":4,\"pid\":22,\"opt\":1,\"AA\":0,\"maxRound\":8,\"dianpao\":1,\"zimo\":1,\"haidi\":1,\"ting\":1,\"piao\":0,\"chongfeng\":1,\"queyimen\":0,\"hujia\":0,\"hongzhong\":1,\"qgh\":0,\"qgh_opt\":0,\"qgh_type\":0,\"qgh_score\":0,\"qgh_double\":0,\"qgh_double_opt\":0,\"qgh_double_type\":0,\"qgh_double_score\":0,\"qgh_double_score_opt\":0,\"qgh_double_score_type\":0,\"qgh_double_score_type_opt\":0}");
            defaultConfig.put("hpConfig", "{\"times\":1,\"limitInRoom\":0,\"maxRound\":8}");
            
            jedis11.hmset(playKey, defaultConfig);
            
            //更新缓存版本
            jedis11.hincrBy(playKey, "cache_ver", 1);
            
            //更新群组玩法列表 将此玩法添加进去
            String gpidsKey = "g{" + groupId + "}:pids";
            jedis11.zadd(gpidsKey, 1 * 10 + 0, String.valueOf(wanfaId));
            
            log.info("成功创建跑得快默认玩法配置 键名: {}", playKey);
        } catch (Exception e) {
            log.error("创建跑得快默认玩法配置时发生错误 群组ID: {}, 玩法ID: {}", groupId, wanfaId, e);
        }
    }

    /**
     * 创建默认群组信息
     */
    private static void createDefaultGroupInfo(Jedis jedis11, int groupId) {
        try {
            log.info("为群组 {} 创建默认群组信息", groupId);
            
            String groupKey = "group:" + groupId;
            
            Map<String, String> defaultGroupInfo = new HashMap<>();
            defaultGroupInfo.put("ban", "0");         //未禁用
            defaultGroupInfo.put("ban_apply", "0");   //不禁止申请
            defaultGroupInfo.put("ban_chat1", "false");
            defaultGroupInfo.put("ban_chat2", "false");
            defaultGroupInfo.put("create_time", String.valueOf(System.currentTimeMillis() / 1000));
            defaultGroupInfo.put("dissolve_opt", "1"); //解散选项
            defaultGroupInfo.put("exit_opt", "0");
            defaultGroupInfo.put("gms", "19");
            defaultGroupInfo.put("id", String.valueOf(groupId));
            defaultGroupInfo.put("kick_opt", "1");    //踢人选项
            defaultGroupInfo.put("name", "机器人专用群组-" + groupId);
            defaultGroupInfo.put("notice", "");
            defaultGroupInfo.put("opt", "1");         //开启状态
            defaultGroupInfo.put("option", "0");      //选项
            defaultGroupInfo.put("owner", "999999");  //使用机器人系统账户ID
            defaultGroupInfo.put("pay_type", "1");    //房主支付
            defaultGroupInfo.put("type", "2");        //普通群组类型

            jedis11.hmset(groupKey, defaultGroupInfo);
            
            log.info("成功创建默认群组信息，键名: {}", groupKey);
        } catch (Exception e) {
            log.error("创建默认群组信息时发生错误，群组ID: {}", groupId, e);
        }
    }

    /**
     * 创建默认游戏配置
     */
    private static void createDefaultGameConfig(Jedis jedis0, int wanfaId) {
        try {
            log.info("为玩法 {} 创建默认游戏配置", wanfaId);
            
            String gameConfigKey = "game:" + wanfaId;
            
            Map<String, String> defaultGameInfo = new HashMap<>();
            defaultGameInfo.put("id", String.valueOf(wanfaId));
            defaultGameInfo.put("name", "跑得快");
            defaultGameInfo.put("maxPlayers", "4");  //跑得快为4人游戏
            defaultGameInfo.put("minPlayers", "2");  //最少2人
            defaultGameInfo.put("type", "1");        //游戏类型
            defaultGameInfo.put("status", "1");      //状态开启
            defaultGameInfo.put("icon", "");         //图标
            defaultGameInfo.put("desc", "跑得快游戏"); //描述
            defaultGameInfo.put("version", "1.0");   //版本
            defaultGameInfo.put("pay", "0");         //支付金额
            defaultGameInfo.put("times", "8");       //局数
            defaultGameInfo.put("hpType", "0");      // 体力值类型，必需字段
            defaultGameInfo.put("gameType", "1");    // 游戏类型，必需字段
            defaultGameInfo.put("isNonnegative", "0"); // 不可负分，必需字段

            defaultGameInfo.put("opt1", "8");
            defaultGameInfo.put("opt2", "16");
            defaultGameInfo.put("opt3", "24");
            defaultGameInfo.put("opt4", "32");
            defaultGameInfo.put("opt5", "40");
            //设置支付选项
            defaultGameInfo.put("pay1_2", "10");
            defaultGameInfo.put("pay1_3", "15");
            defaultGameInfo.put("pay1_4", "20");
            
            jedis0.hmset(gameConfigKey, defaultGameInfo);
            
            log.info("成功创建默认游戏配置，键名: {}", gameConfigKey);
        } catch (Exception e) {
            log.error("创建默认游戏配置时发生错误，玩法ID: {}", wanfaId, e);
        }
    }

    /**
     * 房间信息类
     */
    public static class RoomInfo {
        private String roomId;
        private int groupId;
        private int wanfaId;
        private String serverIp;
        private int serverPort;
        
        public String getRoomId() { return roomId; }
        public void setRoomId(String roomId) { this.roomId = roomId; }
        public int getGroupId() { return groupId; }
        public void setGroupId(int groupId) { this.groupId = groupId; }
        public int getWanfaId() { return wanfaId; }
        public void setWanfaId(int wanfaId) { this.wanfaId = wanfaId; }
        public String getServerIp() { return serverIp; }
        public void setServerIp(String serverIp) { this.serverIp = serverIp; }
        public int getServerPort() { return serverPort; }
        public void setServerPort(int serverPort) { this.serverPort = serverPort; }
    }
}