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

// 预设的结构名称列表
const structureNames = [
    { name: 'pm_m8:abandoned_factory', abbr: 'afa' },
    { name: 'pm_m8:medical_center', abbr: 'mce' },
    { name: 'pm_m8:monster_cave', abbr: 'mcv' },
    { name: 'pm_m8:monster_nest_ruins', abbr: 'mnr' },
    { name: 'pm_m8:outpost', abbr: 'otp' },
    { name: 'pm_m8:research_laboratory', abbr: 'rlb' },
    { name: 'pm_m8:subway_station', abbr: 'sws' }
];
let currentStructureIndex = 0;

// 每个结构的可选偏移坐标（x, y, z）
const structureOffsets = {
    'pm_m8:abandoned_factory': { x: 0, y: 0, z: 0 },
    'pm_m8:medical_center': { x: 0, y: 0, z: 0 },
    'pm_m8:monster_cave': { x: 9, y: 3, z: 9 },
    'pm_m8:monster_nest_ruins': { x: 0, y: 0, z: 0 },
    'pm_m8:outpost': { x: 0, y: 0, z: 0 },
    'pm_m8:research_laboratory': { x: 0, y: 0, z: 0 },
    'pm_m8:subway_station': { x: 0, y: 0, z: 0 }
};

// 维护序列号计数器，序列号会重复!
function getAndIncrementStructureCounter() {
    let currentCounter = world.getDynamicProperty('pm_m8:str_counter');
    if (currentCounter === undefined) {
        currentCounter = 0;
        world.setDynamicProperty('pm_m8:str_counter', currentCounter);
    }
    currentCounter++;
    if (currentCounter >= 9999) {
        currentCounter = 0;
    }
    world.setDynamicProperty('pm_m8:str_counter', currentCounter);
    return currentCounter;
}

system.afterEvents.scriptEventReceive.subscribe((event) => {
    const { id, message, sourceEntity } = event;

    if (id === 'pm_m8:structure_spawn') {
        const playerDimension = sourceEntity.dimension;
        const dimension = world.getDimension('overworld');
        if (playerDimension === dimension) {
            // 获取原实体的坐标
            const originalX = sourceEntity.location.x;
            const originalZ = sourceEntity.location.z;

            // 生成半径64以外、半径200以内的随机点

            let randomRadius = Math.random() * (200 - 64) + 64;
            // 如果在基地附近就例外
            if (message === 'around_base') {
                randomRadius = Math.random() * (120 - 80) + 80;
            } 
            
            let randomAngle = Math.random() * 2 * Math.PI;

            // 计算新的xz坐标
            let newX = originalX + randomRadius * Math.cos(randomAngle);
            let newZ = originalZ + randomRadius * Math.sin(randomAngle);

            // 取整
            newX = Math.round(newX);
            newZ = Math.round(newZ);

            // 在xz位置附近取多个随机点找最高方块坐标
            let minY = Infinity;
            let maxTries = 50;
            let counter = 0;
            let i = 0;
            for (i = 0; counter < 8 && i < maxTries; i++) { // 取8个点
                let offsetX = Math.floor(Math.random() * 25);
                let offsetZ = Math.floor(Math.random() * 25);
                let checkX = newX + offsetX;
                let checkZ = newZ + offsetZ;
                const topBlock = dimension.getTopmostBlock({ x: checkX, z: checkZ });
                if (topBlock.location.y >= 200 ) {
                    continue;
                }
                counter++;
                if (sourceEntity.hasTag(`log`)) {
                        sourceEntity.sendMessage(`structure_spawn: 检查生成结构位置 ${topBlock.location.x}, ${topBlock.location.y}, ${topBlock.location.z}`);
                    }
                let checkY = topBlock.location.y;
                if (checkY < minY) {
                    minY = checkY;
                }
            }
            if (counter < 8) { // 如果找到的点太少
                if (sourceEntity.hasTag(`log`)) {
                    sourceEntity.sendMessage(`structure_spawn: 失败 - 无法找到合适的生成位置`);
                }
                return;
            }
            

            // 获取当前结构名称并更新索引
            let currentStructure = structureNames[currentStructureIndex];
            let newStructureName = currentStructure.name;
            let newStructureAbbr = currentStructure.abbr;

            // 获取偏移值
            const offset = structureOffsets[newStructureName] || { x: 0, y: 0, z: 0 };

            currentStructureIndex = (currentStructureIndex + 1) % structureNames.length;
            

            // 特殊结构处理
            if (newStructureName === 'pm_m8:outpost') {
                if (sourceEntity.hasTag(`log`)) {
                    sourceEntity.sendMessage(`structure_spawn: 将要生成§aoutpost`);
                }

                if (minY > 63) {
                    if (sourceEntity.hasTag(`log`)) {
                        sourceEntity.sendMessage(`structure_spawn: 取消生成，因为§aoutpost最高方块大于63。name:${newStructureName}, x: ${newX}, z: ${newZ}`);
                    }
                    return; // 取消生成
                }

                // 将outpost的高度特殊设置
                minY = 3;
                
            } else if (newStructureName === 'pm_m8:monster_cave') {
                minY = Math.floor(Math.random() * 41) - 20; // 随机生成-20到20之间的整数
            } else if (minY <= 64) {
                // console.warn(`structure_spawn: 取消生成，因为最高方块小于等于62。name:${newStructureName}, x: ${newX}, z: ${newZ}`);
                if (sourceEntity.hasTag(`log`)) {
                    sourceEntity.sendMessage(`structure_spawn: 取消生成，因为最高方块小于等于64。name:${newStructureName}, x: ${newX}, z: ${newZ}`);
                }
                return; // 取消生成
            }

            // 检查已有结构是否过近
            const propertyIds = world.getDynamicPropertyIds();
            for (const propertyId of propertyIds) {
                if (propertyId.startsWith('pm_m8:str_')) {
                    const existingLocation = world.getDynamicProperty(propertyId);
                    if (existingLocation) {
                        const dx = Math.abs(newX - existingLocation.x);
                        const dz = Math.abs(newZ - existingLocation.z);
                        if (dx < 96 && dz < 96) {
                            // console.warn(`structure_spawn: 取消生成，因为结构距离过近。name:${newStructureName}, x: ${newX}, z: ${newZ}`);
                            if (sourceEntity.hasTag(`log`)) {
                                sourceEntity.sendMessage(`structure_spawn: 取消生成，因为结构距离过近。name:${newStructureName}, x: ${newX}, z: ${newZ}`);
                            }
                            return; // 取消生成
                        }
                    }
                }
            }

            // 如果是subway_station结构，y坐标减
            if (newStructureName === 'pm_m8:subway_station') {
                minY -= 10;
            }

            let structureLocation = { x: newX, y: minY, z: newZ };

            if (sourceEntity.hasTag(`log`)) {
                sourceEntity.sendMessage(`structure_spawn: Y 坐标: ${minY}`);
            }

            dimension.runCommand(`execute positioned ${newX} ${minY} ${newZ} run /tickingarea add circle ~~~ 3 structure_spawn `);
            system.runTimeout(() => {
                try {
                    world.structureManager.place(newStructureName, dimension, structureLocation);
                } catch (error) {}
                
            }, 20 * 0.5);
            

            

            system.runTimeout(() => {
                dimension.runCommand(`execute positioned ${newX} ${minY} ${newZ} run /tickingarea remove structure_spawn`);
            }, 20 * 1);

            // 生成唯一标识符
            let sequenceNumber = getAndIncrementStructureCounter().toString().padStart(4, '0');
            let hasBoss = 't'; // 默认有boss

            // 生成属性名
            let propertyName = `pm_m8:str_${newStructureAbbr}${sequenceNumber}_${hasBoss}`;

            // 偏移坐标
            const structureLocationWithOffset = {
                x: structureLocation.x + offset.x,
                y: structureLocation.y + offset.y,
                z: structureLocation.z + offset.z
            };

            // 存储世界属性
            world.setDynamicProperty(propertyName, structureLocationWithOffset);

            // console.warn(`生成结构: name:${newStructureName}, x: ${newX}, y: ${minY}, z: ${newZ}, 属性名: ${propertyName}`);
            if (sourceEntity.hasTag(`log`)) {
                sourceEntity.sendMessage(`生成结构: name:${newStructureName}, 原始坐标：(${structureLocation.x}, ${structureLocation.y}, ${structureLocation.z}), 属性名: ${propertyName}， 偏移后坐标：(${structureLocationWithOffset.x}, ${structureLocationWithOffset.y}, ${structureLocationWithOffset.z})`);
            }
        }
    }
    else if (id === 'pm_m8:structure_boss_defeat') {
        const playerDimension = sourceEntity.dimension;
        const dimension = world.getDimension('overworld');
        if (playerDimension === dimension) {
            // 获取原实体的坐标
            const originalX = sourceEntity.location.x;
            const originalY = sourceEntity.location.y;
            const originalZ = sourceEntity.location.z;
    
            // 获取世界的所有动态属性
            const propertyIds = world.getDynamicPropertyIds();
            let closestStructure = null;
            let closestDistance = Infinity;
    
            for (const propertyId of propertyIds) {
                if (propertyId.startsWith('pm_m8:str_')) {
                    const structureLocation = world.getDynamicProperty(propertyId);
                    if (structureLocation) {
                        const distance = Math.sqrt(
                            Math.pow(originalX - structureLocation.x, 2) +
                            Math.pow(originalY - structureLocation.y, 2) +
                            Math.pow(originalZ - structureLocation.z, 2)
                        );
                        if (distance < closestDistance) {
                            closestDistance = distance;
                            closestStructure = { propertyId, structureLocation, distance };
                        }
                    }
                }
            }
    
            if (closestStructure && closestDistance <= 128) {
                const propertyId = closestStructure.propertyId;

                // 检查是否是 Medical Center 或 Training Base 结构
                const isSpecialStructure = ['mce', 'bas'].some(abbr => propertyId.includes(abbr));

                if (isSpecialStructure) {
                    if (sourceEntity.hasTag('log')) {
                        sourceEntity.sendMessage(`不修改 boss 标志：该结构为 基地类型`);
                    }
                    return;
                }

                // 修改属性名的最后一位为 'f'
                const newPropertyId = closestStructure.propertyId.slice(0, -1) + 'f';
                const structureLocation = closestStructure.structureLocation;
    
                // 存储所有动态属性
                const propertiesToRestore = {};
                for (const propertyId of propertyIds) {
                    propertiesToRestore[propertyId] = world.getDynamicProperty(propertyId);
                }
    
                // 清空所有动态属性
                world.clearDynamicProperties();
    
                // 重新设置除了需要修改的属性外的所有属性
                for (const propertyId in propertiesToRestore) {
                    if (propertyId !== closestStructure.propertyId) {
                        const value = propertiesToRestore[propertyId];
                        world.setDynamicProperty(propertyId, value);
                        if (sourceEntity.hasTag(`log`)) {
                            sourceEntity.sendMessage(`设置属性: ${propertyId}`);
                        }
                    }
                }
    
                // 设置修改后的属性
                world.setDynamicProperty(newPropertyId, structureLocation);
    
                // 报告结果
                if (sourceEntity.hasTag(`log`)) {
                    console.warn(`玩家坐标: X:${originalX}, Y:${originalY}, Z:${originalZ}`);
                    console.warn(`结构坐标: X:${structureLocation.x}, Y:${structureLocation.y}, Z:${structureLocation.z}`);
                    console.warn(`修改的属性名: ${closestStructure.propertyId}`);
                    console.warn(`修改后的属性名: ${newPropertyId}`);
                }
                
            } else {
                if (sourceEntity.hasTag(`log`)) {
                    sourceEntity.sendMessage(`structure_boss_defeat: 没有找到距离玩家128格以内的结构。`);
                }
            }
        }
    }
    else if (id === 'pm_m8:structure_spawn_base') {
        //获取玩家当前位置，将这个位置设置为世界属性pm_m8:str_bas0000_t
        const playerDimension = sourceEntity.dimension;
        const dimension = world.getDimension('overworld');
        if (playerDimension === dimension) {
            // 获取玩家当前位置
            const playerLocation = sourceEntity.location;

            // 生成唯一标识符
            let sequenceNumber = '0000';
            let hasBoss = 't';

            // 生成属性名
            let propertyName = `pm_m8:str_bas${sequenceNumber}_${hasBoss}`;
            world.setDynamicProperty(propertyName, playerLocation);
        }
    }
});


// 每隔一段时间生成一个结构
system.runInterval(() => {
    const players = world.getAllPlayers();
    if (players.length === 0) return; // 如果没有玩家在线，直接返回

    // 随机选择一个玩家
    const randomIndex = Math.floor(Math.random() * players.length);
    const selectedPlayer = players[randomIndex];

    const initScore = world.scoreboard.getObjective("world").getScore("initialised");

    if (initScore < 500) {
        if (selectedPlayer.hasTag(`log`)) {
            selectedPlayer.sendMessage(`生成结构: 时间太早，不生成`);
        }
        return;
    }

    selectedPlayer.runCommand(`scriptevent pm_m8:structure_spawn`);
    
}, 20 * 4)