using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

[Serializable]
public class ConfigTableInfo
{
    public string tableName;
    public string displayName;
    public string description;
    public List<FieldRelation> relations = new List<FieldRelation>();
    public bool isExistInProject;
    public string fileExtension = ".xlsx";
}

[Serializable]
public class FieldRelation
{
    public string fieldName;
    public string targetTable;
    public string targetField;
    public string relationFormat;
    public string description;
}

public class ReverseRelation
{
    public string sourceTable;
    public string sourceDisplayName;
    public string fieldName;
    public string description;
    public string relationFormat;
}

[Serializable]
public class FieldRelationBackup
{
    public string fieldName;
    public string targetTable;
    public string targetField;
    public string relationFormat;
    public string description;
}

public static class ConfigLinkDatabase
{
    private static List<ConfigTableInfo> _cachedData;
    private static HashSet<string> _existingTableNames;
    private static string _excelFolderPath;

    private const string CONFIG_PATH = "Resources/Resources_moved/config";

    public static void SetExcelFolderPath(string path)
    {
        _excelFolderPath = path;
        PlayerPrefs.SetString("ConfigLinkExcelFolderPath", path);
    }

    public static string GetExcelFolderPath()
    {
        if (string.IsNullOrEmpty(_excelFolderPath))
        {
            _excelFolderPath = PlayerPrefs.GetString("ConfigLinkExcelFolderPath", "");
        }
        return _excelFolderPath;
    }

    public static string GetExcelFilePath(string tableName)
    {
        string folderPath = GetExcelFolderPath();
        if (string.IsNullOrEmpty(folderPath))
            return null;

        var tableInfo = GetTableInfo(tableName);
        string extension = tableInfo?.fileExtension ?? ".xlsx";
        string excelPath = Path.Combine(folderPath, $"{tableName}{extension}");
        return File.Exists(excelPath) ? excelPath : null;
    }

    public static bool IsExcelFolderSet()
    {
        return !string.IsNullOrEmpty(GetExcelFolderPath());
    }

    public static bool IsExcelFileExists(string tableName)
    {
        return GetExcelFilePath(tableName) != null;
    }

    public static List<ConfigTableInfo> GetAllTableInfo()
    {
        if (_cachedData != null)
            return _cachedData;

        _cachedData = new List<ConfigTableInfo>
        {
            new ConfigTableInfo { tableName = "activity", displayName = "活动表", description = "活动配置表" },
            new ConfigTableInfo { tableName = "activityreward", displayName = "活动奖励表", description = "活动奖励配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "activityId", targetTable = "activity", targetField = "id", description = "关联活动" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "奖励(类型_id_数量)" }
            }},
            new ConfigTableInfo { tableName = "achievement", displayName = "成就表", description = "成就配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励(类型_id_数量)" }
            }},
            new ConfigTableInfo { tableName = "arenaaward", displayName = "竞技场奖励表", description = "竞技场排名奖励", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励(类型_id_数量)" }
            }},
            new ConfigTableInfo { tableName = "attribute", displayName = "属性表", description = "属性配置表" },
            new ConfigTableInfo { tableName = "box", displayName = "宝箱表", description = "宝箱抽奖配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "reward", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "buff", displayName = "Buff表", description = "Buff效果配置" },
            new ConfigTableInfo { tableName = "callstrength", displayName = "召唤强度表", description = "召唤强度概率配置" },
            new ConfigTableInfo { tableName = "checkpointreward", displayName = "关卡奖励表", description = "关卡奖励池配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "rune", targetField = "id", relationFormat = "rune_id_num", description = "符文奖励" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "道具奖励" },
                new FieldRelation { fieldName = "rewards", targetTable = "equip", targetField = "id", relationFormat = "equip_id_num", description = "装备奖励" }
            }},
            new ConfigTableInfo { tableName = "collectionreward", displayName = "收藏奖励表", description = "收藏奖励配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "common", displayName = "通用配置表", description = "通用配置项", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "key", targetTable = "language", targetField = "key", description = "多语言key" }
            }},
            new ConfigTableInfo { tableName = "drawlinereward", displayName = "画线奖励表", description = "画线游戏奖励", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "enemy", displayName = "敌人表", description = "敌人基础配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "reward_id", targetTable = "checkpointreward", targetField = "id", description = "掉落奖励" },
                new FieldRelation { fieldName = "skills", targetTable = "skill", targetField = "id", description = "技能列表" }
            }},
            new ConfigTableInfo { tableName = "enemylevel", displayName = "敌人等级表", description = "敌人等级成长配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "升级消耗" },
                new FieldRelation { fieldName = "target_id", targetTable = "enemy", targetField = "id", description = "关联敌人" }
            }},
            new ConfigTableInfo { tableName = "equip", displayName = "装备表", description = "装备基础配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "attr_id", targetTable = "equipAttrRandom", targetField = "id", description = "随机属性ID" },
                new FieldRelation { fieldName = "retrieve_pros", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "回收奖励" }
            }},
            new ConfigTableInfo { tableName = "equipAttrRandom", displayName = "装备随机属性表", description = "装备随机属性配置" },
            new ConfigTableInfo { tableName = "equiplevel", displayName = "装备等级表", description = "装备等级成长配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "升级消耗" },
                new FieldRelation { fieldName = "target_id", targetTable = "equip", targetField = "id", description = "关联装备" }
            }},
            new ConfigTableInfo { tableName = "equipstage", displayName = "装备品阶表", description = "装备品阶配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "突破消耗" },
                new FieldRelation { fieldName = "target_id", targetTable = "equip", targetField = "id", description = "关联装备" }
            }},
            new ConfigTableInfo { tableName = "fight_arena", displayName = "竞技场战斗表", description = "竞技场关卡配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "enemy_ids", targetTable = "enemy", targetField = "id", relationFormat = "id_pos_lv", description = "敌人(格式: id_位置_等级)" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" },
                new FieldRelation { fieldName = "out_enemy_config", targetTable = "map_act", targetField = "id", relationFormat = "表名", description = "出怪表名" }
            }},
            new ConfigTableInfo { tableName = "fight_fb1", displayName = "副本战斗表1", description = "副本关卡配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "enemy_ids", targetTable = "enemy", targetField = "id", relationFormat = "id_pos_lv", description = "敌人(格式: id_位置_等级)" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" },
                new FieldRelation { fieldName = "out_enemy_config", targetTable = "map_act", targetField = "id", relationFormat = "表名", description = "出怪表名" }
            }},
            new ConfigTableInfo { tableName = "fight_fb2", displayName = "副本战斗表2", description = "副本关卡配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "enemy_ids", targetTable = "enemy", targetField = "id", relationFormat = "id_pos_lv", description = "敌人(格式: id_位置_等级)" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" },
                new FieldRelation { fieldName = "out_enemy_config", targetTable = "map_act2", targetField = "id", relationFormat = "表名", description = "出怪表名" }
            }},
            new ConfigTableInfo { tableName = "fight_fb3", displayName = "副本战斗表3", description = "副本关卡配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "enemy_ids", targetTable = "enemy", targetField = "id", relationFormat = "id_pos_lv", description = "敌人(格式: id_位置_等级)" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" },
                new FieldRelation { fieldName = "out_enemy_config", targetTable = "map_act3", targetField = "id", relationFormat = "表名", description = "出怪表名" }
            }},
            new ConfigTableInfo { tableName = "fight_fb4", displayName = "副本战斗表4", description = "副本关卡配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "enemy_ids", targetTable = "enemy", targetField = "id", relationFormat = "id_pos_lv", description = "敌人(格式: id_位置_等级)" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" },
                new FieldRelation { fieldName = "out_enemy_config", targetTable = "map_act4", targetField = "id", relationFormat = "表名", description = "出怪表名" }
            }},
            new ConfigTableInfo { tableName = "fight_sample", displayName = "战斗样例表", description = "战斗关卡配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "enemy_ids", targetTable = "enemy", targetField = "id", relationFormat = "id_pos_lv", description = "敌人(格式: id_位置_等级)" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" },
                new FieldRelation { fieldName = "pass_rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "回合进度奖励" },
                new FieldRelation { fieldName = "out_enemy_config", targetTable = "map_act", targetField = "id", relationFormat = "表名", description = "出怪表名" }
            }},
            new ConfigTableInfo { tableName = "fight_x", displayName = "战斗X表", description = "战斗关卡配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "enemy_ids", targetTable = "enemy", targetField = "id", relationFormat = "id_pos_lv", description = "敌人(格式: id_位置_等级)" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" },
                new FieldRelation { fieldName = "pass_rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "回合进度奖励" }
            }},
            new ConfigTableInfo { tableName = "funopencondition", displayName = "功能开放条件表", description = "功能开放条件配置" },
            new ConfigTableInfo { tableName = "gacha", displayName = "抽卡表", description = "抽卡配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "hero", targetField = "id", description = "抽卡获得的英雄" }
            }},
            new ConfigTableInfo { tableName = "gachareward", displayName = "抽卡奖励表", description = "抽卡奖励配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "game2048reward", displayName = "2048游戏奖励表", description = "2048游戏奖励配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "guide", displayName = "引导表", description = "新手引导配置" },
            new ConfigTableInfo { tableName = "guildbox", displayName = "公会宝箱表", description = "公会宝箱配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "guilddonate", displayName = "公会捐献表", description = "公会捐献配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "消耗" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "guildlevel", displayName = "公会等级表", description = "公会等级配置" },
            new ConfigTableInfo { tableName = "guildname", displayName = "公会名称表", description = "公会名称配置" },
            new ConfigTableInfo { tableName = "hero", displayName = "英雄表", description = "英雄基础配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "level_attr_id", targetTable = "attribute", targetField = "id", description = "升级显示属性" },
                new FieldRelation { fieldName = "stage_attr_id", targetTable = "attribute", targetField = "id", description = "升阶显示属性" },
                new FieldRelation { fieldName = "skills", targetTable = "skill", targetField = "id", description = "技能列表" },
                new FieldRelation { fieldName = "compose", targetTable = "hero", targetField = "id", description = "合成所需英雄" },
                new FieldRelation { fieldName = "equips", targetTable = "equip", targetField = "id", description = "装备列表" },
                new FieldRelation { fieldName = "buffs", targetTable = "buff", targetField = "id", relationFormat = "buffId_lv", description = "升阶解锁buff" },
                new FieldRelation { fieldName = "internal_buffs", targetTable = "buff", targetField = "id", description = "初始可抽取buff" },
                new FieldRelation { fieldName = "shardItem", targetTable = "prop", targetField = "id", description = "碎片道具ID" },
                new FieldRelation { fieldName = "activateRewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "激活奖励" }
            }},
            new ConfigTableInfo { tableName = "herolevel", displayName = "英雄等级表", description = "英雄等级成长配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "升级消耗" },
                new FieldRelation { fieldName = "target_id", targetTable = "hero", targetField = "id", description = "关联英雄" }
            }},
            new ConfigTableInfo { tableName = "herolevelinternal", displayName = "英雄内丹表", description = "英雄内丹配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "消耗" },
                new FieldRelation { fieldName = "buffs", targetTable = "buff", targetField = "id", description = "对应提升buff" }
            }},
            new ConfigTableInfo { tableName = "herostage", displayName = "英雄品阶表", description = "英雄品阶配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "道具消耗" },
                new FieldRelation { fieldName = "target_id", targetTable = "hero", targetField = "id", description = "关联英雄" }
            }},
            new ConfigTableInfo { tableName = "idlereward", displayName = "挂机奖励表", description = "挂机奖励配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "挂机宝箱奖励" }
            }},
            new ConfigTableInfo { tableName = "language", displayName = "语言表", description = "多语言配置" },
            new ConfigTableInfo { tableName = "link", displayName = "英雄羁绊表", description = "英雄羁绊配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "hero_ids", targetTable = "hero", targetField = "id", description = "英雄ID列表" }
            }},
            new ConfigTableInfo { tableName = "mail", displayName = "邮件表", description = "邮件配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "mall", displayName = "商店表", description = "商店商品配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "productId", targetTable = "prop", targetField = "id", description = "商品道具ID" },
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "购买消耗" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "购买获得奖励" }
            }},
            new ConfigTableInfo { tableName = "map", displayName = "地图表", description = "地图房间配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num", description = "初始怪物" }
            }},
            new ConfigTableInfo { tableName = "map1", displayName = "地图1表", description = "地图1房间配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num", description = "初始怪物" }
            }},
            new ConfigTableInfo { tableName = "map2", displayName = "地图2表", description = "地图2房间配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num", description = "初始怪物" }
            }},
            new ConfigTableInfo { tableName = "map3", displayName = "地图3表", description = "地图3房间配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num", description = "初始怪物" }
            }},
            new ConfigTableInfo { tableName = "map_act", displayName = "出怪表", description = "关卡出怪配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "怪物(格式: id_等级_数量_时间)" },
                new FieldRelation { fieldName = "boss", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "Boss(格式: id_等级_数量_限时)" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "波次奖励" }
            }},
            new ConfigTableInfo { tableName = "map_act2", displayName = "出怪表2", description = "关卡出怪配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "怪物" },
                new FieldRelation { fieldName = "boss", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "Boss" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "波次奖励" }
            }},
            new ConfigTableInfo { tableName = "map_act3", displayName = "出怪表3", description = "关卡出怪配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "怪物" },
                new FieldRelation { fieldName = "boss", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "Boss" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "波次奖励" }
            }},
            new ConfigTableInfo { tableName = "map_act4", displayName = "出怪表4", description = "关卡出怪配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "怪物" },
                new FieldRelation { fieldName = "boss", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "Boss" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "波次奖励" }
            }},
            new ConfigTableInfo { tableName = "map_act_x", displayName = "出怪表X", description = "关卡出怪配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "怪物" },
                new FieldRelation { fieldName = "boss", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "Boss" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "波次奖励" }
            }},
            new ConfigTableInfo { tableName = "mapx", displayName = "地图X表", description = "地图X房间配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num", description = "初始怪物" }
            }},
            new ConfigTableInfo { tableName = "monthlycard", displayName = "月卡表", description = "月卡配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" },
                new FieldRelation { fieldName = "recharge_id", targetTable = "recharge", targetField = "id", description = "购买立即获得" }
            }},
            new ConfigTableInfo { tableName = "name", displayName = "名字表", description = "随机名字配置" },
            new ConfigTableInfo { tableName = "outenemypoint", displayName = "外出敌人点表", description = "外出敌人点配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num", description = "怪物" }
            }},
            new ConfigTableInfo { tableName = "pandora", displayName = "潘多拉表", description = "潘多拉奖励池配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励池" }
            }},
            new ConfigTableInfo { tableName = "pass", displayName = "通行证表", description = "通行证奖励配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "免费奖励" },
                new FieldRelation { fieldName = "rewards2", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "付费奖励" }
            }},
            new ConfigTableInfo { tableName = "player", displayName = "玩家表", description = "玩家基础配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "equips", targetTable = "equip", targetField = "id", description = "初始装备" }
            }},
            new ConfigTableInfo { tableName = "playerlevel", displayName = "玩家等级表", description = "玩家等级成长配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "升级消耗" },
                new FieldRelation { fieldName = "talent_id", targetTable = "playertalent", targetField = "id", description = "天赋ID" },
                new FieldRelation { fieldName = "target_id", targetTable = "player", targetField = "id", description = "关联玩家" }
            }},
            new ConfigTableInfo { tableName = "playerskin", displayName = "玩家皮肤表", description = "玩家皮肤配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "激活消耗" },
                new FieldRelation { fieldName = "target_id", targetTable = "player", targetField = "id", description = "关联玩家" }
            }},
            new ConfigTableInfo { tableName = "playerstage", displayName = "玩家境界表", description = "玩家境界配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "突破消耗" },
                new FieldRelation { fieldName = "target_id", targetTable = "player", targetField = "id", description = "关联玩家" }
            }},
            new ConfigTableInfo { tableName = "playertalent", displayName = "玩家天赋表", description = "玩家天赋配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "升级消耗" },
                new FieldRelation { fieldName = "lostConsumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "抛弃消耗" }
            }},
            new ConfigTableInfo { tableName = "prop", displayName = "道具表", description = "道具配置" },
            new ConfigTableInfo { tableName = "pushboxreward", displayName = "推箱奖励表", description = "推箱游戏奖励", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "qirilibao", displayName = "七日礼包表", description = "七日礼包配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "免费奖励" },
                new FieldRelation { fieldName = "rewards2", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "付费奖励" }
            }},
            new ConfigTableInfo { tableName = "quest", displayName = "任务表", description = "任务配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "任务奖励" },
                new FieldRelation { fieldName = "next", targetTable = "quest", targetField = "id", description = "下一个任务" }
            }},
            new ConfigTableInfo { tableName = "recharge", displayName = "充值表", description = "充值配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" },
                new FieldRelation { fieldName = "children", targetTable = "recharge", targetField = "id", description = "打包售卖关联的孩子" }
            }},
            new ConfigTableInfo { tableName = "rechargegift", displayName = "累充礼物表", description = "累充礼物配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "rune", displayName = "符文表", description = "符文基础配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "attr_id", targetTable = "attribute", targetField = "id", description = "属性ID" }
            }},
            new ConfigTableInfo { tableName = "runelevel", displayName = "符文等级表", description = "符文等级配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "target_id", targetTable = "rune", targetField = "id", description = "关联符文" }
            }},
            new ConfigTableInfo { tableName = "scene", displayName = "场景表", description = "场景配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "fight_cf_name", targetTable = "fight_sample", targetField = "id", relationFormat = "表名", description = "战斗配置表名" },
                new FieldRelation { fieldName = "map_cf_name", targetTable = "map", targetField = "id", relationFormat = "表名", description = "地图配置表名" }
            }},
            new ConfigTableInfo { tableName = "serverError", displayName = "服务器错误表", description = "服务器错误码配置" },
            new ConfigTableInfo { tableName = "signin", displayName = "签到表", description = "签到奖励配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "签到奖励" }
            }},
            new ConfigTableInfo { tableName = "skill", displayName = "技能表", description = "技能配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "to_partner_buff", targetTable = "buff", targetField = "id", description = "给己方的buff" },
                new FieldRelation { fieldName = "to_enemy_buff", targetTable = "buff", targetField = "id", description = "给敌方的buff" }
            }},
            new ConfigTableInfo { tableName = "skilllevel", displayName = "技能等级表", description = "技能等级配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "target_id", targetTable = "skill", targetField = "id", description = "关联技能" }
            }},
            new ConfigTableInfo { tableName = "systemopen", displayName = "系统开放表", description = "系统开放条件配置" },
            new ConfigTableInfo { tableName = "test_map_act", displayName = "测试出怪表", description = "测试关卡出怪配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "monsters", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "怪物" },
                new FieldRelation { fieldName = "boss", targetTable = "enemy", targetField = "id", relationFormat = "id_lv_num_time", description = "Boss" },
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "波次奖励" }
            }},
            new ConfigTableInfo { tableName = "title", displayName = "称号表", description = "称号配置" },
            new ConfigTableInfo { tableName = "trainbreak", displayName = "修炼突破表", description = "修炼突破配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "突破消耗" },
                new FieldRelation { fieldName = "quest", targetTable = "quest", targetField = "id", description = "突破任务" }
            }},
            new ConfigTableInfo { tableName = "trainlevel", displayName = "修炼等级表", description = "修炼等级配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "consumes", targetTable = "prop", targetField = "id", relationFormat = "item_id_num", description = "修炼消耗" }
            }},
            new ConfigTableInfo { tableName = "vip", displayName = "VIP表", description = "VIP等级配置", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "免费礼包" },
                new FieldRelation { fieldName = "recharge_id", targetTable = "recharge", targetField = "id", description = "付费礼包" }
            }},
            new ConfigTableInfo { tableName = "fishingreward", displayName = "钓鱼奖励表", description = "钓鱼游戏奖励", relations = new List<FieldRelation> {
                new FieldRelation { fieldName = "rewards", targetTable = "prop", targetField = "id", relationFormat = "type_id_num", description = "奖励" }
            }},
            new ConfigTableInfo { tableName = "dirty_words", displayName = "敏感词表", description = "敏感词过滤配置（TXT文件）", fileExtension = ".txt" },
            new ConfigTableInfo { tableName = "奖励格式说明", displayName = "奖励格式说明", description = "奖励数据格式说明文档（TXT文件）", fileExtension = ".txt" }
        };

        MarkExistingTables();
        return _cachedData;
    }

    private static void MarkExistingTables()
    {
        _existingTableNames = new HashSet<string>();
        
        string configPath = Path.Combine(Application.dataPath, CONFIG_PATH);
        if (Directory.Exists(configPath))
        {
            string[] jsonFiles = Directory.GetFiles(configPath, "*.json");
            foreach (string file in jsonFiles)
            {
                string tableName = Path.GetFileNameWithoutExtension(file);
                _existingTableNames.Add(tableName.ToLower());
            }
        }

        string configPathAlt = Path.Combine(Application.dataPath, "../Resources/Resources_moved/config");
        if (Directory.Exists(configPathAlt))
        {
            string[] jsonFilesAlt = Directory.GetFiles(configPathAlt, "*.json");
            foreach (string file in jsonFilesAlt)
            {
                string tableName = Path.GetFileNameWithoutExtension(file);
                _existingTableNames.Add(tableName.ToLower());
            }
        }

        foreach (var table in _cachedData)
        {
            bool existInConfig = _existingTableNames.Contains(table.tableName.ToLower());
            
            if (!existInConfig && table.fileExtension == ".txt")
            {
                string excelFolderPath = GetExcelFolderPath();
                if (!string.IsNullOrEmpty(excelFolderPath))
                {
                    string txtPath = Path.Combine(excelFolderPath, $"{table.tableName}{table.fileExtension}");
                    existInConfig = File.Exists(txtPath);
                }
            }
            
            table.isExistInProject = existInConfig;
        }
    }

    public static bool IsTableExistInConfigFolder(string tableName)
    {
        string configPath = Path.Combine(Application.dataPath, CONFIG_PATH);
        if (!Directory.Exists(configPath))
            return false;

        var tableInfo = GetTableInfo(tableName);
        string extension = tableInfo?.fileExtension ?? ".xlsx";
        
        string jsonPath = Path.Combine(configPath, $"{tableName}.json");
        string configPathAlt = Path.Combine(Application.dataPath, "../Resources/Resources_moved/config");
        string jsonPathAlt = Path.Combine(configPathAlt, $"{tableName}.json");
        
        if (extension == ".txt")
        {
            string excelFolderPath = GetExcelFolderPath();
            if (!string.IsNullOrEmpty(excelFolderPath))
            {
                string txtPath = Path.Combine(excelFolderPath, $"{tableName}{extension}");
                if (File.Exists(txtPath))
                    return true;
            }
        }
        
        return File.Exists(jsonPath) || File.Exists(jsonPathAlt);
    }

    public static ConfigTableInfo GetTableInfo(string tableName)
    {
        return GetAllTableInfo().Find(x => x.tableName.Equals(tableName, StringComparison.OrdinalIgnoreCase));
    }

    public static List<string> GetAllTableNames()
    {
        return GetAllTableInfo().ConvertAll(x => x.tableName);
    }

    public static List<ReverseRelation> GetReverseRelations(string targetTableName)
    {
        List<ReverseRelation> result = new List<ReverseRelation>();
        
        foreach (var table in GetAllTableInfo())
        {
            foreach (var relation in table.relations)
            {
                if (relation.targetTable.Equals(targetTableName, StringComparison.OrdinalIgnoreCase))
                {
                    result.Add(new ReverseRelation
                    {
                        sourceTable = table.tableName,
                        sourceDisplayName = table.displayName,
                        fieldName = relation.fieldName,
                        description = relation.description,
                        relationFormat = relation.relationFormat
                    });
                }
            }
        }
        
        return result;
    }

    public static string FormatRelationValue(string format, string value)
    {
        if (string.IsNullOrEmpty(format) || string.IsNullOrEmpty(value))
            return value;
        
        string[] parts = value.Split('_');
        string result = "";
        
        switch (format.ToLower())
        {
            case "item_id_num":
                if (parts.Length >= 3)
                    result = $"类型:{parts[0]}, ID:{parts[1]}, 数量:{parts[2]}";
                break;
            case "type_id_num":
                if (parts.Length >= 3)
                    result = $"类型:{parts[0]}, ID:{parts[1]}, 数量:{parts[2]}";
                break;
            case "id_pos_lv":
                if (parts.Length >= 3)
                    result = $"ID:{parts[0]}, 位置:{parts[1]}, 等级:{parts[2]}";
                break;
            case "id_lv_num":
                if (parts.Length >= 3)
                    result = $"ID:{parts[0]}, 等级:{parts[1]}, 数量:{parts[2]}";
                break;
            case "id_lv_num_time":
                if (parts.Length >= 4)
                    result = $"ID:{parts[0]}, 等级:{parts[1]}, 数量:{parts[2]}, 时间:{parts[3]}";
                break;
            case "buffid_lv":
                if (parts.Length >= 2)
                    result = $"BuffID:{parts[0]}, 等级:{parts[1]}";
                break;
            case "rune_id_num":
                if (parts.Length >= 2)
                    result = $"符文ID:{parts[0]}, 数量:{parts[1]}";
                break;
            case "equip_id_num":
                if (parts.Length >= 2)
                    result = $"装备ID:{parts[0]}, 数量:{parts[1]}";
                break;
            case "表名":
                result = $"表名: {value}";
                break;
        }
        
        return string.IsNullOrEmpty(result) ? value : result;
    }

    public static List<string> GetRelatedTableNames(string tableName)
    {
        var tableInfo = GetTableInfo(tableName);
        if (tableInfo == null)
            return new List<string>();
        
        return tableInfo.relations.Select(r => r.targetTable).Distinct().ToList();
    }

    public static List<string> GetAllDisplayNames()
    {
        return GetAllTableInfo().ConvertAll(x => $"{x.displayName} ({x.tableName})");
    }

    public static List<ConfigTableInfo> GetExistingTables()
    {
        return GetAllTableInfo().Where(x => x.isExistInProject).ToList();
    }

    public static bool IsTableExist(string tableName)
    {
        if (_existingTableNames == null)
        {
            GetAllTableInfo();
        }
        return _existingTableNames.Contains(tableName.ToLower());
    }

    public static void ClearCache()
    {
        _cachedData = null;
        _existingTableNames = null;
    }
}
