package com.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.service.CommonService;
import com.util.IdGenerator;
import com.util.Page;

@Service("commonService")
public class CommonServiceImpl implements CommonService {

	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	
	public <T> List<T> findPage(String sqlId, Page page, Map<String, Object> paras) throws Exception {
		validateSqlId("findPage", sqlId);
		paras.put("page", page);
		return sqlSessionTemplate.selectList(sqlId+"ByPage", paras);
	}

	public <T> T findOne(String sqlId, Map<String, Object> paras) {
		validateSqlId("findOne", sqlId);
		return sqlSessionTemplate.selectOne(sqlId, paras);
	}

	public <T> List<T> findAll(String sqlId, Map<String, Object> paras) {
		validateSqlId("findAll", sqlId);
		return sqlSessionTemplate.selectList(sqlId, paras);
	}
	
	private void validateSqlId(String method, String sqlId){
		//if(StringUtils.isEmpty(sqlId))
		if(null == sqlId || "".equals(sqlId))
			throw new NullPointerException(getClass() + "." + method + " 方法中，参数\"sqlId\"不能为空!");
	}

	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	public String insert(String sqlId, Object obj) throws Exception {
		validateSqlId("insert", sqlId);
		Map<String, Object> paras = new HashMap<String, Object>();
		String uuid = IdGenerator.getUUID();
		paras.put("id", uuid);
		paras.put("obj", obj);
		this.sqlSessionTemplate.insert(sqlId, paras);
		return uuid;
	}

}
