/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.ejweb.core.service;

import java.util.ArrayList;
import java.util.List;

import com.ejweb.modules.report.dao.CtBbtcBusCategoryDao;
import com.ejweb.modules.report.dao.CtBbtcBusTypeDao;
import com.ejweb.modules.report.entity.CtBbtcBusCategory;
import com.ejweb.modules.report.entity.CtBbtcBusType;
import com.ejweb.modules.report.entity.ReportEntity;
import com.ejweb.modules.report.service.CtBbtcBusCategoryService;
import com.ejweb.modules.report.service.CtBbtcBusTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.ejweb.core.persistence.CrudDao;
import com.ejweb.core.persistence.DataEntity;
import com.ejweb.core.persistence.Page;

/**
 * Service基类
 * @author ThinkGem
 * @version 2014-05-16
 */
@Transactional(readOnly = true)
public abstract class CrudService<D extends CrudDao<T>, T extends DataEntity<T>> extends BaseService {
    
    /**
     * 持久层对象
     */
    @Autowired
    protected D dao;


    /**
     * 获取单条数据
     * @param id
     * @return
     */
    public T get(String id) {
        return dao.get(id);
    }
    
    /**
     * 获取单条数据
     * @param entity
     * @return
     */
    public T get(T entity) {
        return dao.get(entity);
    }
    
    /**
     * 查询列表数据
     * @param entity
     * @return
     */
    public List<T> findList(T entity) {
        return dao.findList(entity);
    }
    
    /**
     * 查询分页数据
     * @param page 分页对象
     * @param entity
     * @return
     */
    public Page<T> findPage(Page<T> page, T entity) {
        entity.setPage(page);
        List list=  dao.findList(entity);
        page.setList(list);
        return page;
    }

    /**
     * 保存数据（插入或更新）
     * @param entity
     */
    @Transactional(readOnly = false)
    public void save(T entity) {
        if (entity.getIsNewRecord()){
            entity.preInsert();

            List<T> byNumber = dao.getByNumber(entity);
            if(byNumber.size() != 0){
                throw  new RuntimeException("保存失败，编码重复！！！！！！");
            }
            dao.insert(entity);
        }else{
            entity.preUpdate();
            dao.update(entity);
        }
    }
    
    /**
     * 删除数据
     * @param entity
     */
    @Transactional(readOnly = false)
    public void delete(T entity) {
        dao.delete(entity);
    }

}
