package com.td.boss.game.combosses.service;

import com.td.boss.common.pojo.Result;
import com.td.boss.common.service.*;
import com.td.boss.game.combosses.pojo.ComBosses;
import com.td.boss.game.combosses.vo.ComBossesVo;
import com.td.boss.game.combosses.repository.ComBossesRepository;
import com.td.boss.game.combossesbattle.pojo.ComBossesBattle;
import com.td.boss.game.combossesbattle.repository.ComBossesBattleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class ComBossesServiceImpl extends CommonServiceImpl<ComBossesVo, ComBosses, Integer> implements ComBossesService{

    @PersistenceContext
    private EntityManager em;
    @Autowired
    private ComBossesRepository comBossesRepository;


    @Override
    public List<ComBosses> findAll() {
        return comBossesRepository.findAll(Sort.by(Sort.Direction.DESC,"id"));
    }

    /**
     * 获取bosses 数据，存入缓存中。
     * @param id
     * @return
     */
    @Override
    public ComBosses findById(Integer id) {
        return comBossesRepository.findById(id).orElse(null);
    }
    /**
     * 添加事务回退
     * @param bossesId
     * @return
     */
    @Override
    public ComBosses intoCombat(Integer bossesId) {
        Optional<ComBosses> comBossesOptional = comBossesRepository.findComBossesWithPessimisticLock(bossesId);
        if(!comBossesOptional.isPresent()){
            return null;
        }
        ComBosses comBosses = comBossesOptional.get();
        //设置boss属性 剩余血量，减一。
        comBosses.setRestHealth(comBosses.getRestHealth() -1);
        comBosses.setBattleCount(comBosses.getBattleCount() +1);
        return  comBossesRepository.save(comBosses);

    }

}
