import { world, system } from "@minecraft/server";

import { dimensions } from "./the_snatching.js";

// 这些动态数据不识别为喷射目标
const notSpitTarget = [
    "pm_mock:hover_rotation",
    "pm_mock:hover_location",
    "pm_mock:spit_bullet_count",
    "pm_mock:rider_holding_item",
    "pm_mock:stasis_effect_ticks",
]

// 检查实体是否是玩家并且是否穿戴了鞘翅
function isPlayerWithElytra(entity) {
    try {
        if (entity.typeId === 'minecraft:player') {
            const playerEquipmentComponent = entity.getComponent('minecraft:equippable');
            const playerChestEquipment = playerEquipmentComponent.getEquipment('Chest');
            return playerChestEquipment && playerChestEquipment.typeId === 'minecraft:elytra';
        }
        return false;
    } catch (error) {
        // console.error("An error occurred in isPlayerWithElytra:", error);
        return false;
    }
}

// 向上击退函数
function knockbackUp(entity) {
    const view = entity.getViewDirection();
    entity.applyKnockback(view.x, view.z, 0.0, 0.5); // 向上击退
    // console.warn(`Knocked back up!`);
}

// 向下击退函数
function knockbackDown(entity) {
    const view = entity.getViewDirection();
    entity.applyKnockback(view.x, view.z, 0.0, -0.5); // 向下击退
    // console.warn(`Knocked back down!`);
}

// 召唤单个闪电
function spawnLightningAtLocation(location, dimension) {
    try {
        // 在指定坐标位置生成粒子效果
        dimension.spawnParticle('pm_mock:stormspitter_inhalation_10', location);
        dimension.spawnParticle('pm_mock:stormspitter_inhalation_8', location);

        // 延时3秒后生成闪电
        system.runTimeout(() => {
            try {
                const lightningLocation = { x: location.x, y: location.y + 1, z: location.z };
                dimension.spawnEntity("minecraft:lightning_bolt", lightningLocation);
                dimension.spawnParticle('pm_mock:stormspitter_inhalation_5', location);
            } catch (error) {
                // console.error("An error occurred while spawning lightning:", error);
            }
        }, 3 * 20); // 3秒，20时间单位为1秒
    } catch (error) {
        // console.error("An error occurred while spawning particle:", error);
    }
}

// 取坐标召唤闪电
function spawnLightningAroundLocation(location, dimension) {
    try {
        const centerX = location.x;
        const centerZ = location.z;

        for (let i = 0; i < 1; i++) {
            const randomX = centerX + (Math.random() * 30 - 15);
            const randomZ = centerZ + (Math.random() * 30 - 15);

            for (let y = location.y; y > -64; y--) {
                const blockLocation = { x: randomX, y: y, z: randomZ };
                const block = dimension.getBlock(blockLocation);

                if (block && !block.isAir) {
                    const lightningLocation = { x: randomX, y: y + 1, z: randomZ };
                    spawnLightningAtLocation(lightningLocation, dimension);
                    break;
                }
            }
        }
    } catch (error) {
        // console.error("An error occurred while spawning lightning around location:", error);
    }
}


// 吸引实体函数
function attractEntityBySight(entity) {
    try {
        // 获取实体tamed
        const tamedState = entity.getProperty('pm_mock:tame_state');
        // 获取视野中的怪物
        const monstersInView = entity.getEntitiesFromViewDirection({ maxDistance: 64, families: ['monster'] });
        // 获取视野中的玩家
        const playersInView = entity.getEntitiesFromViewDirection({ maxDistance: 64, families: ['player'] });

        // 合并两个列表
        const entitiesInView = [...monstersInView, ...playersInView];

        if (entitiesInView.length === 0) {
            // console.warn("No entities found in view.");

            entity.triggerEvent("skill_reset");

            return;
        }

        // 按照距离排序，选择最近的实体
        entitiesInView.sort((a, b) => a.distance - b.distance);
        const targetEntity = entitiesInView[0].entity;
        let attractCountdown = 100; // 5秒，每5时间单位一次，共100个时间单位

        const attractAction = system.runInterval(() => {
            try {
                // 目标丢失
                if (!entity.isValid() || !targetEntity.isValid()) {
                    // console.warn("Entity or target entity is no longer valid. Stopping attraction.");
                    system.clearRun(attractAction);
                    entity.triggerEvent("skill_reset");
                    return;
                }

                const entityLocation = entity.location;
                const targetLocation = targetEntity.location;

                const horizontalDistance = Math.sqrt(
                    Math.pow(entityLocation.x - targetLocation.x, 2) +
                    Math.pow(entityLocation.z - targetLocation.z, 2)
                );

                const verticalDistance = Math.abs(entityLocation.y - targetLocation.y);

                // 成功吸取
                if (horizontalDistance < 2) {
                    targetEntity.teleport(targetEntity.location);
                    // targetEntity.clearVelocity();
                    if (tamedState == 0) {
                        // console.warn("Target entity is close enough. Stopping attraction.");
                        system.clearRun(attractAction);
                        entity.triggerEvent("skill_2");
                        return;
                    } else {
                        // console.warn(`Eat target entity: ${targetEntity.typeId}`);
                        system.clearRun(attractAction);

                        const propertyList = entity.getDynamicPropertyIds();

                        // 剔除不可作为喷射目标的数据
                        const validProperties = propertyList.filter(prop => !notSpitTarget.includes(prop));

                        // 计算剩余动态数据的值总和
                        let totalBullets = 0;
                        validProperties.forEach(prop => {
                            const value = entity.getDynamicProperty(prop);
                            if (typeof value === 'number') {
                                totalBullets += value;
                            }
                        });

                        // console.warn(`Total bullets: ${totalBullets}`);

                        // 如果子弹数量没到10，就将刚刚吃掉的实体id作为实体属性id，数值加一
                        if (totalBullets < 10) {
                            const targetEntityId = targetEntity.typeId;
                            const existingCount = entity.getDynamicProperty(targetEntityId) || 0;
                            entity.setDynamicProperty(targetEntityId, existingCount + 1);
                            // console.warn(`Updated ${targetEntityId} count to: ${existingCount + 1}`);

                            // 总子弹数同步到pm_mock:cannon_count
                            entity.setProperty('pm_mock:cannon_count', totalBullets + 1);
                        }

                        targetEntity.remove();
                        entity.dimension.playSound('random.burp', entity.location);
                        entity.triggerEvent("skill_reset");
                        return;
                    }
                }

                // 时间超限
                if (attractCountdown <= 0) {
                    // console.warn("Attraction time exceeded. Stopping attraction.");
                    system.clearRun(attractAction);
                    entity.triggerEvent("skill_reset");
                    return;
                }

                // 计算从目标实体到自己实体的方向向量
                const directionX = entityLocation.x - targetLocation.x;
                const directionZ = entityLocation.z - targetLocation.z;
                const directionY = entityLocation.y - targetLocation.y;

                // 归一化方向向量
                const magnitude = Math.sqrt(directionX * directionX + directionY * directionY + directionZ * directionZ);
                const normalizedX = directionX / magnitude;
                const normalizedY = directionY / magnitude;
                const normalizedZ = directionZ / magnitude;

                const horizontalKnockback = (horizontalDistance / 10) * 0.5 + 0.6;
                const verticalKnockback = (verticalDistance / 10) * 0.6 + 0.2;

                // 应用击退效果
                targetEntity.applyKnockback(normalizedX, normalizedZ, horizontalKnockback, verticalKnockback);

                attractCountdown -= 5;
            } catch (error) {
                // console.error("An error occurred in attractEntityBySight interval:", error);
                system.clearRun(attractAction);
                if (entity.isValid()) {
                    entity.triggerEvent("skill_reset");
                };
            }
        }, 5);
    } catch (error) {
        // console.error("An error occurred in attractEntityBySight:", error);
    }
}


// 发射目标实体函数
function shootEntityBySight(entity) {
    try {
        // 获取视野中的怪物
        const monstersInView = entity.getEntitiesFromViewDirection({ maxDistance: 64, families: ['monster'] });
        // 获取视野中的玩家
        const playersInView = entity.getEntitiesFromViewDirection({ maxDistance: 64, families: ['player'] });

        // 合并两个列表
        const entitiesInView = [...monstersInView, ...playersInView];

        if (entitiesInView.length === 0) {
            // console.warn("No entities found in view.");
            return;
        }

        // 按照距离排序，选择最近的实体
        entitiesInView.sort((a, b) => a.distance - b.distance);
        const targetEntity = entitiesInView[0].entity;

        if (!entity.isValid() || !targetEntity.isValid()) {
            // console.warn("Entity or target entity is no longer valid. Stopping spit.");
            return;
        }

        //修正实体位置
        const targetLocation = {
            x: targetEntity.location.x,
            y: entity.location.y,
            z: targetEntity.location.z  
        };

        targetEntity.teleport(targetLocation);
        // targetEntity.clearVelocity();

        const entityLocation = entity.location;
        // const targetLocation = targetEntity.location;

        // 计算从目标实体到自己实体的方向向量
        const directionX = entityLocation.x - targetLocation.x;
        const directionZ = entityLocation.z - targetLocation.z;

        // 归一化方向向量
        const magnitude = Math.sqrt(directionX * directionX + directionZ * directionZ);
        const normalizedX = directionX / magnitude;
        const normalizedZ = directionZ / magnitude;

        system.runTimeout(() => {
            if (targetEntity.isValid()) {
                // 应用击退效果
                targetEntity.applyKnockback(normalizedX, normalizedZ, 7, 1);

                // 根据是否雷雨天增加效果
                if (entity.getProperty('pm_mock:storm_state') == 0) {
                    if (!isPlayerWithElytra(targetEntity)) {
                        targetEntity.addEffect('slow_falling', 160);
                    }
                } else {
                    chargeEntityUntilHit(targetEntity);
                }
            }
        }, 5);

        // console.warn(`Spit target entity: ${targetEntity.typeId}`);
    } catch (error) {
        // console.error("An error occurred in shootEntityBySight:", error);
    }
}

// 驯服后发射玩家
function shootPlayerAfterTamed(entity) {

    const nearbyEntities = entity.dimension.getEntities({
        type: 'minecraft:player',
        location: entity.location,
        maxDistance: 16,
        closest: 1,
    });

    if (nearbyEntities.length === 0) {
        // console.warn("No players found.");
        return;
    }

    const targetPlayer = nearbyEntities[0];

    if (!entity.isValid() || !targetPlayer.isValid()) {
        // console.warn("Entity or target player is no longer valid.");
        return;
    }

    const entityLocation = entity.location;
    const viewDirection = entity.getViewDirection();

    // 计算玩家传送的位置（实体前方2格）
    const teleportLocation = {
        x: entityLocation.x + viewDirection.x * 2,
        y: entityLocation.y + 1,
        z: entityLocation.z + viewDirection.z * 2
    };

    // 传送玩家到新位置
    targetPlayer.teleport(teleportLocation);

    // 给玩家赋予缓降效果
    if (!isPlayerWithElytra(targetPlayer)) {
        targetPlayer.addEffect('slow_falling', 160);
    };

    // 计算击退方向向量
    const directionX = viewDirection.x;
    const directionZ = viewDirection.z;

    // 音效
    entity.runCommand('playsound mock.stormspitter.launch @a ~~~');

    system.runTimeout(() => {
        if (targetPlayer.isValid()) {
            // 应用击退效果
            targetPlayer.applyKnockback(directionX, directionZ, 9, 1);
        }
        
    }, 5);
}


// 充能的实体落在地上爆炸
function chargedEntityHit(entity) {
    //在实体位置y+1召唤一个闪电
    const dimension = entity.dimension;
    const location = { x: entity.location.x, y: entity.location.y + 1, z: entity.location.z };
    dimension.spawnEntity("minecraft:lightning_bolt", location);
    dimension.createExplosion(location, 3);
    dimension.spawnParticle('pm_mock:stormspitter_inhalation_5', location);
    dimension.spawnParticle('pm_mock:stormspitter_inhalation_6', location);
    dimension.playSound('mock.stormspitter.hit', location);

}

// 悬停出界调整
function hoverOutOfBoundsAdjustment(entity) {
    // 检查是不是正在悬停而且出界
    if (entity.getProperty('pm_mock:hover_state') === 1) {
        const hoverLocation = entity.getDynamicProperty('pm_mock:hover_location');
        const hoverRotation = entity.getDynamicProperty('pm_mock:hover_rotation');

        if (hoverLocation) {
            const entityLocation = entity.location;

            // 计算实体当前位置与悬停位置的距离
            const distanceX = Math.abs(entityLocation.x - hoverLocation.x);
            const distanceY = Math.abs(entityLocation.y - hoverLocation.y);
            const distanceZ = Math.abs(entityLocation.z - hoverLocation.z);

            // console.warn(`当前位置：(${entityLocation.x.toFixed(1)}, ${entityLocation.y.toFixed(1)}, ${entityLocation.z.toFixed(1)}), 距离悬停位置：(${distanceX.toFixed(1)}, ${distanceY.toFixed(1)}, ${distanceZ.toFixed(1)})`);

            // 如果任意一轴的距离超过X格，则认为出界
            if (distanceX > 3 || distanceY > 3 || distanceZ > 3) {
                // console.warn("Entity is out of hover bounds. Knocking it back.");

                // 计算击退方向向量
                const directionX = hoverLocation.x - entityLocation.x;
                const directionZ = hoverLocation.z - entityLocation.z;
                const directionY = hoverLocation.y - entityLocation.y;

                // 归一化方向向量
                const magnitude = Math.sqrt(directionX * directionX + directionY * directionY + directionZ * directionZ);
                const normalizedX = directionX / magnitude;
                const normalizedY = directionY / magnitude;
                const normalizedZ = directionZ / magnitude;

                // 应用击退效果
                entity.applyKnockback(normalizedX, normalizedZ, 1, normalizedY > 0 ? 0.3 : -0.3);
            }
        }

        // if (hoverRotation) {
        //     const rotation = { x: hoverRotation.x, y: hoverRotation.y };
        //     console.warn(`悬停角度： ${rotation.x}, ${rotation.y}, 当前角度：${entity.getRotation().x}, ${entity.getRotation().y}`);
        //     // entity.setRotation(rotation);
        //     entity.runCommand(`tp @s ~~~ ${rotation.x} ${rotation.y}`);
        // }
    }


}

// 持续判定实体，直到落地爆炸
function chargeEntityUntilHit(entity) {
    const run = system.runInterval(() => {
        try {
            if (entity.isValid()) {
                entity.dimension.spawnParticle('pm_mock:stormspitter_inhalation_7', entity.location);
                const velocity = entity.getVelocity();
                // 如果实体三轴速度都小
                if ((Math.abs(velocity.x) < 0.1 && Math.abs(velocity.y) < 0.1 && Math.abs(velocity.z) < 0.1) || entity.isOnGround) {
                    // 爆炸
                    chargedEntityHit(entity);
                    system.clearRun(run);
                }
            } else {
                system.clearRun(run);
            }
        } catch (error) {
            // console.error('Error accessing entity location:', error);
            system.clearRun(run);
        }
    }, 2);
}

// 计算炮弹数量的函数
function calculateBullets(entity) {
    // 获取实体的动态属性列表
    const propertyList = entity.getDynamicPropertyIds();

    // 剔除不可作为喷射目标的数据
    const validProperties = propertyList.filter(prop => !notSpitTarget.includes(prop));

    // 计算剩余动态数据的值总和
    let totalBullets = 0;
    let bulletProperty = null;
    validProperties.forEach(prop => {
        const value = entity.getDynamicProperty(prop);
        if (typeof value === 'number' && value > 0) {
            totalBullets += value;
            bulletProperty = prop;
        }
    });

    // console.warn(`Total bullets: ${totalBullets}`);

    return { totalBullets, bulletProperty };
}

// 喷射炮弹
function shootEntityAfterTamed(entity) {
    // 计算炮弹数量
    const { totalBullets, bulletProperty } = calculateBullets(entity);

    // console.warn(`Total bullets: ${totalBullets}`);

    // 如果没有炮弹，发射玩家自己
    if (totalBullets <= 0) {
        // console.warn("No bullets available to spit.");
        shootPlayerAfterTamed(entity);
        return;
    }

    // 取出一发炮弹
    const currentCount = entity.getDynamicProperty(bulletProperty);
    entity.setDynamicProperty(bulletProperty, currentCount - 1);
    // console.warn(`Updated ${bulletProperty} count to: ${currentCount - 1}`);

    // 总子弹数同步到pm_mock:cannon_count
    entity.setProperty('pm_mock:cannon_count', totalBullets - 1);

    // 获取实体的位置和视角方向
    const entityLocation = entity.location;
    const viewDirection = entity.getViewDirection();

    // 计算炮弹生成的位置（实体前方2格）
    const bulletLocation = {
        x: entityLocation.x + viewDirection.x * 2,
        y: entityLocation.y + 1,
        z: entityLocation.z + viewDirection.z * 2
    };

    // 生成炮弹实体
    const dimension = entity.dimension;
    const bulletEntity = dimension.spawnEntity(bulletProperty, bulletLocation);

    // 音效
    entity.runCommand('playsound mock.stormspitter.launch @a ~~~');

    // 延迟5时间单位后，赋予炮弹落地爆炸效果并大力击退出去
    system.runTimeout(() => {
        if (bulletEntity.isValid() && entity.isValid()) {
            // 应用击退效果
            bulletEntity.applyKnockback(viewDirection.x, viewDirection.z, 8, 0.5);
            // 附加炮弹效果
            chargeEntityUntilHit(bulletEntity);

            entity.runCommand('camerashake add @a[r=10] 0.3 0.3 positional');

            // 获取骑乘该实体的玩家
            const rideComponent = entity.getComponent('minecraft:rideable');
            if (rideComponent) {
                const riderList = rideComponent.getRiders();
                if (riderList.length > 0) {
                    const player = riderList[0];
                    if (player.isValid()) {
                        // 计算剩余的炮弹数量
                        const remainingBullets = totalBullets - 1;
                        let message = ``
                        if (remainingBullets > 0) {
                            message += 'Right-click to §elaunch the stored Mobs!§r\n';
                        }
                        else {
                            message += 'Right-click to §glaunch yourself!§r\n';
                        }
                        message += `Remaining Mobs: ${remainingBullets} `
                        // 通知玩家剩余的炮弹数量
                        player.runCommand(`title @s actionbar ${message}`);
                    }
                }
            }
        }
    }, 5);
}


// 玩家控制实体飞行
function playerControlRide(player, onlyRotate = false) {
    const ridingComponent = player.getComponent('minecraft:riding');
    if (ridingComponent) {
        const rideEntity = ridingComponent.entityRidingOn;
        const playerDirection = player.getViewDirection();

        // 计算玩家的朝向角度
        const pitch = player.getRotation().x; // 垂直角度（俯仰角）
        const yaw = player.getRotation().y; // 水平角度（偏航角）

        // 计算竖直击退强度
        let verticalKnockback = 0;
        let horizontalKnockback = 0.01;
        if (onlyRotate === false) {
            horizontalKnockback = 0.4;
            if (pitch > 45) {
                verticalKnockback = -0.2;
            } else if (pitch < -30) {
                verticalKnockback = 0.2;
            }
        }


        // 应用击退效果到被骑乘的实体
        if (rideEntity.isValid()) {
            rideEntity.applyKnockback(playerDirection.x, playerDirection.z, horizontalKnockback, verticalKnockback);
        }



    }
}

// 玩家使用钓竿吸引
export function pushEntityTowardsPlayer(entity, player = null) {

    let targetPlayer = null;

    if (player === null) {
        // 搜索周围64格范围内的玩家
        const nearbyPlayers = entity.dimension.getEntities({
            type: 'minecraft:player',
            location: entity.location,
            maxDistance: 64,
        });

        // 找到手持幻翼膜钓竿的玩家
        for (const player of nearbyPlayers) {
            const playerMainhandItem = player.getComponent('minecraft:equippable').getEquipment('Mainhand');
            if (playerMainhandItem && playerMainhandItem.typeId === 'pm_mock:phantom_membrane_pole') {
                targetPlayer = player;
                break;
            }
        }
    } else {
        targetPlayer = player;
    }

    // 如果没有找到目标玩家，结束函数
    if (!targetPlayer) {
        return;
    }

    // 定义持续时间和间隔时间
    const duration = 100;
    const segmentDuration = 10;
    const interval = 2;

    // 递归函数，用于持续推动实体
    function pushTowardsPlayer(countdown) {
        // 检查实体和玩家是否仍然有效
        if (!entity.isValid() || !targetPlayer.isValid()) {
            return;
        }

        // 如果时间超限，结束函数
        if (countdown <= 0) {
            return;
        }

        // 计算实体和玩家之间的距离
        const entityLocation = entity.location;
        const targetLocation = targetPlayer.location;
        const distance = Math.sqrt(
            Math.pow(entityLocation.x - targetLocation.x, 2) +
            Math.pow(entityLocation.z - targetLocation.z, 2)
        );

        let verticalKnockback = 0;
        let horizontalKnockback = 0.3;

        if (entityLocation.y > targetLocation.y + 1.5) verticalKnockback = -0.1;
        else if (entityLocation.y < targetLocation.y) verticalKnockback = 0.1;

        // 如果距离小于5格
        if (distance < 5) {
            horizontalKnockback = 0.00;
        }

        // 计算从实体到玩家的方向向量
        const directionX = targetLocation.x - entityLocation.x;
        const directionZ = targetLocation.z - entityLocation.z;

        // 归一化方向向量
        const magnitude = Math.sqrt(directionX * directionX + directionZ * directionZ);
        const normalizedX = directionX / magnitude;
        const normalizedZ = directionZ / magnitude;

        // 每2秒更新一次方向和推动力度
        const pushInterval = system.runInterval(() => {
            if (!entity.isValid() || !targetPlayer.isValid()) {
                system.clearRun(pushInterval);
                return;
            }

            // 应用击退效果
            entity.applyKnockback(normalizedX, normalizedZ, horizontalKnockback, verticalKnockback);

            // 粒子
            targetPlayer.dimension.spawnParticle('pm_mock:stormspitter_attract_1', targetLocation);

            countdown -= 1;
            // console.warn(`countdown: ${countdown}`);
            if (countdown <= 0) {
                system.clearRun(pushInterval);
            }
        }, interval);

        // 停止当前段落的推动
        system.runTimeout(() => {
            system.clearRun(pushInterval);
            if (countdown > 0) {
                pushTowardsPlayer(countdown);
            }
        }, segmentDuration);
    }

    // 开始推动实体
    pushTowardsPlayer(duration);
}

// 子函数，推动一次
function pushEntityTowardsPlayerOnce(entity, targetPlayer = null) {
    // 计算实体和玩家之间的距离
    const entityLocation = entity.location;
    const targetLocation = targetPlayer.location;
    const distance = Math.sqrt(
        Math.pow(entityLocation.x - targetLocation.x, 2) +
        Math.pow(entityLocation.z - targetLocation.z, 2)
    );

    let verticalKnockback = 0;
    let horizontalKnockback = 0.3;

    if (entityLocation.y > targetLocation.y + 1.5) verticalKnockback = -0.1;
    else if (entityLocation.y < targetLocation.y) verticalKnockback = 0.1;

    // 如果距离小于5格
    if (distance < 5) {
        horizontalKnockback = 0.00;
    }

    // 计算从实体到玩家的方向向量
    const directionX = targetLocation.x - entityLocation.x;
    const directionZ = targetLocation.z - entityLocation.z;

    // 归一化方向向量
    const magnitude = Math.sqrt(directionX * directionX + directionZ * directionZ);
    const normalizedX = directionX / magnitude;
    const normalizedZ = directionZ / magnitude;

    // 每2秒更新一次方向和推动力度
    const pushInterval = system.runInterval(() => {
        if (!entity.isValid() || !targetPlayer.isValid()) {
            system.clearRun(pushInterval);
            return;
        }

        // 应用击退效果
        entity.applyKnockback(normalizedX, normalizedZ, horizontalKnockback, verticalKnockback);

        // 粒子
        targetPlayer.dimension.spawnParticle('pm_mock:stormspitter_attract_1', targetLocation);

        countdown -= 1;
        // console.warn(`countdown: ${countdown}`);
        if (countdown <= 0) {
            system.clearRun(pushInterval);
        }
    }, interval);
}

// 根据玩家手持物品显示title
function titleForItemChange(player, itemTypeId, entity) {
    // console.warn(`itemTypeId: ${itemTypeId}`);
    switch (itemTypeId) {
        case 'minecraft:phantom_membrane':
            const { totalBullets: bulletCount } = calculateBullets(entity);
            // console.warn(`bulletCount: ${bulletCount}`);
            if (bulletCount > 0) {
                player.runCommand(`title @s actionbar Right-click to §elaunch the stored Mobs!§r \nRemaining Mobs: ${bulletCount}`);
            }
            else {
                player.runCommand(`title @s actionbar Right-click to §6launch yourself!§r`);
            }
            break;
        case 'pm_mock:phantom_membrane_pole':
            player.runCommand(`title @s actionbar Right-click to §estart controlling its flight direction§r.`);
            break;
        default:
            break;
    }
}


// 射出一个闪电球
function shootChargedBolt(entity) {
    const entityLocation = entity.getHeadLocation();
    const direction = entity.getViewDirection();
    const shootLocation = { x: entityLocation.x + direction.x * 1.5, y: entityLocation.y + direction.y * 1.5, z: entityLocation.z + direction.z * 1.5 };
    const projectileEntity = entity.dimension.spawnEntity('pm_mock:charged_bolt_projectile', shootLocation);
    const projectileComponent = projectileEntity.getComponent('minecraft:projectile');
    const velocity = { x: direction.x * 0.6, y: direction.y * 0.6, z: direction.z * 0.6 };
    projectileComponent.owner = entity;
    projectileComponent.shoot(velocity);
    projectileEntity.setDynamicProperty('pm_mock:bolt_velocity', velocity);
    // 如果是雷雨天发射
    if (entity.getProperty('pm_mock:storm_state') === 1) {
        projectileEntity.setDynamicProperty('pm_mock:bolt_storm_state', true);
    }
}


// 闪电球击中
function chargedBoltHit(entity) {

    try {
        const stormState = entity.getDynamicProperty('pm_mock:bolt_storm_state');

        if (stormState == true) {
            // 雷雨天
            chargedEntityHit(entity);
        }
        else {
            //粒子和爆炸
            const dimension = entity.dimension;
            const location = { x: entity.location.x, y: entity.location.y + 1, z: entity.location.z };
            dimension.spawnEntity("minecraft:lightning_bolt", location);
            dimension.createExplosion(location, 1);
            dimension.spawnParticle('pm_mock:stormspitter_inhalation_5', location);
            dimension.spawnParticle('pm_mock:stormspitter_inhalation_6', location);
            dimension.playSound('mock.stormspitter.hit', location);
        }
    
    
    
    
        entity.remove();
    }
    catch (error) {
        // console.warn(`chargedBoltHit error: ${error}`);
    }


}









// 监听事件
system.afterEvents.scriptEventReceive.subscribe((event) => {
    const { id, message, sourceEntity } = event;

    // 向上击退事件
    if (id === 'pm_mock:knockback_up') {
        knockbackUp(sourceEntity);
    }

    // 向下击退事件
    else if (id === 'pm_mock:knockback_down') {
        knockbackDown(sourceEntity);
    }

    // 闪电风暴事件
    else if (id === 'pm_mock:stormspitter_lightning') {
        const entityLocation = sourceEntity.location;
        const entityDimension = sourceEntity.dimension;

        // 总共X组，每组之间间隔X时间单位
        for (let group = 0; group < 3; group++) {
            system.runTimeout(() => {
                // 每组从t=20时间单位开始，每X时间单位调用一次spawnLightningAroundLocation
                for (let t = 15; t <= 36; t += 7) {
                    system.runTimeout(() => {
                        spawnLightningAroundLocation(entityLocation, entityDimension);
                    }, t);
                }

                system.runTimeout(() => {
                    try {
                        // 找到最近的玩家并召唤一个闪电
                        const targets = entityDimension.getEntities({type: 'minecraft:player', location: entityLocation, closest: 1})
                        if (targets.length > 0) {
                            const target = targets[0];
                            const targetLocation = target.location;
                            const targetDimension = target.dimension;
                            spawnLightningAtLocation(targetLocation, targetDimension);
                        }
                    } catch (error) {}
                }, 15);
            }, group * 45);
        }
    }

    // 吸取目标事件
    else if (id === 'pm_mock:stormspitter_attract') {
        system.runTimeout( () => {
            if (sourceEntity.isValid()) {
                // const entitiesInView = sourceEntity.getEntitiesFromViewDirection({ maxDistance: 100 });

                // entitiesInView.forEach(entityInfo => {
                //     const { distance, entity } = entityInfo;
                //     // console.warn(`Entity ID: ${entity.typeId}, Distance: ${distance}`);
                // });
        
                attractEntityBySight(sourceEntity);
            }
        }, 5);
    }

    // 发射目标实体
    else if (id === 'pm_mock:stormspitter_spit') {
        shootEntityBySight(sourceEntity);
    }

    // 驯服后的发射玩家
    else if (id === 'pm_mock:stormspitter_tamed_spit_player') {
        shootPlayerAfterTamed(sourceEntity);
    }

    // 开始悬停事件
    else if (id === 'pm_mock:stormspitter_hover_start') {
        sourceEntity.setDynamicProperty('pm_mock:hover_location', sourceEntity.location);
        const rotation = sourceEntity.getRotation();
        const hoverRotation = {
            x: rotation.x,
            y: rotation.y,
            z: 0,
        };
        sourceEntity.setDynamicProperty('pm_mock:hover_rotation', hoverRotation);
        // console.warn(`ok`);
    }

    // 获得落地爆炸效果
    else if (id === 'pm_mock:storm_spit') {
        chargeEntityUntilHit(sourceEntity);
    }

    //驯服后喷射一发炮弹
    else if (id === 'pm_mock:cannon_spit_tamed') {
        shootEntityAfterTamed(sourceEntity);
    }

    //charged_air使用，调用这个立刻爆炸
    else if (id === 'pm_mock:charged_air_hit') {
        chargedEntityHit(sourceEntity);
    }

    // 玩家使用钓竿吸引
    else if (id === 'pm_mock:attract_to_player') {
        pushEntityTowardsPlayer(sourceEntity);
    }

    // 射出一个闪电球
    else if (id === 'pm_mock:stormspitter_charged_bolt') {
        shootChargedBolt(sourceEntity);
        sourceEntity.playAnimation('animation.pm_mock_stormspitter_inhalation_animation2');
    }

    // 闪电球击中
    else if (id === 'pm_mock:charged_bolt_hit') {
        chargedBoltHit(sourceEntity);
    }

});





// 全局定时器-高频
system.runInterval(() => {
    dimensions.forEach(dim => {
        const dimensionObj = world.getDimension(dim);
        if (dimensionObj) {
            const entityArray = dimensionObj.getEntities();
            for (const entity of entityArray) {

                // 检查实体，是不是被玩家骑着，玩家是不是拿着指定物品，然后引导运动
                if (entity.typeId === 'pm_mock:stormspitter') {
                    const rideComponent = entity.getComponent('minecraft:rideable');

                    //驯服
                    if (rideComponent) {
                        const riderList = rideComponent.getRiders();
                        //正在骑乘
                        if (riderList.length > 0) {
                            const player = riderList[0];
                            const playerMainhandItem = player.getComponent('minecraft:equippable').getEquipment('Mainhand');
                            //手里有物品
                            if (playerMainhandItem) {
                                const currentItemId = playerMainhandItem.typeId;
                                // console.warn(`${player.name} is holding ${currentItemId}`);

                                // 获取上一次记录的手持物品
                                const lastItemId = entity.getDynamicProperty('pm_mock:rider_holding_item');

                                // 如果手持物品发生变化，执行title
                                if (currentItemId !== lastItemId) {
                                    // console.warn(`${player.name} is holding ${currentItemId}`);
                                    titleForItemChange(player, currentItemId, entity);
                                    entity.setDynamicProperty('pm_mock:rider_holding_item', currentItemId);
                                }

                                

                                //幻翼膜钓竿，控制移动
                                if (playerMainhandItem.typeId === 'pm_mock:phantom_membrane_pole') {
                                    playerControlRide(player);
                                    
                                    //使用了物品，而且不在冷却期
                                    if (entity.isSprinting && entity.getProperty('pm_mock:ride_use_cooldown') == 0) {
                                        // console.warn(`使用幻翼膜钓竿`);

                                        // 切换悬浮状态
                                        if (entity.getProperty('pm_mock:hover_state') == 1) {
                                            entity.triggerEvent('hover_stop');
                                        }
                                        else {
                                            entity.triggerEvent('hover_start');
                                        }



                                        entity.setProperty('pm_mock:ride_use_cooldown', 1);

                                        //重置冷却
                                        system.runTimeout(() => {
                                            if (entity.isValid()) {
                                                entity.setProperty('pm_mock:ride_use_cooldown', 0);
                                            }
                                        }, 30);
                                    }
                                }

                                //幻翼膜，开火
                                else if (playerMainhandItem.typeId === 'minecraft:phantom_membrane') {
                                    playerControlRide(player, true);
                                    
                                    //使用了物品，而且不在冷却期
                                    if (entity.isSprinting && entity.getProperty('pm_mock:ride_use_cooldown') == 0) {
                                        // console.warn(`使用幻翼膜`);

                                        entity.triggerEvent("tamed_spit_entity");

                                        entity.setProperty('pm_mock:ride_use_cooldown', 1);
                                        

                                        //重置冷却
                                        system.runTimeout(() => {
                                            if (entity.isValid()) {
                                                entity.setProperty('pm_mock:ride_use_cooldown', 0);
                                            }
                                        }, 50);
                                    }
                                }
                            }
                            else {
                                // 如果玩家没有手持物品，清除记录
                                entity.setDynamicProperty('pm_mock:rider_holding_item', null);
                            }
                        }
                        // // 没有正在骑乘
                        // // 尝试寻找自己的属主，如果属主手持幻翼膜就跟随他
                        // else {
                        //     try {
                        //         const tameComponent = entity.getComponent('minecraft:tameable');
                        //         if (tameComponent) {
                        //             const owner = tameComponent.tamedToPlayer;
                        //             if (owner) {
                        //                 const ownerMainhandItem = owner.getComponent('minecraft:equippable').getEquipment('Mainhand');
                        //                 if (ownerMainhandItem && ownerMainhandItem.typeId === 'minecraft:phantom_membrane') {
                        //                     // console.warn(`${owner.name} is holding ${ownerMainhandItem.typeId}`);
                        //                     // console.warn(`${entity.name} is following ${owner.name}`)
                        //                 }
                        //             }
                        //         }
                                
                        //     } catch (error) {
                                
                        //     }
                        // }

                    }
                    // 非驯服状态，如果是眩晕状态
                    else if (entity.getProperty('pm_mock:skill_state') == 4) {
                        try {
                            entity.applyKnockback(0, 0, 0, -0.3);
                            entity.dimension.spawnParticle('pm_mock:stormspitter_stun_1', entity.location);
                        }
                        catch (error) {}
                        
                    }

                    
                }

                else if (entity.typeId === 'pm_mock:charged_bolt_projectile') {
                    try {
                        const velocity = entity.getDynamicProperty('pm_mock:bolt_velocity');
                        if (velocity) {
                            const realVelocity = entity.getVelocity();
                            const velocityDiff = { x: (velocity.x - realVelocity.x)/2, y: (velocity.y - realVelocity.y)/2, z: (velocity.z - realVelocity.z)/2 };
                            entity.applyImpulse(velocityDiff);
                        }

                        if (entity.getDynamicProperty('pm_mock:bolt_bounce_back') === true) {
                            const nearbyEntities = entity.dimension.getEntities({ type: 'pm_mock:stormspitter', location: entity.location, maxDistance: 5 });
                            if (nearbyEntities.length > 0) {
                                entity.triggerEvent('hit');
                                // console.warn(`bolt bounce back hit`);
                            }
                        }
                    }
                    catch (error) {
                        // console.warn(`${error}`);
                    }

                    

                }
            }
        }
    });
}, 2);

// 监听实体死亡
world.afterEvents.entityDie.subscribe((event) => {
    const { damageSource, deadEntity } = event;

    // 检查死亡的实体是否是 pm_mock:stormspitter
    if (deadEntity.typeId === 'pm_mock:stormspitter') {
        // 获取实体的动态属性列表
        const propertyList = deadEntity.getDynamicPropertyIds();

        // 剔除不可作为喷射目标的数据
        const validProperties = propertyList.filter(prop => !notSpitTarget.includes(prop));

        // 遍历有效的动态属性，生成相应的炮弹实体
        validProperties.forEach(prop => {
            const value = deadEntity.getDynamicProperty(prop);
            const dimension = deadEntity.dimension;
            if (typeof value === 'number' && value > 0) {
                for (let i = 0; i < value; i++) {
                    // 计算炮弹生成的位置（实体死亡位置）
                    const bulletLocation = {
                        x: deadEntity.location.x,
                        y: deadEntity.location.y,
                        z: deadEntity.location.z
                    };

                    try {
                        dimension.spawnEntity(prop, bulletLocation);
                    } catch (error) {}
                }
            }
        });
    }
});


// 监听击中实体
world.afterEvents.entityHitEntity.subscribe((event) => {
    const { damagingEntity, hitEntity } = event;
    // console.warn(`${damagingEntity.typeId} 击中了 ${hitEntity.typeId}`);
    if (damagingEntity.typeId === 'minecraft:player' && hitEntity.typeId === 'pm_mock:charged_bolt_projectile') {
        // console.warn(`玩家击中了charged_bolt_projectile`);
        const direction = damagingEntity.getViewDirection();
        const velocity = { x: direction.x * 1.5, y: direction.y * 1.5, z: direction.z * 1.5 };

        if (hitEntity.isValid()) {
            hitEntity.setDynamicProperty('pm_mock:bolt_velocity', velocity);
            hitEntity.setDynamicProperty('pm_mock:bolt_bounce_back', true);

            hitEntity.clearVelocity();
            hitEntity.triggerEvent('remove_float');

            system.runTimeout(() => {
                if (hitEntity.isValid()) {
                    hitEntity.applyImpulse(velocity);
                }
                
            }, 2);

        }

        

        

    }
});

