// priority: 9

//参考脆骨症夜鸢大佬的代码
//不清楚优化会不会更好，但是写起来方便一点
NetworkEvents.dataReceived('mainhand_effect', event => {
    let player = event.player;
    if (!player) return;
    let item = player.getMainHandItem();
    if (!item.item instanceof $ModularItem) return;

    let effects = getAllEffects(item);
    effects.forEach(effect => {
        let strategy = tetraPlayerkeybindStrategies[effect.name] || tetraPlayerkeybindStrategies.default;
        strategy(event, player, effect.level, item, effect.name, effect.efficiency);
    });


});
const tetraPlayerkeybindStrategies = {
    //缩壳
    'basalt_snail_shell': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 60) return
        player.persistentData.putInt(effectname, player.age)


        player.potionEffects.add('minecraft:resistance', 20 * 8, 2)
        player.potionEffects.add('minecraft:slowness', 20 * 8, 4)
    },
    'echo_form': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        // 持续30S，冷却==持续
        let duration = 20 * 30  // 持续时间
        if (CD < duration * 2) {
            if (CD > duration) {
                player.tell("回声形态在：" + ((duration * 2 - CD) / 20 | 0) + "秒后可用")
                return
            }
            return
        }
        player.persistentData.putInt(effectname, player.age)
        player.getServer().scheduleInTicks(duration * 2, () => {
            player.tell("回声形态充能完毕")
        });
        /// 切换形态
        // 配置参数
        let frameInterval = 2; // 每帧的间隔时间
        let baseModels = [
            "form_1",
            "form_2",
            "form_2",
            "form_3",
            "form_4",
            "form_5",
            "form_6",
            "form_6",
            "form_6"
        ];

        // 生成倒序序列（去除重复的首尾元素）
        let reversedModels = []

        // 从原数组最后一个元素开始遍历，依次添加到新数组
        for (let i = baseModels.length - 1; i >= 0; i--) {
            reversedModels.push(baseModels[i]);
        }
        // // // 清除现有模型
        // // ShowModelHelper.clearShowModel(item);
        // // ShowModelHelper.addShowModel(event.item, "form_1", "item");

        // 正序播放
        baseModels.forEach((model, index) => {
            let tickTime = index * frameInterval;
            player.getServer().scheduleInTicks(tickTime, () => {
                if (index > 0) {
                    ShowModelHelper.removeShowModel(item, baseModels[index - 1]);
                }
                ShowModelHelper.addShowModel(item, model, "item");
            });
        });

        // 计算正序播放的总时间（用来给倒序开始的时间计算）
        let totalForwardTime = (baseModels.length - 1) * frameInterval;

        // 倒序播放，也就是变回去
        reversedModels.forEach((model, index) => {
            // 倒序开始时间 = 正序总时间 + 延迟 + 倒序当前帧的时间(帧间隔)
            let tickTime = totalForwardTime + duration + (index * frameInterval);
            player.getServer().scheduleInTicks(tickTime, () => {
                // 移除前一个模型，再添加回去
                if (index > 0) {
                    ShowModelHelper.removeShowModel(item, reversedModels[index - 1]);
                } else {
                    // 移除正序的最后一个模型(只在倒序开始时)
                    ShowModelHelper.removeShowModel(item, baseModels[baseModels.length - 1]);
                }
                ShowModelHelper.addShowModel(item, model, "item");
            });
        });
    },

    'soul_form': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        let duration = 20 * 60 * 3
        let fire_damage = player.getAttributeTotalValue('kubejs:fire_damage')
        let health = player.health
        let maxHealth = player.maxHealth
        // 持续3分钟，冷却5分钟，等效冷却2分钟
        if (CD < duration * 5 / 3) {
            if (CD > duration) {
                player.tell("魂焰形态尚在冷却：" + ((duration * 5 / 3 - CD) / 20 | 0) + "秒")
            }
            return
        }
        player.persistentData.putInt(effectname, player.age)
        player.getServer().scheduleInTicks(duration * 5 / 3, () => {
            player.tell("魂焰形态充能完毕")
        });

        /// 切换形态

        ShowModelHelper.clearShowModel(item)
        ShowModelHelper.addShowModel(item, "form_2", "item")
        // player.tell("变蓝")

        player.getServer().scheduleInTicks(duration, () => {
            // player.tell("变回去")
            ShowModelHelper.removeShowModel(item, "form_2")
            ShowModelHelper.addShowModel(item, "form_1", "item")
        })

        /// 切换形态小aoe
        let entityList = getLivingWithinRadius(player.getLevel(), player.position(), 6)
        // 遍历实体列表
        entityList.forEach(entity => {
            if (entity.isLiving() && entity != player) {
                // 延迟一刻执行，这样可以让训练假人正常显示伤害
                entity.getServer().scheduleInTicks(1, () => {
                    simpleAttackEntity(true, player, entity, 'kubejs_fire_damage', fire_damage * 3)
                })
            }
        })

        let currentDamagePercent = 0.01 // 初始伤害百分比为1%
        let tickInterval = 20 * 3 // 每隔 3 秒执行一次伤害
        for (let tick = 0; tick <= duration; tick += tickInterval) {
            player.getServer().scheduleInTicks(tick, () => {

                let mainHandItem = player.getMainHandItem();

                // 如果没有手持特定物品，则不烧血
                if (!ShowModelHelper.getShowModels(mainHandItem).contains("form_2") && !hasItemEffect(mainHandItem, 'soul_form')) {
                    // player.tell('1');
                    return; // 
                }

                health = player.getHealth();
                if (health > 2) { // 小于1心的时候不触发受伤效果，省点计算
                    let damageAmount = maxHealth * Math.min(currentDamagePercent, 0.2)
                    player.setHealth(Math.max(health - damageAmount, 2));
                    player.attack(1); // 触发受伤效果

                    // 显示信息
                    // player.tell(`第${Math.floor(tick / tickInterval) + 1}次伤害`);
                    // player.tell(`伤害百分比: ${(currentDamagePercent * 100).toFixed(1)}%`);
                    // player.tell(`扣除血量: ${damageAmount.toFixed(1)}`);

                    // 执行一次增加1%，上限20%
                    currentDamagePercent += 0.01
                    // player.tell("本次伤害百分比:" + (Math.min(currentDamagePercent, 0.2)));
                }
            });
        }

        /// 特效
        // 定义粒子发射的数量
        let particleCount = 20
        let delay = 3
        // player.tell("粒子数量 " + particleCount)
        for (let i = 0; i < particleCount; i++) {
            // 随机生成在玩家周围R格范围内的偏移量
            let R = 4
            let offsetX = Math.floor(Math.random() * R * 2 + 1) - R;
            let offsetY = Math.floor(Math.random() * R * 2 + 1) - R;
            let offsetZ = Math.floor(Math.random() * R * 2 + 1) - R;

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

            // 形态切换粒子
            player.level.spawnParticles("cataclysm:ignis_soul_explode", false, spawnX, spawnY, spawnZ, 0, 1, 0, 3, 0)
            // 形态结束粒子
            player.getServer().scheduleInTicks(duration - delay, () => {
                let spawnX = player.x + offsetX;
                let spawnY = player.y + offsetY;
                let spawnZ = player.z + offsetZ;
                player.level.spawnParticles("cataclysm:ignis_explode", false, spawnX, spawnY, spawnZ, 0, 1, 0, 1, 0)
            })
        }
        // 切形态音效
        player.server.runCommandSilent(`execute positioned ${player.x} ${player.y} ${player.z} run playsound cataclysm:flame_burst player @a ~ ~ ~ 0.7 1 0`)
        player.server.runCommandSilent(`execute positioned ${player.x} ${player.y} ${player.z} run playsound minecraft:entity.generic.explode player @a ~ ~ ~ 0.5 1.2 0`)

        // 形态结束音效
        player.getServer().scheduleInTicks(duration - delay, () => {
            player.server.runCommandSilent(`execute positioned ${player.x} ${player.y} ${player.z} run playsound cataclysm:flame_burst player @a ~ ~ ~ 0.2 1 0`)
        })
    },

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

        let Level = simpleGetTetraEffectLevel(item, 'villager_metal_block')
        let uuid = player.getUuid()

        let ironGolem = player.level.createEntity('minecraft:iron_golem')

        ironGolem.setPosition(player.x + 2, player.y, player.z)
        ironGolem.spawn()

        ironGolem.persistentData.putString('owner', uuid)
        ironGolem.persistentData.putInt('player_created', 1)

        ironGolem.maxHealth = 100 + Level * 20
        ironGolem.health = ironGolem.maxHealth

        ironGolem.getServer().scheduleInTicks(20 * 30, () => {
            if (ironGolem.isAlive()) {
                player.level.spawnParticles('minecraft:happy_villager', true,
                    ironGolem.x, ironGolem.y + 1, ironGolem.z, 0.5, 1.0, 0.5, 0.1, 20)
                ironGolem.discard()
            }
        })
    },
    //火焰吐息
    'fire_breath': 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 level = player.level
        let viewVector = player.getViewVector(1.0);
        let normalizedVector = normalizeVector(viewVector)
        let spawn_entity = player.level.createEntity("legendary_monsters:fire_breath");
        spawn_entity.setPosition(player.x, player.y + 1, player.z);
        spawn_entity.setMotion(normalizedVector.x * 4, normalizedVector.y * 4, normalizedVector.z * 4);
        spawn_entity.setRotation(player.yaw, player.pitch)
        spawn_entity.spawn();

        //造成伤害
        fire_breath(level, player, spawn_entity.getUuid())
        function fire_breath(level, player, uuid) {
            let spawn_entity = level.getEntity(uuid)
            if (!spawn_entity) return
            player.server.scheduleInTicks(1, () => {
                spawn_entity.teleportTo(level.dimension, player.x, player.y + 1.5, player.z, player.yaw, player.pitch)
                fire_breath(level, player, spawn_entity.uuid)
                let entity = player.rayTrace(player.getAttributeTotalValue('forge:block_reach')).entity
                if (entity && entity.isLiving() && !entity.isPlayer()) {
                    let entityList = getLivingWithinRadius(entity.level, entity.pos, 1)
                    entityList.forEach(entity1 => {
                        let a = player.getAttributeTotalValue('kubejs:fire_damage') * effectLevel / 100
                        simpleAttackEntity(false, null, entity1, 'kubejs_fire_damage', a)
                    })
                }
            })
        }
    },
    //蔚蓝海洋之心
    'blue_heart_of_the_sea': function (event, player, effectLevel, item, effectname, efficiency) {
        event.server.runCommandSilent("/weather thunder")
    },
    //武弁头
    'aptrgangr_head': 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)
        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, normalizedVector.y * 4, normalizedVector.z * 4);
        spawn_entity.setRotation(player.yaw, player.pitch)
        spawn_entity.setOwner(player);
        spawn_entity.persistentData.putInt('attack_addition', damageValue * 1.2)
        spawn_entity.spawn();
    },
    //末影之眼
    'ender_eye': function (event, player, effectLevel, item, effectname, efficiency) {
        let deathLocation = player.lastDeathLocation
        if (deathLocation.isPresent()) {
            let deathPos = deathLocation.get().pos()
            player.teleportTo(deathLocation.get().dimension(), deathPos.x, deathPos.y, deathPos.z, event.player.yaw, event.player.pitch)
        }
    },
    //幻境石水晶
    'myalite_crystal': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 30) return
        player.persistentData.putInt(effectname, player.age)

        getLivingWithinRadius(player.getLevel(), new Vec3d(player.x, player.y, player.z), 8).forEach(entity => {
            //排除玩家
            if (!entity.isPlayer()) {
                entity.potionEffects.add('kubejs:ru_meng', 20 * 3, 0)
            }
        })
    },
    //末影合金
    'enderite_block': 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);
        //开始拉屎！
        getLivingWithinRadius(player.getLevel(), new Vec3d(player.x, player.y, player.z), 16).forEach(entity => {
            //排除玩家
            if (!entity.isPlayer()) {
                //牵引过来
                entity.move('self', (new Vec3d(player.x - entity.x, player.y - entity.y, player.z - entity.z)).scale(1))
                entity.getServer().scheduleInTicks(5, () => {
                    //根据玩家朝向肘飞
                    entity.move('self', (new Vec3d(normalizedVector.x, 8, normalizedVector.z)).scale(1))
                    //差不多摔下来时造成伤害
                    entity.getServer().scheduleInTicks(15, () => {
                        simpleAttackEntity(true, player, entity, 'common', damageValue * 2)
                    })
                })
            }
        })
    },
    //连锁
    'chain_destruction': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.persistentData.getBoolean('chain_destruction_switch')) {
            player.persistentData.putBoolean('chain_destruction_switch', false)
            player.tell('连锁已开启')
            player.tell('小心你的房子')
        } else {
            player.persistentData.putBoolean('chain_destruction_switch', true)
            player.tell('连锁已关闭')
        }
    },
    //龙首
    'dragon_head': 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 level = player.level
        let viewVector = player.getViewVector(1.0);
        let normalizedVector = normalizeVector(viewVector)
        let spawn_entity = level.createEntity("minecraft:dragon_fireball")
        spawn_entity.setPosition(player.x, player.y + 1, player.z);
        spawn_entity.setMotion(normalizedVector.x * 2, normalizedVector.y * 2, normalizedVector.z * 2);
        spawn_entity.setOwner(player);
        spawn_entity.spawn();
        spawn_entity.getServer().scheduleInTicks(20 * 3, () => {
            if (spawn_entity) {
                spawn_entity.kill()
            }
        })
    },
    //霜冻符文
    'frozen_rune': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 60) return
        player.persistentData.putInt(effectname, player.age)

        // 获取周围实体
        let entityList = getLivingWithinRadius(player.getLevel(), player.position(), 5)
        // 遍历实体列表
        entityList.forEach(entity => {
            if (entity.isLiving() && entity != player) {
                entity.modifyAttribute('minecraft:generic.max_health', 'shi_wen', -0.2, 'multiply_total')
                entity.potionEffects.add('legendary_monsters:freeze', 20 * 5, 0)
            }
        })
    },
    //时之沙
    'time_hourglass': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 60) return
        player.persistentData.putInt(effectname, player.age)

        let health = player.health
        if (item.nbt.ni_zhuan) {
            let ni_zhuan = item.nbt.ni_zhuan
            player.setHealth(ni_zhuan)
            item.nbt.remove('ni_zhuan')
            player.sendData('time_hourglass')
        } else {
            item.nbt.putInt('ni_zhuan', health)
        }
    },
    //滕炎锭
    'ignitium_ingot': function (event, player, effectLevel, item, effectname, efficiency) {
        let time = player.persistentData.getInt(effectname) ?? 0
        let CD = Math.abs(player.age - time)
        if (CD < 20 * 60) return
        player.persistentData.putInt(effectname, player.age)

        let damage = player.getAttributeTotalValue('kubejs:fire_damage') * effectLevel / 100

        let level = player.level
        let entity_1 = level.createEntity("cataclysm:flame_strike")
        entity_1.persistentData.putInt('null_attack_addition', damage)
        entity_1.setPosition(player.x, player.y, player.z)
        entity_1.mergeNbt({ Radius: 9 })
        entity_1.spawn()
    },
    //玄武蜗牛壳
    'snailshell': 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.potionEffects.add('minecraft:resistance', 20 * 8, 2)
        player.potionEffects.add('minecraft:slowness', 20 * 8, 4)
    },
    //村民金属锭
    'villager_metal_ingot': function (event, player, effectLevel, item, effectname, efficiency) {
        player.potionEffects.add('minecraft:hero_of_the_village', 20 * 60, 0)
    },
    //暴怒符咒
    'charmof_fury': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.hasEffect('born_in_chaos_v1:medium_rampage')) return
        player.potionEffects.add('born_in_chaos_v1:medium_rampage', 20 * 60 * 5, 1)
        reduce_durability(item, 50)
    },
    //耐力符文
    'charmof_endurance': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.hasEffect('minecraft:speed')) return
        player.potionEffects.add('minecraft:speed', 20 * 60 * 5, 4)
        reduce_durability(item, 50)
    },
    //隐身符咒
    'charmof_stealth': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.hasEffect('minecraft:invisibility')) return
        player.potionEffects.add('minecraft:invisibility', 20 * 60 * 5, 2)
        reduce_durability(item, 50)
    },
    //力量符咒
    'charmof_power': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.hasEffect('minecraft:strength')) return
        player.potionEffects.add('minecraft:strength', 20 * 60 * 5, 2)
        reduce_durability(item, 50)
    },
    //抗性符咒
    'charmof_resistance': function (event, player, effectLevel, item, effectname, efficiency) {
        if (player.hasEffect('minecraft:resistance')) return
        player.potionEffects.add('minecraft:resistance', 20 * 60 * 5, 1)
        reduce_durability(item, 50)
    },
    'default': function (event, player, effectLevel, item, effectname, efficiency) {
        return
    }
}