// priority: 9
// 玩家攻击事件
//参考脆骨症夜鸢大佬的代码
//不清楚优化会不会更好，但是写起来方便一点
function tetraplayerattack(event) {
    let player = event.source.player;
    let item = player.getMainHandItem();
    if (!item.item instanceof $ModularItem) return;

    let effects = getAllEffects(item);
    effects.forEach(effect => {
        let strategy = tetraPlayerAttackStrategies[effect.name] || tetraPlayerAttackStrategies.default;
        strategy(event, player, effect.level, item, effect.name, effect.efficiency);
    });
}
const tetraPlayerAttackStrategies = {
    //永恒疯狂
    'eternal_madness': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type != 'player') return

        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity
        let pestilence = player.getAttributeTotalValue('kubejs:pestilence')

        let amount = entity.persistentData.getDouble('eternal_madness_amount') ?? 0
        amount += effectLevel * pestilence / 100

        entity.modifyAttribute('minecraft:generic.max_health', effectname, -amount, 'addition')
        entity.persistentData.putDouble('eternal_madness_amount', amount)

    },
    //延申
    'kubejs_reaching': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        let distance = player.distanceToSqr(entity)

        if (distance < 0) return

        if (event.getSource().is($DamageTypeTags.IS_PROJECTILE)) {
            simple_main_increased_damage(player, effectLevel * Math.log(distance * distance) * efficiency / 100)
        } else {
            simple_main_increased_damage(player, effectLevel * Math.log(distance * distance) / 100)
        }
    },
    //雷火超载
    'thunder_fire_overload': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        let entity = event.entity
        if (type == 'kubejs_fire_damage') {
            //CD
            let time = player.persistentData.getInt(effectname) ?? 0
            let CD = Math.abs(player.age - time)
            if (CD < 20) return
            player.persistentData.putInt(effectname, player.age)

            //获取唤雷等级效率，玩家火焰伤害面板
            let call_thunder_level = get_mainhand_call_thunder(player).level
            let call_thunder_efficiency = get_mainhand_call_thunder(player).efficiency
            let fire_damage = player.getAttributeTotalValue('kubejs:fire_damage')

            //攻击范围
            let range = call_thunder_efficiency * efficiency / 100
            //攻击伤害
            let damageValue = fire_damage * call_thunder_level * effectLevel / 100

            let entityList = getLivingWithinRadius(entity.getLevel(), entity.position(), range)
            //产生一次爆炸当作装饰
            let explosion = event.entity.block.createExplosion();
            explosion.strength(3);
            explosion.explode();
            // 遍历实体列表
            entityList.forEach(entity => {
                if (entity.isLiving() && entity != player) {
                    let spawn_entity = entity.level.createEntity("minecraft:lightning_bolt");
                    spawn_entity.setPosition(entity.x, entity.y, entity.z);
                    spawn_entity.setVisualOnly(true)
                    spawn_entity.spawn();
                    simpleAttackEntity(true, player, entity, 'player_explosion', damageValue)
                }
            })
        }
    },
    //炎葬
    'the_incinerator': function (event, player, effectLevel, item, effectname, efficiency) {

        let type = event.getSource().getType().toString();
        if (type == 'kubejs_fire_damage') return // 防循环
        let time = player.persistentData.getInt('soul_form') ?? 0 // 防止卡永久蓝火
        let CD = Math.abs(player.age - time)

        let entity = event.entity
        let posX = entity.x
        let posY = entity.y
        let posZ = entity.z

        let health = player.health
        let maxHealth = player.maxHealth
        let random = 1.2 // buff触发概率


        // 常态20%上一层11.5s的炽热烙印，攻击带有烙印的目标回复血量
        // [回复量 = 最大生命值*等级*炽热烙印等级/100 (1级1%，5级5%)]

        if (entity.hasEffect('cataclysm:blazing_brand')) {

            // 获取已有的效果
            let effect = entity.getEffect('cataclysm:blazing_brand')
            // 获取效果等级
            let amplifier = effect.getAmplifier()
            // 获取效果时长
            // let duration = effect.getDuration()
            player.setHealth(health + maxHealth * effectLevel * (amplifier + 1) / 100 * 0.6)

            // 切形态后烙印可叠加到5层，时长不变，叠层概率增至40%，
            // 攻击时造成附伤 [伤害量=火焰伤害*等级*烙印等级/3*(2-当前生命值/最大生命值) ]
            // 魂焰形态期间会持续流失生命，自身生命值越低附加伤害越高

            if (ShowModelHelper.getShowModels(item).contains("form_2")) {
                // 防止卡永久蓝火
                if (CD > 20 * 60 * 3) {
                    ShowModelHelper.clearShowModel(item)
                    ShowModelHelper.addShowModel(item, "form_1", "item")
                    return
                }
                // 叠层
                if (amplifier < 4) {
                    player.level.spawnParticles('cataclysm:flare_explode', true, posX, posY + 1, posZ, 0.05, 0.05, 0.05, 0.02, 10)
                    if (Math.random() <= random * 2) {
                        entity.potionEffects.add('cataclysm:blazing_brand', 20 * 11.5, amplifier + 1)
                    }
                }
                else {
                    // 满层额外特效
                    player.level.spawnParticles('cataclysm:ignis_soul_explode', true, posX, posY + 1, posZ, 0.05, 0.05, 0.05, 0.02, 1)
                    player.level.spawnParticles('cataclysm:flare_explode', true, posX, posY + 1, posZ, 0.05, 0.05, 0.05, 0.02, 10)
                    if (Math.random() <= random * 2) {
                        // player.tell("增加时长")
                        entity.potionEffects.add('cataclysm:blazing_brand', 20 * 11.5, amplifier)
                    }
                }
                // 额外伤害
                let fire_damage = player.getAttributeTotalValue('kubejs:fire_damage') * effectLevel * amplifier / 3 * (2 - health / maxHealth)
                simpleAttackEntity(true, player, entity, 'kubejs_fire_damage', fire_damage)
            }
        }
        else {
            if (Math.random() <= random) {
                entity.potionEffects.add('cataclysm:blazing_brand', 20 * 11, 0)
            }
        }
    },
    // 转化
    'invert': function (event, player, effectLevel, item, effectname, efficiency) {
        event.amount = event.amount * (1 + player.persistentData.getDouble('fire_increased_damag') / 100)
    },
    //翼龙灵魂
    'subterranodon': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type != 'player' && type != 'trident') return

        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 10) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity
        let level = player.level

        let dinosaurSpirit = ACEntityRegistry.DINOSAUR_SPIRIT.get().create(level);

        dinosaurSpirit.setPos(entity.getX(), entity.getY() + entity.getBbHeight(), entity.getZ());
        dinosaurSpirit.setDinosaurType(DinosaurSpiritEntity.DinosaurType.SUBTERRANODON)
        dinosaurSpirit.setPlayerUUID(player.uuid);
        dinosaurSpirit.setAttackingEntityId(entity.id);
        dinosaurSpirit.lookAt(EntityAnchorArgument.Anchor.EYES, entity.getEyePosition());
        level.addFreshEntity(dinosaurSpirit);
        dinosaurSpirit.setEnchantmentLevel(efficiency);

        let fire_damage = player.getAttributeTotalValue('kubejs:fire_damage')
        for (let i = 1; i <= 4; i++) {
            entity.server.scheduleInTicks(15 * i, () => {
                if (!entity.onGround()) {
                    entity.level.spawnParticles('cataclysm:flare_explode', true, entity.x, entity.y, entity.z, 0, 0.05, 0, 1, 0.05)
                    simpleAttackEntity(true, player, entity, 'kubejs_fire_damage', fire_damage * effectLevel / 100)
                }
            })
        }

    },
    //浮空
    'floating': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        if (!entity.onGround()) {
            simple_main_increased_damage(player, effectLevel / 100)
        }
    },
    //灼燃
    'burn': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        entity.persistentData.putInt('burn', Math.floor(player.getAttributeTotalValue('kubejs:fire_damage') * effectLevel / 100))
    },
    //磁极—北
    'north_pole': function (event, player, effectLevel, item, effectname, efficiency) {

        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 / player.getAttributeTotalValue('minecraft:generic.attack_speed')) return
        player.persistentData.putInt(effectname, player.age)

        //增加雷属性伤害
        let type = event.getSource().getType().toString();
        if (type == 'lightningBolt') {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + effectLevel / 100)
        }


        if (type != 'player') return

        let entity = event.entity
        let strength_level = 0
        if ((player.hasEffect('minecraft:strength'))) {
            strength_level = player.getEffect('minecraft:strength').amplifier + 1
        }
        //获取武器攻击力
        let damageValue = item.item.getAttributeValue(item, $Attributes.ATTACK_DAMAGE) + 1 + strength_level * 3
        //获取唤雷等级和效率
        let call_thunder_level = get_call_thunder_level(player, item).level
        //获取副手磁极南等级
        let south_pole_effect_level = simpleGetTetraEffectLevel(player.getOffHandItem(), 'south_pole')

        //物品攻击力 乘 副手磁极等级 乘主手磁极等级 乘 唤雷等级 乘 磁极北的效率增幅
        simple_call_thunder(
            entity, player,
            damageValue * (south_pole_effect_level / 100) * (effectLevel / 100) * call_thunder_level * (1 + efficiency / 100)
        )

    },
    //亡灵杀手
    'undead_killer': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        if (entity.isUndead()) {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + effectLevel / 100)
        }
    },
    //遗忆
    'undergarden_forgotten_metal': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        if (entity.type.split(':')[0] !== 'undergarden') {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.7)
        }
    },
    //重甲杀手
    'heavy_armor_killer': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        let armor = entity.getAttributeTotalValue('minecraft:generic.armor');

        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + effectLevel * armor / 100)
    },
    //世界核平
    'nuclear_bomb': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 10) return
        player.persistentData.putInt(effectname, player.age)

        let pestilence_amount = player.getAttributeTotalValue('kubejs:pestilence');

        //获取使用的总等级
        let total_effect = simple_get_radiation(player).level * (1 + effectLevel / 100)

        let total_efficiency = simple_get_radiation(player).efficiency * efficiency / 100

        // 获取周围实体
        let entityList = getLivingWithinRadius(player.getLevel(), player.position(), total_efficiency)
        // 遍历实体列表
        entityList.forEach(entity => {
            if (entity.isLiving() && entity != player) {
                entity.server.scheduleInTicks(1, () => {
                    simpleAttackEntity(true, player, entity, 'pestilence', pestilence_amount * total_effect)
                })
            }
        })

        let spawn_entity = player.level.createEntity("alexscaves:nuclear_explosion")
        spawn_entity.setSize(0)
        spawn_entity.setPosition(player.x, player.y, player.z);
        spawn_entity.spawn();


    },
    //辐光高照
    'acidic_radrock': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 10) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity
        let count = 0
        entity.potionEffects.active.forEach(ctx => {
            if (ctx.getEffect().getCategory() != 'HARMFUL') return
            count++
        })

        //获取辐射等级
        let radiation_level = simple_get_radiation(player).level


        if (count > radiation_level) return

        let random_effect = MAODLEFFECTS_HARMFUL[Math.floor(Math.random() * MAODLEFFECTS_HARMFUL.length)]
        if (random_effect != null) {
            event.entity.potionEffects.add(random_effect, 20 * 5, 0)
        }
    },
    //辐射
    'radiation': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString()
        if (type == 'pestilence') return

        let pestilence_amount = player.getAttributeTotalValue('kubejs:pestilence');
        let entity = event.entity;
        let radiation = entity.persistentData.getInt('radiation') ?? 0

        if (radiation == 0) {
            entity.persistentData.putInt('radiation', 1)
            // 安排每次攻击
            for (let i = 1; i <= simple_get_radiation(player).efficiency * 20; i++) {
                entity.getServer().scheduleInTicks(i, () => {
                    if (entity && entity.isAlive()) {
                        simpleAttackEntity(true, null, entity, 'pestilence', pestilence_amount * simple_get_radiation(player).level / 100);
                        entity.level.spawnParticles(
                            'alexscaves:acid_drop',
                            false,
                            entity.x + (Math.random() * 2 - 1),
                            entity.y + (Math.random() * 2 - 1),
                            entity.z + (Math.random() * 2 - 1),
                            0, 1, 0, 10, 0
                        );
                    }
                });
            }
            entity.getServer().scheduleInTicks(simple_get_radiation(player).efficiency * 20 + 1, () => {
                if (entity && entity.isAlive()) {
                    entity.persistentData.putInt('radiation', 0)
                }
            })
        }
    },


    //暴击
    'kubejs_criticalStrike': function (event, player, effectLevel, item, effectname, efficiency) {
        let amount = 0
        let random = Math.random() * 100
        //获取全身暴击率，暴击伤害
        let kubejs_criticalStrike_level = get_kubejs_criticalStrike(player).level
        let kubejs_criticalStrike_efficiency = get_kubejs_criticalStrike(player).efficiency - 100

        //获取赌徒的等级
        let gambler_level = simpleGetTetraEffectLevel(item, 'gambler')

        let dong_xi = arrmor_total_effect_level(player, 'dong_xi').level

        if (random < kubejs_criticalStrike_level) {
            //洞悉+自身暴击效果
            amount = amount + kubejs_criticalStrike_efficiency / 100 + dong_xi / 100
            //赌徒
            amount = amount * (1 + (1 - effectLevel / 100) * gambler_level)

            //窥愿珍珠效果实现
            let gazing_pearl = simpleGetTetraEffectLevel(item, 'gazing_pearl')
            if (gazing_pearl > 0) {
                let DeepOneReputation = $ACWorldData.get(player.level).getDeepOneReputation(player.getUuid())
                if (DeepOneReputation / 200 > Math.random()) {
                    amount = amount * 2
                }
            }
        }
        if (amount > 0) {
            simple_main_increased_damage(player, amount)
        }
    },
    // 远古之星
    'ancient_star': function (event, player, effectLevel, item, effectname, efficiency) {

        let attackSpeed = player.getAttributeTotalValue('minecraft:generic.attack_speed')
        // 攻击冷却(ticks)
        let cooldownTicks = 20.0 / Math.max(attackSpeed, 0.1)

        // 计算蓄力时间
        let currentTime = player.age
        let lastAttackTime = player.persistentData.getInt('ancient_star_last_attack') || 0
        let timeSinceLastAttack = currentTime - lastAttackTime
        // 转换为秒
        let chargeTime = Math.max(0, timeSinceLastAttack / 20.0)

        // 计算攻击冷却进度 (0~1)
        let cooldownProgress = Math.min(1.0, (timeSinceLastAttack + 0.5) / cooldownTicks)

        // 如果攻击冷却条已满，限制最大蓄力时间
        // 冷却时间对应的最大蓄力时间
        let maxChargeTime = cooldownTicks / 20.0
        if (cooldownProgress >= 1.0) {
            //最大蓄力时间
            chargeTime = Math.min(chargeTime, maxChargeTime)
        }

        // 计算伤害倍率
        let damageMultiplier = chargeTime * effectLevel / 100
        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + damageMultiplier)

        // 更新时间
        player.persistentData.putInt('ancient_star_last_attack', currentTime)
    },
    // 机械之星
    'machine_star': function (event, player, effectLevel, item, effectname, efficiency) {
        let totalCritChance = simpleGetTetraEffectLevel(item, 'kubejs_criticalStrike') || 0

        // 暴击溢出转增伤逻辑
        if (totalCritChance > 100) {
            let critOverflow = totalCritChance - 100
            let bonusCritDamage = critOverflow * effectLevel / 100

            // 应用额外增伤
            let damageMultiplier = (bonusCritDamage / 100.0)
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + damageMultiplier)
        }
    },
    //真——变换之刃
    'true_ever_changing': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString()
        if (type == 'player') {
            for (let i = 0; i < 9; i++) {
                player.server.scheduleInTicks(i, () => {
                    simpleAttackEntity(true, player, event.entity, 'magic', 1)
                })
            }
        }
        if (type == 'magic') {
            event.amount *= 0.01
        }


        let major_modules = item.item.getMajorModules(item)
        let minor_modules = item.item.getMinorModules(item)

        if (major_modules) {
            for (let module of major_modules) {
                // 获取模块
                if (module) {
                    let variantData = module.getVariantData();
                    let variantKeys = variantData.map(data => data.key);
                    // 随机选择一个变体 Key
                    let randomKey = variantKeys[Math.floor(Math.random() * variantKeys.length)];
                    // 替换武器模块为选中的变体
                    module.addModule(item, randomKey, player)
                    updateItemEffects(item);
                }
            }
        }
        if (minor_modules) {
            for (let module of minor_modules) {
                if (module) {
                    let variantData = module.getVariantData();
                    let variantKeys = variantData.map(data => data.key);
                    // 随机选择一个变体 Key
                    let randomKey = variantKeys[Math.floor(Math.random() * variantKeys.length)];
                    // 替换武器模块为选中的变体
                    module.addModule(item, randomKey, player)
                    updateItemEffects(item);
                }
            }
        }
    },
    //变换之刃
    'ever_changing': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString()
        if (type == 'player') {
            for (let i = 0; i < 4; i++) {
                player.server.scheduleInTicks(i, () => {
                    simpleAttackEntity(true, player, event.entity, 'magic', 1)
                })
            }
        }
        if (type == 'magic') {
            event.amount *= 0.01
        }


        let module = item.getItem().getModuleFromSlot(item, "sword/blade")
        if (module) {
            let variantData = module.getVariantData();
            let variantKeys = variantData.map(data => data.key);
            // 随机选择一个变体 Key
            let randomKey = variantKeys[Math.floor(Math.random() * variantKeys.length)];
            // 替换武器模块为选中的变体
            module.addModule(item, randomKey, player)
            updateItemEffects(item);
        }
    },
    //薄瞑
    'twilight': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity
        if (Math.random() * 100 < efficiency) {
            simpleAttackEntity(true, null, entity, 'attributeslib:cold_damage', entity.getMaxHealth() * effectLevel / 100)
        }
        if (Math.random() * 100 < efficiency) {
            simpleAttackEntity(true, null, entity, 'kubejs_fire_damage', entity.getMaxHealth() * effectLevel / 100)
        }
        if (Math.random() * 100 < efficiency) {
            simpleAttackEntity(true, null, entity, 'pestilence', entity.getMaxHealth() * effectLevel / 100)
        }
        if (Math.random() * 100 < efficiency) {
            simpleAttackEntity(true, null, entity, 'common', entity.getMaxHealth() * effectLevel / 100)
        }
    },
    //穿刺
    'elder_guardian_scale': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString()
        if (type != 'trident') return

        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + effectLevel / 100)
    },
    //爆燃
    'deflagration': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type != 'player') return

        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 100) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity
        let fire_time = entity.nbt.Fire || 0
        if (player.isCrouching()) {
            entity.setRemainingFireTicks(0)
            entity.server.scheduleInTicks(1, () => {
                simpleAttackEntity(true, player, event.entity, 'explosion', fire_time * effectLevel / 100)
            })

            let explosion = entity.block.createExplosion()
            explosion.strength(2)
            explosion.causesFire(true)
            explosion.explode()
        }
    },
    //游侠
    'blackmetal_block': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        //获取攻击敌人周围的实体
        let entityList = Math.min(getLivingWithinRadius(entity.getLevel(), entity.position(), 10 + effectLevel), 9)


        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + (0.1 * entityList.length))
    },
    // 独木难支
    'cursium_block': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        let range = Math.max(1, Math.abs(5 - effectLevel))
        let entityList = getLivingWithinRadius(entity.getLevel(), entity.position(), range)

        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + Math.max(0, (0.7 - (entityList.length * 0.1))))
    },
    // 苦寒坚冰
    'bitter_cold_shard': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type != 'player') return

        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity;
        let Damage = player.getAttributeTotalValue('minecraft:generic.attack_damage') / 6
        // 获取攻击范围内的敌人
        let entityList = getLivingWithinRadius(entity.getLevel(), entity.position(), 8);
        let enemies = entityList.filter(e => e.isLiving() && e != player && e != entity);

        // 弹跳次数，保底5次
        let bounceCount = 5 + (enemies.length * (1 + effectLevel));
        // 创建弹跳目标列表（包含原目标和其他敌人）
        let bounceTargets = [entity];
        for (let i = 0; i < enemies.length; i++) {
            bounceTargets.push(enemies[i]);
        }

        bitterColdShardBounce(player, entity, bounceTargets, Damage, bounceCount, 0, event.source);

        player.server.runCommandSilent(`playsound minecraft:block.glass.break player @a ${entity.x.toFixed(1)} ${entity.y.toFixed(1)} ${entity.z.toFixed(1)} 1 1.2`);
    },
    //冰霜号角
    'stormcallers_horn': function (event, player, effectLevel, item, effectname, efficiency) {
        player.potionEffects.add('born_in_chaos_v1:snow_storm', 20 * 5, 0)
    },
    //暗影棒
    'dark_rod': function (event, player, effectLevel, item, effectname, efficiency) {
        event.entity.potionEffects.add('minecraft:darkness', 20 * 5, effectLevel - 1)
    },
    // 贯虹
    'guan_hong': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type != 'arrow') return;

        let time = player.persistentData.getInt('guan_hong') ?? 0;

        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + effectLevel * time * time / 100)

        player.persistentData.remove('guan_hong')
    },
    // 充能紫晶
    'charged_amethyst_block': function (event, player, effectLevel, item, effectname, efficiency) {

        let entity = event.entity;
        let type = event.getSource().getType().toString();
        if (type != 'player') return

        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 2) return
        player.persistentData.putInt(effectname, player.age)

        let Level = simpleGetTetraEffectLevel(item, 'charged_amethyst_block')

        let entityX = entity.x
        let entityY = entity.y
        let entityZ = entity.z
        let floatHeight = entityY + 4

        //浮空和充能标记
        if (entity.onGround()) {
            //升起粒子
            drawPortalColumn(entity, player)
            // 把敌人顶起来
            entity.move('self', new Vec3d(0, 4, 0))

            // 标记为浮空状态
            entity.persistentData.putInt('amethyst_floating', player.age + 60 + (4 * Level))

            // 持续滞空,每1刻传送到固定高度，持续5秒
            for (let airTime = 1; airTime < 60 + (4 * Level); airTime++) {
                entity.getServer().scheduleInTicks(airTime * 1, () => {
                    entity.teleportTo(entityX, floatHeight, entityZ)
                })
            }

        }

        // 对浮空目标的充能
        let floatingUntil = entity.persistentData.getInt('amethyst_floating') || 0
        let isFloating = player.age < floatingUntil || !entity.onGround()

        if (isFloating) {
            // 检查充能衰减（距离上次充能超过5秒则重置）
            let lastChargeTime = entity.persistentData.getInt('last_charge_time') || 0
            let timeSinceLastCharge = player.age - lastChargeTime

            let chargeLevel = entity.persistentData.getInt('amethyst_charge') || 0

            // 如果超过5秒没有充能，重置充能
            if (timeSinceLastCharge > 100) {
                chargeLevel = 0
            }

            // 充能标记,累积充能层数
            chargeLevel = Math.min(chargeLevel + 1, 3 + Level) // 最多3+等级层
            entity.persistentData.putInt('amethyst_charge', chargeLevel)

            // 充能粒子效果
            for (let i = 0; i < chargeLevel; i++) {
                let angle = (i / chargeLevel) * 2 * 3.1415926
                let radius = 0.8 + i * 0.3
                let particleX = entity.x + Math.cos(angle) * radius
                let particleZ = entity.z + Math.sin(angle) * radius
                player.level.spawnParticles('minecraft:electric_spark', true,
                    particleX, entity.y + 1 + i * 0.5, particleZ, 0.1, 0.1, 0.1, 0.05, 2)
            }

            // 充能音效
            player.server.runCommandSilent(`playsound minecraft:block.amethyst_block.chime player @a ${entity.x} ${entity.y} ${entity.z} 0.5 ${1.0 + chargeLevel * 0.2}`)

            // 消耗充能层数获得额外效果
            if (chargeLevel >= 3) {
                // 充能爆发范围伤害
                let nearbyEntities = getLivingWithinRadius(entity.getLevel(), entity.position(), 5)
                nearbyEntities.forEach(nearbyEntity => {
                    if (nearbyEntity.isLiving() && nearbyEntity != player) {
                        entity.server.scheduleInTicks(1, () => {
                            simpleAttackEntity(true, player, nearbyEntity, 'common', player.getAttributeTotalValue('minecraft:generic.attack_damage') * 1.6)
                            //斩击粒子
                            drawSingleRandomSlashLineWithOffset(nearbyEntity, 'minecraft:wax_off', 0, player)
                            // 充能爆发粒子
                            player.level.spawnParticles('minecraft:sonic_boom', true,
                                nearbyEntity.x, nearbyEntity.y + 1, nearbyEntity.z, 0.3, 0.3, 0.3, 0.1, 3)
                        })
                    }
                })
                // 重置充能
                entity.persistentData.putInt('amethyst_charge', 0)
                // 爆发音效
                player.server.runCommandSilent(`playsound minecraft:block.amethyst_cluster.break player @a ${entity.x} ${entity.y} ${entity.z} 1.0 0.8`)
            }
        }

        // 充能衰减同时记录最后充能时间，避免重复计时器（每次攻击都有要计时不如记录最后时间来检查）
        entity.persistentData.putInt('last_charge_time', player.age)
    },
    // 风之力
    'wind_iron_block': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity;
        let type = event.getSource().getType().toString();
        if (type != 'player') return


        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 10) return
        player.persistentData.putInt(effectname, player.age)

        let Level = simpleGetTetraEffectLevel(item, 'wind_iron_block')

        //风粒子
        drawWindColumn(entity, player)
        // 把敌人顶起来
        entity.move('self', new Vec3d(0, 5, 0))

        // 每秒额外伤害
        let checkAirDamage = (count) => {
            entity.getServer().scheduleInTicks(count, () => {
                if (!entity.onGround() && entity.isAlive()) {

                    simpleAttackEntity(true, player, entity, "common", player.getAttributeTotalValue('minecraft:generic.attack_damage') * (0.3 + Level / 3))
                    drawSingleRandomSlashLineWithOffset(entity, 'minecraft:cloud', 0, player)
                    // 递归检查下一秒
                    checkAirDamage(count + 1)
                }
            })
        }
        // 开始第1秒的检查
        checkAirDamage(1)

    },
    // 凝结之风
    'congeal_wind': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity;
        let type = event.getSource().getType().toString();
        if (type != 'player') return

        if (!entity.onGround()) {
            entity.potionEffects.add('minecraft:slowness', 20 * 3, 5)
        }
    },
    // 砖块
    'brick': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity;
        entity.potionEffects.add('born_in_chaos_v1:bone_fracture', 20 * 1, 1)
    },
    // 海洋之心
    'ocean_heart': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity;
        let type = event.getSource().getType().toString();
        if (type != 'player') return

        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 10) return
        player.persistentData.putInt(effectname, player.age)

        //水柱粒子
        drawWaterColumn(entity, player)
        // 把敌人顶起来
        entity.move('self', new Vec3d(0, 6, 0))

        let tide_level = get_specific_effect(player, 'tide').level

        // 第一次额外伤害 - 0.25秒后
        entity.getServer().scheduleInTicks(5, () => {
            simpleAttackEntity(true, player, entity, 'common', player.getAttributeTotalValue('minecraft:generic.attack_damage') * (effectLevel / 100) * (1 + tide_level / 100))
            player.level.spawnParticles('minecraft:bubble_pop', true,
                entity.x, entity.y + 1, entity.z, 0.5, 0.5, 0.5, 0.1, 8)
        })

        // 第二次额外伤害 - 0.5秒后
        entity.getServer().scheduleInTicks(10, () => {
            simpleAttackEntity(true, player, entity, 'common', player.getAttributeTotalValue('minecraft:generic.attack_damage') * (effectLevel / 100) * (1 + tide_level / 100))
            player.level.spawnParticles('minecraft:bubble_pop', true,
                entity.x, entity.y + 1, entity.z, 0.5, 0.5, 0.5, 0.1, 12)
        })
    },
    // 火药
    'gunpowder': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 3) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity;

        let Level = simpleGetTetraEffectLevel(item, 'gunpowder')
        let baseDamage = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        let entityList = getLivingWithinRadius(entity.getLevel(), entity.position(), 2)

        // 攻击范围内的敌人
        entityList.forEach(nearbyEntity => {
            if (nearbyEntity.isLiving() && nearbyEntity != player) {
                entity.server.scheduleInTicks(1, () => {
                    let explosionDamage = (baseDamage * (1 + Level * 0.3))
                    simpleAttackEntity(true, player, nearbyEntity, 'minecraft:explosion', explosionDamage)
                })
            }
        })
        let posX = entity.x
        let posY = entity.y
        let posZ = entity.z

        player.level.spawnParticles('minecraft:explosion_emitter', true, posX, posY + 1, posZ, 0.05, 0.05, 0.05, 0.02, 10)

        // 爆炸音效
        player.server.runCommandSilent(`execute positioned ${posX} ${posY} ${posZ} run playsound minecraft:entity.generic.explode player @a ~ ~ ~ 1 1`)
    },
    // 奢侈打击
    'luxury_strike': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity;
        let type = event.getSource().getType().toString();
        if (type != 'player') return

        let goldCount = 0
        // 遍历玩家物品栏计算金锭数量
        for (let i = 0; i < 36; i++) {
            let stack = player.inventory.getStackInSlot(i)
            if (stack.id == 'minecraft:gold_ingot') {
                goldCount += stack.count
            }
        }

        if (goldCount > 0) {
            // 扣除金锭
            for (let i = 0; i < 36; i++) {
                let stack = player.inventory.getStackInSlot(i)
                if (stack.id == 'minecraft:gold_ingot' && stack.count > 0) {
                    stack.count = stack.count - 1
                    break
                }
            }

            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + effectLevel * 0.35)
            drawSingleRandomSlashLineWithOffset(entity, 'minecraft:wax_on', 0, player)
        }
    },
    // 壁垒
    'barrier': function (event, player, effectLevel, item, effectname, efficiency) {

        let armor = player.getAttributeTotalValue('minecraft:generic.armor')
        let armor_toughness = player.getAttributeTotalValue('minecraft:generic.armor_toughness')

        simple_main_increased_damage(player, armor * effectLevel / 1000 + armor_toughness * efficiency / 100)

    },
    //剧毒法术
    'poison_spell': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        entity.potionEffects.add('minecraft:poison', 20 * 10, 0)
        entity.potionEffects.add('minecraft:weakness', 20 * 10, 0)
        entity.potionEffects.add('minecraft:slowness', 20 * 10, 0)
    },
    //中毒
    'poison': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        entity.potionEffects.add('minecraft:poison', 20 * 10, effectLevel - 1)
    },
    //失明
    'blindness': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        entity.potionEffects.add('minecraft:blindness', 20 * 10, effectLevel - 1)
    },
    //迷失改 效果实现
    'disorienting_gai': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        let type = event.getSource().getType().toString();
        if (type == 'pestilence') {
            let effects_all_time = 0
            entity.potionEffects.active.forEach(ctx => {
                if (ctx.getEffect().getCategory() != 'HARMFUL') return
                let time = ctx.getDuration()
                effects_all_time = effects_all_time + time
            })
            let increase = Math.min((effects_all_time / 1200) * effectLevel, efficiency)

            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + increase / 100)
        }
    },
    //幸运横扫
    'lucky_sweep': function (event, player, effectLevel, item, effectname, efficiency) {
        // 检查冷却时间，避免循环触发
        let time = player.persistentData.getInt(effectname) ?? 0;
        let CD = Math.abs(player.age - time);
        if (CD < 60) return;
        player.persistentData.putInt(effectname, player.age);

        //获取玩家幸运
        let pasterdreamLuck = player.getAttributeTotalValue('pasterdream:luck');
        let genericLuck = player.getAttributeTotalValue('minecraft:generic.luck');
        let luckValue = (pasterdreamLuck + genericLuck) / 2;


        player.server.scheduleInTicks(1, () => {
            let weaponDamage = player.getAttributeTotalValue('minecraft:generic.attack_damage');


            //攻击伤害
            let sweepDamage = Math.max(1, weaponDamage * luckValue / 20);
            //攻击范围
            let sweepRange = Math.max(1, 3 + luckValue * 0.4);


            let targetEntity = event.entity;
            let entityList = getLivingWithinRadius(targetEntity.getLevel(), targetEntity.position(), sweepRange);

            entityList.forEach((entity, index) => {
                if (entity.isLiving() && entity != player) {
                    simpleAttackEntity(true, player, entity, 'common', sweepDamage);
                }
            });

            //横扫粒子效果
            player.server.runCommandSilent(`execute at ${player.name.string} run particle minecraft:sweep_attack ~ ~1 ~ 0 0 0 0 1`);
            //横扫音效
            player.server.runCommandSilent(`execute at ${player.name.string} run playsound minecraft:entity.player.attack.sweep player @a ~ ~ ~ 1 1`);

            let TriggerChance = 0.8 + luckValue * 0.01

            let recursiveSweep = (chance, count, delay) => {
                // [调试] 显示递归检查
                let roll = Math.random();


                if (roll >= chance) return;

                // 延迟执行，避免重叠
                player.server.scheduleInTicks(delay, () => {
                    //基础伤害的(1 - 0.1 * count)，每次递减10%
                    let currentSweepDamage = sweepDamage * Math.max(0.3, 1 - 0.1 * count);
                    let currentSweepRange = sweepRange << 1; // 范围翻倍

                    let currentEntityList = getLivingWithinRadius(targetEntity.getLevel(), targetEntity.position(), currentSweepRange);

                    currentEntityList.forEach((entity, index) => {
                        if (entity.isLiving() && entity != player) {
                            let time = entity.invulnerableTime;
                            entity.invulnerableTime = 0;
                            entity.attack(event.source, currentSweepDamage);
                            entity.invulnerableTime = time;
                        }
                    });

                    player.server.runCommandSilent(`execute at ${player.name.string} run particle minecraft:sweep_attack ~ ~1 ~ 0 0 0 0 1`);
                    player.server.runCommandSilent(`execute at ${player.name.string} run playsound minecraft:entity.player.attack.sweep player @a ~ ~ ~ 1 1`);

                    let nextChance = chance * 0.9;
                    // 延迟增加2tick
                    let nextDelay = delay + 2;

                    recursiveSweep(nextChance , count + 1, nextDelay);
                });
            };

            recursiveSweep(TriggerChance, 1, 2);

        });
    },
    'crystal_burst': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 3) return
        player.persistentData.putInt(effectname, player.age)

        // 获取被攻击的实体
        let target = event.entity

        if (!target || !target.isLiving()) {
            return
        }

        let Level = simpleGetTetraEffectLevel(item, 'crystal_burst')
        let baseDamage = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        //碎晶伤害计算
        let shardDamage = baseDamage * 0.25 * Level
        //调用碎晶函数，封装好了，直接调用
        crystal_burst(event, target, player, shardDamage, Level)
    },
    // 融梦极光斩击
    'dream_aurorian_steel': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity;
        let damageValue = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        let type = event.getSource().getType().toString();
        if (type != 'player') return

        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 2) return
        player.persistentData.putInt(effectname, player.age)

        if (simpleGetTetraEffectLevel(item, 'dream_aurorian_awakened') > 0) {
            drawAwakenedSlashParticleLine(entity, player)
        } else {
            //调用斩击粒子线接口
            drawSlashParticleLine(entity)
        }
        for (let i = 0; i < effectLevel; i++) {
            entity.server.scheduleInTicks(1, () => {
                simpleAttackEntity(true, player, event.entity, 'common', damageValue * efficiency / 100)
            })
        }
    },
    //死灰斩
    'dead_ashes': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 10) return
        player.persistentData.putInt(effectname, player.age)

        let damageValue = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        let viewVector = player.getViewVector(1.0);
        let normalizedVector = normalizeVector(viewVector)

        // 生成5道斧刃，中间一道，左右各两道
        for (let i = -2; i <= 2; i++) {
            let angleOffset = i * 0.35;
            let yaw = player.yaw + angleOffset;


            let spawn_entity = player.level.createEntity("cataclysm:axe_blade");
            spawn_entity.setPosition(player.x, player.y + 1, player.z);
            spawn_entity.setMotion(normalizedVector.x * 4 + angleOffset * 4, normalizedVector.y * 4, normalizedVector.z * 4 + angleOffset * 4);
            spawn_entity.setRotation(yaw, player.pitch);
            spawn_entity.setOwner(player);
            spawn_entity.persistentData.putInt('attack_addition', damageValue * effectLevel / 100);
            spawn_entity.spawn();
        }
    },
    //铁块防御
    'iron_blocks_defense': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 2) return
        player.persistentData.putInt(effectname, player.age)

        //let entity = event.entity;
        if (player.hasEffect('kubejs:iron_blocks_defense')) {
            let effect = player.getEffect('kubejs:iron_blocks_defense');
            let amplifier = effect.getAmplifier();//buff等级
            let duration = 20 * 8;//持续时间
            if (amplifier < 9) {
                player.potionEffects.add('kubejs:iron_blocks_defense', duration, amplifier + 1);
            }
            else {
                player.potionEffects.add('kubejs:iron_blocks_defense', duration, amplifier);
            }
        }
        else {
            player.potionEffects.add('kubejs:iron_blocks_defense', 20 * 8, 0);
        }
    },
    //冻伤
    'ice': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        entity.potionEffects.add('minecraft:slowness', 20 * 5, 3)
    },

    //冰冻
    'blue_ice': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        entity.potionEffects.add('minecraft:slowness', 20 * 2, 10)
    },
    //雷霆之怒
    'thunderous_wrath': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type == 'lightningBolt') {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + effectLevel / 100)
        }
    },
    //唤雷
    'call_thunder': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type != 'player') return

        if (forbid_call_thunder(player)) return

        let entity = event.entity;
        let time = entity.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(entity.age - time)
        if (CD < 10) return
        entity.persistentData.putInt(effectname, entity.age)

        let damageValue = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        let thunderCount = Math.max(1, Math.floor(effectLevel))


        if (simpleGetTetraEffectLevel(item, 'essence_of_the_storm') > 0) {
            simple_call_thunder(entity, player, damageValue * effectLevel * efficiency / 100)
        } else {
            // 循环生成雷霆
            for (let i = 0; i < thunderCount; i++) {
                entity.getServer().scheduleInTicks(5 * i, () => {
                    simple_call_thunder(entity, player, damageValue * efficiency / 100)
                })
            }
        }
    },
    //寒霜雪怪毛皮
    'frost_yeti_hair': function (event, player, effectLevel, item, effectname, efficiency) {
        player.potionEffects.add('jerotesvillage:rampant', 20 * 10, 2);
    },
    //虚空石
    'void_stone': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 2) return
        player.persistentData.putInt(effectname, player.age)

        //获取攻击力
        let damageValue = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        entity.server.scheduleInTicks(1, () => {
            simpleAttackEntity(true, player, event.entity, 'minecraft:out_of_world', damageValue * 0.5)
        })
    },
    //虚空核心
    'void_core': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 2) return
        player.persistentData.putInt(effectname, player.age)

        //获取攻击力
        let damageValue = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        entity.server.scheduleInTicks(1, () => {
            simpleAttackEntity(true, player, event.entity, 'magic', damageValue * 0.6)
        })
    },
    //龙首
    'dragon_head': function (event, player, effectLevel, item, effectname, efficiency) {
        //获取攻击力
        let damageValue = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        let type = event.getSource().getType().toString();
        if (type == 'indirectMagic') {
            event.amount = event.amount + damageValue * (1 + effectLevel / 100)
        }
    },
    //凋零骨头
    'withered_bone': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 10) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity;
        if (entity.hasEffect('minecraft:wither')) {
            let effect = entity.getEffect('minecraft:wither');
            let amplifier = effect.getAmplifier();
            let duration = effect.getDuration();
            entity.potionEffects.add('minecraft:wither', duration, amplifier + 1);
        } else {
            entity.potionEffects.add('minecraft:wither', 20 * 30, 0);
        }
    },
    //凋零之角
    'withered_horn': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 10) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity;
        if (entity.hasEffect('minecraft:wither')) {
            let effect = entity.getEffect('minecraft:wither');
            let amplifier = effect.getAmplifier();
            let duration = effect.getDuration();
            entity.potionEffects.add('minecraft:wither', duration, amplifier + 1);
        } else {
            entity.potionEffects.add('minecraft:wither', 20 * 30, 0);
        }
    },
    //锚把手
    'anchor_handle': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 5) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity
        entity.potionEffects.add('legendary_monsters:stun', 20 * 3, 0)
    },
    //炎魔肉
    'ignis': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        entity.potionEffects.add('cataclysm:blazing_brand', 20 * 3, 1)
    },
    //灵骸心炖
    'maledictus_heart_stew': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        //伤害类型
        let type = event.getSource().getType().toString();
        // 检查 NBT 数据中是否存在特定键
        if (!item.nbt || !item.nbt.contains("sword/blade:blade/wei_shi/maledictus_heart_stew")) return;
        if (type == 'cataclysm.maledictio_sagitta') {
            //受伤间隔设置为0防止丢失伤害
            event.entity.invulnerableTime = 0
        }
        if (type !== 'player') return;
        // 创建并生成两个实体
        for (let i = 0; i < 2; i++) {
            // 创建实体
            let zhao_huan_wu = entity.level.createEntity("cataclysm:phantom_arrow");
            if (i === 0) {
                // 第一个实体，x 坐标增加 4
                zhao_huan_wu.setPosition(entity.x + 4, entity.y + 5, entity.z);
                // 第一个实体的朝向
                zhao_huan_wu.setMotion(-1, -1, 0);
            } else {
                // 第二个实体，z 坐标增加 4
                zhao_huan_wu.setPosition(entity.x, entity.y + 5, entity.z + 4);
                // 第二个实体的朝向
                zhao_huan_wu.setMotion(0, -1, -1);
            }
            // 设置主人
            zhao_huan_wu.setOwner(player);
            // 生成实体
            zhao_huan_wu.spawn();
        }
    },
    //阴影石
    'shadow_stone': function (event, player, effectLevel, item, effectname, efficiency) {
        let lightLevel = getPlayerLightLevel(player)

        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + effectLevel / 100 - lightLevel * efficiency / 100)
    },
    //凋零骷髅头
    'wither_skeleton_skull': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 10) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity;
        if (entity.hasEffect('minecraft:wither')) {
            let effect = entity.getEffect('minecraft:wither');
            let amplifier = effect.getAmplifier();
            let duration = effect.getDuration();
            entity.potionEffects.add('minecraft:wither', duration, amplifier + 1);
        } else {
            entity.potionEffects.add('minecraft:wither', 20 * 30, 0);
        }
        if (player.isCrouching()) {
            if (entity.hasEffect('minecraft:wither')) {
                let effect = entity.getEffect('minecraft:wither');
                let amplifier = effect.getAmplifier();
                let damage = amplifier * 30;
                let health = entity.health
                entity.removeEffect('minecraft:wither');
                if (damage > health / 2) {
                    entity.setHealth(0)
                } else {
                    event.amount = event.amount + damage;
                }
            }
        }
    },
    //梦魇寻踪兽爪
    'nightmare_claw': function (event, player, effectLevel, item, effectname, efficiency) {
        player.potionEffects.add('minecraft:speed', 20 * 3, 0)
    },
    //血肉掠夺镰
    'despoil_sickle': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 2) return
        player.persistentData.putInt(effectname, player.age)

        let count = player.persistentData.getInt(YingYangCount)
        if (count < 10) return

        event.amount = event.amount + count / 6
        if (!player.hasEffect('kubejs:living')) {
            updateYingYangCount(player, count - 10)
        }
    },
    //窃命者之骨
    'lifestealer_bone': function (event, player, effectLevel, item, effectname, efficiency) {
        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage - 0.25)
        player.potionEffects.add('born_in_chaos_v1:vampiric_touch', 20 * 3, 0)
    },
    //蛇龙合金锭
    'serpon_alloy_ingot': function (event, player, effectLevel, item, effectname, efficiency) {
        let serpent_dominater_level = get_specific_effect(player, 'serpent_dominater').level
        let serpent_dominater_efficiency = get_specific_effect(player, 'serpent_dominater').efficiency
        let health_1 = player.maxHealth
        let health_2 = event.entity.maxHealth
        if (health_1 * (150 + serpent_dominater_level) > health_2) {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.9 + serpent_dominater_efficiency / 100)
        }
    },
    //龙血狗头人
    'dragon_blood': function (event, player, effectLevel, item, effectname, efficiency) {
        let health_1 = player.maxHealth
        let health_2 = event.entity.maxHealth
        if (health_1 * 50 > health_2) {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.5)
        }
    },
    //仙境木板
    'wonderland_planks': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type == 'arrow') {
            event.entity.invulnerableTime = 0
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.25)
        }
    },
    //阴影木板
    'shadow_planks': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type == 'arrow') {
            event.entity.invulnerableTime = 0
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.5)
        }
    },
    //远古木板
    'ancient_planks': function (event, player, effectLevel, item, effectname, efficiency) {
        let type = event.getSource().getType().toString();
        if (type == 'arrow') {
            event.entity.invulnerableTime = 0
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.5)
        }
    },
    //远古守卫者鳞甲
    'guardianscale': function (event, player, effectLevel, item, effectname, efficiency) {
        // 伤害类型
        let type = event.getSource().getType().toString();
        if (type == 'trident') {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 1.5)
        }
    },
    //染梦合金锭
    'ru_meng': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        let random = Math.random()
        if (random <= 0.2) {
            entity.potionEffects.add('kubejs:ru_meng', 20 * 4, 0)
        }
    },
    //炙焰金锭
    'moltengold_ingot': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 2) return
        player.persistentData.putInt(effectname, player.age)

        //获取火伤
        let a = player.getAttributeTotalValue('kubejs:fire_damage')
        // 获取被攻击的实体
        let entity1 = event.entity
        // 获取周围实体
        let entityList = getLivingWithinRadius(entity1.getLevel(), entity1.position(), 6)
        // 遍历实体列表
        entityList.forEach(entity => {
            if (entity.isLiving() && entity != entity1 && entity != player) {
                // 延迟一刻执行，这样可以让训练假人正常显示伤害
                entity.getServer().scheduleInTicks(1, () => {
                    simpleAttackEntity(true, player, entity, 'kubejs_fire_damage', a)
                })
            }
        })
        // 定义粒子发射的数量
        let particleCount = 49;
        for (let i = 0; i < particleCount; i++) {
            // 随机生成在玩家周围三格范围内的偏移量
            let offsetX = Math.floor(Math.random() * 7) - 3; // -3 到 3 的随机整数
            let offsetY = Math.floor(Math.random() * 7) - 3;
            let offsetZ = Math.floor(Math.random() * 7) - 3;

            // 计算粒子生成的位置
            let spawnX = player.x + offsetX;
            let spawnY = player.y + offsetY;
            let spawnZ = player.z + offsetZ;

            // 生成粒子
            player.level.spawnParticles("minecraft:lava", false, spawnX, spawnY, spawnZ, 0, 1, 0, 3, 0)
        }
    },
    //回响碎片
    'echo_shard': function (event, player, effectLevel, item, effectname, efficiency) {
        let level = player.getXpLevel()
        player.giveExperiencePoints(-level)
        event.amount = event.amount + level / 2
    },
    //回响之心
    'sculk_heart': function (event, player, effectLevel, item, effectname, efficiency) {
        let level = player.getXpLevel()
        player.giveExperiencePoints(-level / 2)
        event.amount = event.amount + level / 2
    },
    //岩浆膏
    'magma_cream': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        let maxHealth = entity.maxHealth
        if (player.isOnFire()) {
            simpleAttackEntity(true, null, entity, 'common', maxHealth / 100);
        }
    },
    //下界合金
    'netherite_ingot': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        let damage_count = entity.persistentData.getInt('damage_count') ?? 0

        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + damage_count * 0.1)
        reduce_durability(item, damage_count)
        if (damage_count >= 5) return
        entity.persistentData.putInt('damage_count', damage_count + 1)
    },
    //深渊祭品
    'koboleton_bone': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.isInWaterOrRain()) {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.2)
        }
    },
    //骷髅狗头人之骨
    'koboleton_bone': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity;
        if (entity) {
            let mainitem = entity.getMainHandItem();
            if (mainitem && mainitem.id && mainitem.count && mainitem.nbt) {
                entity.block.popItem(Item.of(mainitem.id, mainitem.count, mainitem.nbt));
                entity.setMainHandItem('minecraft:air');
            }
        }
    },
    //凋零合金锭
    'witherite_ingot': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        let health = entity.health
        let maxHealth = entity.maxHealth

        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + (0.8 - 0.8 * (maxHealth - health) / maxHealth))
    },
    //灵魂冲击
    'soul_shock': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        let health = entity.health
        let maxHealth = entity.maxHealth

        let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
        player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + effectLevel / 100 * (maxHealth - health) / maxHealth)
    },
    //海洋宝石
    'ocean_gemstone': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.isInWaterOrRain()) {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.8)
        }
    },
    //锈蚀步甲颚
    'rust_beetle_mandible': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        entity.potionEffects.add('jerotes:corrosive', 20 * 30, 9)
    },
    // 撕裂
    'tear': function (event, player, effectLevel, item, effectname, efficiency) {

        if (player.getCooldowns().isOnCooldown(item)) return

        // 伤害类型
        let type = event.getSource().getType().toString();
        let entity = event.entity;
        let damageValue = player.getAttributeTotalValue('minecraft:generic.attack_damage')
        let CD = 1 / player.getAttributeTotalValue('minecraft:generic.attack_speed')

        event.amount = event.amount * (1 - efficiency / 100)
        // 如果不是近战伤害类型返回
        if (type !== 'player') return;
        let gear_shift_level = get_gear_shift(player)
        // 延迟一刻进行
        for (let i = 0; i < effectLevel * (1 + gear_shift_level / 100); i++) {
            entity.getServer().scheduleInTicks(i, () => {
                simpleAttackEntity(true, player, entity, 'common', damageValue)
            })
        }
        player.addItemCooldown(item, 20 * CD)
    },
    //原生孔腔
    'primal_orifice': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 2) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity
        let itemNbt = item.nbt
        if (entity.hasEffect('biomancy:armor_shred')) {
            // 获取已有的效果
            let effect = entity.getEffect('biomancy:armor_shred')
            // 获取效果等级
            let amplifier = effect.getAmplifier()
            // 获取效果时长
            let duration = effect.getDuration()
            if (amplifier < 3) {
                entity.potionEffects.add('biomancy:armor_shred', 20 * 30, amplifier)
            }
        }
        // 否则执行以下逻辑
        else {
            // 增加效果
            entity.potionEffects.add('biomancy:armor_shred', 20 * 30, 0)
        }
    },
    //原生血肉块
    'primal_flesh': function (event, player, effectLevel, item, effectname, efficiency) {
        //恢复饱和度
        player.setSaturation(Math.min(player.getSaturation() + 1, 20))
    },
    //恶性血肉块
    'malignant_flesh': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 1) return
        player.persistentData.putInt(effectname, player.age)

        //减少饥饿值
        player.setFoodLevel(Math.max(player.getFoodLevel() - 1, 0))
        //恢复饱和度
        player.setSaturation(Math.min(player.getSaturation() + 1, 20))
        //没有饥饿值给玩家造成伤害
        if (player.getFoodLevel() == 0) {
            player.attack(4)
        }
    },
    //恶性脉络
    'malignant_flesh_veins': function (event, player, effectLevel, item, effectname, efficiency) {
        //获取nbt
        let itemNbt = item.nbt
        //获取营养值
        let count = player.persistentData.getInt(YingYangCount)
        //是否为长弓
        if ((itemNbt.contains('bow/long_stave_material'))) {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.2)
            //减少营养值
            updateYingYangCount(player, count - 5)
            //没有饥饿值给玩家造成伤害
            if (count <= 0) {
                player.attack(4)
            }
        }
    },
    // 混沌种子镶嵌效果
    'seedof_chaos': function (event, player, effectLevel, item, effectname, efficiency) {
        event.amount = event.amount * (0.8 + Math.random() * 0.8)
    },
    //裂纹头骨
    'shattered_skull': function (event, player, effectLevel, item, effectname, efficiency) {
        player.potionEffects.add('minecraft:strength', 20 * 10, 0)
    },
    //梦魇寻踪兽
    'nightmare_stalker_skull': function (event, player, effectLevel, item, effectname, efficiencyr) {
        if (player.hasEffect('minecraft:invisibility')) {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.3)
        }
    },
    //恶魔灯笼
    'fel_lamp': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.isPassenger()) {
            let mainhand_increased_damage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') ?? 0
            player.persistentData.putDouble('mainhand_increased_damage_multiplication', mainhand_increased_damage + 0.3)
        }
    },
    //恶魔灯笼
    'lord_pumpkinheads_lamp': function (event, player, effectLevel, item, effectname, efficiency) {
        let entity = event.entity
        if (entity.hasEffect('born_in_chaos_v1:soul_stratification')) return
        entity.potionEffects.add('born_in_chaos_v1:soul_stratification', 20 * 10, 0)
    },
    // 转变之花镶嵌效果
    'transformative_flower': function (event, player, effectLevel, item, effectname, efficiency) {
        event.amount = event.amount * (0.2 + Math.random() * 2.2)
    },
    //骇狼首领之牙攻击效果
    'fangofthe_hound_leader': function (event, player, effectLevel, item, effectname, efficiency) {
        let itemNbt = item.nbt;
        if (itemNbt.contains('double/head_left') && itemNbt.contains('double/head_right')) {
            player.potionEffects.add('born_in_chaos_v1:rampant_rampage', 20 * 3, 4)
        }
    },
    //蜘蛛鄂剑刃效果
    'spider_mandible': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 10) return
        player.persistentData.putInt(effectname, player.age)

        let entity = event.entity
        entity.potionEffects.active.forEach(ctx => {
            let name = ctx.getEffect().getDescriptionId()
            if (ctx.getEffect().getCategory() != 'HARMFUL') return
            if (effect_blacklist.includes(name)) return
            entity.potionEffects.add(ctx.effect, Math.min(ctx.getDuration() + 20 * 10, 20 * 120), ctx.getAmplifier())
        })
    },
    'default': function (event, player, effectLevel, item, effectname, efficiency) {
        return
    }
}