package org.ccpit.business.phase;

import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.Phased;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * Date: 2015年11月16日 09:58
 *
 * @author 孙其鹏
 * @version 1.0
 */
@Service
public class PhaseService {
    @Autowired
    private PhaseDao phaseDao;

    @Transactional
    public boolean add(Phase phase){
        return phaseDao.save(phase);
    }
    @Transactional
    public boolean update(Phase phase){
        return phaseDao.save(phase);
    }
    @Transactional
    public boolean delete(Phase phase){
        if (phase==null){
            return false;
        }

        if (phase.isWhetherDelete())
            return true;

        phase.setWhetherDelete(true);
        return phaseDao.save(phase);
    }
    @Transactional
    public boolean deletePhases(List<Long> ids){
        boolean success = true;
        for (long id:ids){
            boolean result = delete(queryById(id));
            if (!result){
                success = false;
            }
        }
        return success;
    }


    public Page<Phase> queryByPage(PageRequest pr, String hql, String... params) {
        return phaseDao.findPage(pr, hql, params);
    }
    public List<Phase> queryAll() {
        return phaseDao.query("from Phase order by time desc");
    }
    public Phase queryById(Long id) {
        return phaseDao.queryById(id);
    }


    /**
     * 获取状态为active的Phase  只有0或1个
     * @return
     */
    public Phase getActivePhase(){
        List<Phase> phaseList = phaseDao.query("from Phase where active = ?",true);
        if (phaseList==null || phaseList.isEmpty()){
            return null;
        }
        return phaseList.get(0);
    }
}