package com.fos.core.base;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;

import com.fos.core.conf.GConstants;

/**
 * Service基类
 * @team BBDTEK Dev Team
 * @version 1.0
 * @time 2016-03-10
 */
@Transactional(readOnly = true)
public abstract class BaseService <D extends BaseDao>{

    @Autowired(required=false)  
    protected Validator validator;//这个需要在applicationContext.xml中配置bean注射进来  

    protected String dbprefix=GConstants.getValue("db.table.prefix", "");// 数据库表前缀
    /**
     * 持久层对象
     */
    @Autowired
    protected D dao;
    
//    public long getShopIdByCode(String shopCode){
//        return dao.getShopIdByCode(shopCode);
//    }
//    
//    public long getUserIdByCode(String userCode){
//        return dao.getUserIdByCode(userCode);
//    }
    /**
     * 验证
     * @param target
     * @param errors
     * @return
     */
    public String validate(Object target, BindingResult errors){
        if(target == null)
            return "获取对象为NULL";
        validator.validate(target, errors);
        if(errors !=null && errors.hasErrors()){
            List<ObjectError>  allErrors = errors.getAllErrors();
            if(allErrors !=null && allErrors.size()>0)
                return allErrors.get(0).getDefaultMessage();
        }
        return null;
    }
    public String validate(Object target){
        if(target == null)
            return "获取对象为NULL";
        BindingResult errors = new BeanPropertyBindingResult(target, target.getClass().getName());
        validator.validate(target, errors);
        if(errors !=null && errors.hasErrors()){
            List<ObjectError>  allErrors = errors.getAllErrors();
            if(allErrors !=null && allErrors.size()>0)
                return allErrors.get(0).getDefaultMessage();
        }
        return null;
    }
}
