package com.example.demo01.service.impl;

import com.example.demo01.entity.Player;
import com.example.demo01.mapper.PlayerMapper;
import com.example.demo01.service.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PlayerServiceImpl implements PlayerService {

    @Autowired
    private PlayerMapper playerMapper;

    @Override
    public Player getPlayerStatus(Long playerId) {
        return playerMapper.selectById(playerId);
    }

    @Override
    @Transactional // 涉及数据库修改，建议开启事务
    public boolean moveToRoom(Long playerId, Long newRoomId) {
        Player player = playerMapper.selectById(playerId);
        if (player == null) return false;

        player.setCurrentRoomId(newRoomId);
        return playerMapper.updateById(player) > 0;
    }

    @Override
    public void takeDamage(Long playerId, Integer damage) {
        Player player = playerMapper.selectById(playerId);
        if (player != null) {
            // 计算扣血后的 HP，确保不小于 0
            int newHp = Math.max(0, player.getHp() - damage);
            player.setHp(newHp);
            playerMapper.updateById(player);

            if (newHp == 0) {
                // 这里可以触发死亡逻辑，比如清空存档或传回出生点
                System.out.println("玩家 " + player.getName() + " 已阵亡！");
            }
        }
    }

    @Override
    public void addRewards(Long playerId, Integer exp, Integer gold) {
        Player player = playerMapper.selectById(playerId);
        if (player != null) {
            player.setExp(player.getExp() + exp);
            // 简单的升级逻辑：每 100 经验升一级
            if (player.getExp() >= player.getLevel() * 100) {
                player.setLevel(player.getLevel() + 1);
                player.setAtk(player.getAtk() + 5); // 升级加攻击
                player.setHp(player.getMaxHp());    // 升级回满血
            }
            playerMapper.updateById(player);
        }
    }
}
