
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials } = event;
    if (!player || !player.getServer()) return;

    //锻造时更新effect之类的东西
    //锻造时，自动检测，排序effect，并且存储进nbt
    let server = player.getServer();
    server.scheduleInTicks(2, () => {
        updateItemEffects(upgradedStack);
    });
    // 测试专用
    //upgradedStack.item.setHoningProgress(upgradedStack, 0);

});

TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials } = event;
    if (!player || !player.getServer()) return;
    ShowModelHelper.clearShowModel(upgradedStack);
    ShowModelHelper.addShowModel(upgradedStack, "form_1", "item")

    upgradedStack.getEnchantmentTags().removeIf(
        tag => tag.asString.includes('pasterdream:enchantment_shelterer')
    )
});

//改造时强制保留真变换之刃效果
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials, workbenchTile } = event
    //防止单人的时候client侧出问题
    if (level.clientSide || !targetStack || !upgradedStack) return
    if (upgradedStack.item instanceof $ModularItem && targetStack.item instanceof $ModularItem) {

        //检测改造的outcome是否带有module
        if (hasModuleKey(currentSchematic)) {
            //获取改造前的module
            let target_module = targetStack.getItem().getModuleFromSlot(targetStack, currentSlot)
            //获取改造后的module
            let upgrade_module = upgradedStack.getItem().getModuleFromSlot(upgradedStack, currentSlot)
            //检测改造前是否有真变换之刃
            if (targetStack && target_module && target_module instanceof $ItemModuleMajor && target_module.getImprovement(targetStack, 'true_shifting_blade') != null) {
                //加回improvement
                upgrade_module.addImprovement(upgradedStack, 'true_shifting_blade', 0)
            }
        }
    }
})

//改造时移除空气改进
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials, workbenchTile } = event
    //防止单人的时候client侧出问题
    if (level.clientSide || !targetStack || !upgradedStack) return
    //根据slot获取module
    let module = upgradedStack.getItem().getModuleFromSlot(upgradedStack, currentSlot)
    remove_improvement(upgradedStack, 'shared/air', true, module)
})

//献祭效果实现
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials, workbenchTile } = event
    //防止单人的时候client侧出问题
    if (level.clientSide || !targetStack || !upgradedStack) return
    let schematic = currentSchematic.key
    switch (schematic) {
        case "armor/shared/living_armor/sacrifice/sacrifice_1":
            living_armor_sacrifice(event, schematic)
            break;
        case "armor/shared/living_armor/sacrifice/sacrifice_2":
            living_armor_sacrifice(event, schematic)
            break;
        case "armor/shared/living_armor/sacrifice/sacrifice_3":
            living_armor_sacrifice(event, schematic)
            break;
        case "armor/shared/living_armor/sacrifice/sacrifice_4":
            living_armor_sacrifice(event, schematic)
            break;
        case "armor/shared/living_armor/sacrifice/sacrifice_5":
            living_armor_sacrifice(event, schematic)
            break;
    }
})
function living_armor_sacrifice(event, schematic) {
    let player = event.player
    let count = 0
    let entityList = getLivingWithinRadius(player.getLevel(), player.position(), 8)
    entityList.forEach(entity => {
        if (entity.type == 'minecraft:villager') {
            entity.kill()
            count += 1
        }
    })
    if (count < 3) {
        player.tell('祭品不足')
        //根据slot获取module
        let module = event.upgradedStack.getItem().getModuleFromSlot(event.upgradedStack, event.currentSlot)
        remove_improvement(event.upgradedStack, 'living_armor/sacrifice', false, module)
    }
}

//熔岩吸收效果实现
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials, workbenchTile } = event
    //防止单人的时候client侧出问题
    if (level.clientSide || !targetStack || !upgradedStack) return
    let schematic = currentSchematic.key

    if (schematic != "sword/flamberge_blade/lava_absorption_5" &&
        schematic != "sword/flamberge_blade/lava_absorption_4" &&
        schematic != "sword/flamberge_blade/lava_absorption_3" &&
        schematic != "sword/flamberge_blade/lava_absorption_2" &&
        schematic != "sword/flamberge_blade/lava_absorption_1"
    ) return


    let workbenchTilePos = workbenchTile.getBlockPos()
    let count = 0
    // 遍历3×3区域（x和z方向各偏移1格，y为玩家脚下）
    for (let x = -1; x <= 1; x++) {
        for (let z = -1; z <= 1; z++) {
            let pos = workbenchTilePos.offset(x, -1, z)
            let state = level.getBlockState(pos)
            let block = state.getBlock()
            let block_id = block.getId()
            if (block_id == 'minecraft:magma_block') {
                level.destroyBlock(pos, false, player)
                count += 1
            }
        }
    }

    if (count != 9) {
        player.tell('岩浆块不足,岩浆块不足,岩浆块不足');
        let module = upgradedStack.getItem().getModuleFromSlot(upgradedStack, currentSlot)
        //等级减一
        remove_improvement(upgradedStack, "flamberge_blade/lava_absorption", false, module)
    }

})

//祛魔书转移附魔
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials } = event
    //防止单人的时候client侧出问题
    if (level.clientSide || !targetStack || !upgradedStack) return
    let materialItem = materials[0].id
    if (materialItem != "kubejs:qu_mo_shu") return
    if (upgradedStack.isEnchanted()) {
        upgradedStack.allEnchantments.forEach((name, level) => {
            player.give(Item.of('minecraft:enchanted_book').enchant(name, Math.min(level, 5)))
        })
        upgradedStack.nbt.remove('Enchantments')
    } else {
        player.tell('没有附魔')
        player.give("kubejs:qu_mo_shu")
    }
})
//磨刀石效果实现
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials } = event
    //防止单人的时候client侧出问题
    if (level.clientSide || !targetStack || !upgradedStack) return
    let materialItem = materials[0].id
    if (materialItem == 'kubejs:whetstone') {
        if (!upgradedStack.nbt.honing_available) {
            upgradedStack.item.setHoningProgress(upgradedStack, 0)
        } else {
            let conversion_level = simpleGetTetraEffectLevel(upgradedStack, 'over_honing:conversion');
            //获取打磨值上限
            let honing_limit = upgradedStack.item.getHoningLimit(upgradedStack);

            $OverHoningUtil.addOverHoning(upgradedStack, honing_limit * (1 + conversion_level / 100));
        }
    }

    if (currentSchematic.key == 'shared/whetstone_overcharge') {
        if (!upgradedStack.nbt.honing_available) {
            upgradedStack.item.setHoningProgress(upgradedStack, 0)
        } else {
            let conversion_level = simpleGetTetraEffectLevel(upgradedStack, 'over_honing:conversion');
            //获取打磨值上限
            let honing_limit = upgradedStack.item.getHoningLimit(upgradedStack);

            $OverHoningUtil.addOverHoning(upgradedStack, honing_limit * (1 + conversion_level / 100));
        }

        let conversion_level = simpleGetTetraEffectLevel(upgradedStack, 'over_honing:conversion');
        //获取打磨值上限
        let honing_limit = upgradedStack.item.getHoningLimit(upgradedStack);

        $OverHoningUtil.addOverHoning(upgradedStack, honing_limit * 9 * (1 + conversion_level / 100));

    }
})
//附魔附加
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials } = event
    //防止单人的时候client侧出问题
    if (level.clientSide || !targetStack || !upgradedStack) return
    player.getServer().scheduleInTicks(1, () => {
        //时运附加
        forgeing_enchantment('tetra:modular_double', 'add_fortune', "minecraft:fortune", upgradedStack)
        //精准采集附加
        forgeing_enchantment('tetra:modular_double', 'add_silk_touch', "minecraft:silk_touch", upgradedStack)
        //效率附加
        forgeing_enchantment('tetra:modular_double', 'add_efficiency', "minecraft:efficiency", upgradedStack)
        forgeing_enchantment('tetra:modular_single', 'add_efficiency', "minecraft:efficiency", upgradedStack)
        //煤炭
        forgeing_enchantment('tetra:modular_sword', 'coal', "minecraft:smite", upgradedStack)
        //忠诚和激流
        forgeing_enchantment('tetra:modular_single', 'add_riptide', "minecraft:riptide", upgradedStack)
        forgeing_enchantment('all', 'add_loyalty', "minecraft:loyalty", upgradedStack)
        //经验修补
        forgeing_enchantment('all', 'add_mending', "minecraft:mending", upgradedStack)
        // 灰烬砖
        forgeing_enchantment('tetra:modular_sword', 'ash_brick', "minecraft:fire_aspect", upgradedStack)
        // 很红的砖
        forgeing_enchantment('tetra:modular_sword', 'brick', "jerotes:bane_of_humanoids", upgradedStack)
        //抢夺附加
        forgeing_enchantment('all', 'add_looting', "minecraft:looting", upgradedStack)
    })
})
//天雷锻兵
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials } = event

    if (currentSchematic.key != "sword/basic_blade/lei_1" && currentSchematic.key != "sword/basic_blade/lei_2" && currentSchematic.key != "sword/basic_blade/lei_3") return

    let random = Math.random()
    if (random < 0.05) {
        event.upgradedStack.shrink(1)
        player.tell('锻造失败')
    }

    // 获取玩家的坐标
    let playerX = player.x;
    let playerY = player.y;
    let playerZ = player.z;

    // 循环遍历玩家周围两格的范围
    for (let x = -2; x <= 2; x++) {
        for (let z = -2; z <= 2; z++) {
            // 创建闪电实体
            let entity_1 = level.createEntity("minecraft:lightning_bolt");
            // 设置闪电的位置
            entity_1.setPosition(playerX + x, playerY, playerZ + z);
            // 生成闪电实体
            entity_1.spawn();
        }
    }
})
//恐龙骨头给不毁效果
//以及移除不毁效果
TetraJSEvents.workbenchCraft(event => {
    let { targetStack, upgradedStack } = event

    if (upgradedStack?.nbt && !upgradedStack.nbt?.Unbreakable && hasItemEffect(upgradedStack, 'dinosaur_bone')) {
        upgradedStack.nbt.merge({ Unbreakable: 1 })
    }
    if (upgradedStack?.nbt && upgradedStack.nbt?.Unbreakable && !hasItemEffect(upgradedStack, 'dinosaur_bone')) {
        upgradedStack.nbt.remove('Unbreakable')
    }

})
//骷髅狗头人将军头颅和蛇龙合金锭联动
TetraJSEvents.workbenchCraft(event => {
    let { player, level, currentSchematic, currentSlot, targetStack, upgradedStack, materials } = event

    if (upgradedStack.nbt && hasItemEffect(upgradedStack, 'kobolediator_skull') && hasItemEffect(upgradedStack, 'serpon_alloy_ingot')) {
        if (!upgradedStack.nbt.contains("sword/blade:dragon_blood")) {
            $ItemModuleMajor.addImprovement(upgradedStack, "sword/blade", "dragon_blood", 1);
            updateItemEffects(upgradedStack);
        }
    }
    if (upgradedStack.nbt && upgradedStack.nbt.contains("sword/blade:dragon_blood")) {
        if (!hasItemEffect(upgradedStack, 'kobolediator_skull_check') || !hasItemEffect(upgradedStack, 'serpon_alloy_ingot')) {
            upgradedStack.nbt.remove("sword/blade:dragon_blood")
            updateItemEffects(upgradedStack);
        }
    }
})