/**
 * Copyright &copy; 2017 beyo.com.cn All rights reserved.
 */
package com.lightinit.hsdatagateway.common.service;

import com.lightinit.hsdatagateway.common.persistence.DataVo;
import com.lightinit.hsdatagateway.common.persistence.GatewayDao;
import com.lightinit.hsdatagateway.common.persistence.Page;
import com.lightinit.hsdatagateway.modules.sys.utils.UserUtils;
import com.lightinit.hsdatagateway.common.persistence.DataVo;
import com.lightinit.hsdatagateway.common.persistence.GatewayDao;
import com.lightinit.hsdatagateway.common.persistence.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Service基类
 * @Author: yangrui
 * @version 2014-05-16
 */

public abstract class GatewayService<D extends GatewayDao<T>, T extends DataVo<T>> extends BaseService {
	
	/**
	 * 持久层对象
	 */
	@Autowired
	protected D dao;
	
	/**
	 * 获取单条数据
	 * @param id
	 * @return
	 */
	@Transactional(propagation = Propagation.SUPPORTS,isolation = Isolation.DEFAULT,readOnly = true)
	public T get(Long id) {
		return dao.get(id);
	}
	
	/**
	 * 获取单条数据
	 * @param entity
	 * @return
	 */
	@Transactional(propagation = Propagation.SUPPORTS,isolation = Isolation.DEFAULT,readOnly = true)
	public T get(T entity) {
		return dao.get(entity);
	}
	
	/**
	 * 查询列表数据
	 * @param entity
	 * @return
	 */
	@Transactional(propagation = Propagation.SUPPORTS,isolation = Isolation.DEFAULT,readOnly = true)
	public List<T> findList(T entity) {
		return dao.findList(entity);
	}
	
	/**
	 * 查询分页数据findList
	 * @param page 分页对象
	 * @param entity
	 * @return
	 */
	@Transactional(propagation = Propagation.SUPPORTS,isolation = Isolation.DEFAULT,readOnly = true)
	public Page<T> findPage(Page<T> page, T entity) {
		entity.setPage(page);
		page.setList(dao.findList(entity));
		return page;
	}

	/**
	 * 保存数据（插入或更新）
	 * @param entity
	 */
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor = Exception.class)
	public void save(T entity){
		if (null==entity.getId()){
			try{
				entity.nextId();
			}catch (Exception e){
				e.printStackTrace();
				//entity.setId(null);
			}
			entity.setCreateTime(new Date());
			//entity.setCreateUser(UserUtils.getUser().getId());
			dao.insert(entity);
			return;
		}
		entity.setUpdateTime(new Date());
		this.update(entity);

	}

	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor = Exception.class)
	public void update(T entity) {
		dao.update(entity);
	}
	
	/**
	 * 删除数据
	 * @param entity
	 */
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,rollbackFor = Exception.class)
	public void delete(T entity) {
		dao.delete(entity);
	}

}
