package com.neusoft.smart.pos.org.repository;

import com.neusoft.smart.pos.dto.org.request.OrgQueryRequest;
import com.neusoft.smart.pos.org.persistent.domain.Org;
import com.neusoft.smart.pos.org.persistent.domain.OrgExample;
import com.neusoft.smart.pos.org.persistent.domain.OrgExample.Criteria;
import com.neusoft.smart.pos.org.persistent.mapper.OrgMapper;

import lombok.val;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author tjm
 * @date 2018-03-01 13：57
 * @description 集团管理使用Repository
 */
@Component
public class OrgRepository {

	@Autowired
	public OrgMapper orgMapper;

	/**
	 * 根据集团名称查询集团信息使用方法
	 * @param name：集团名称
	 * @return
	 */
	public Org queryOrgByName(String name){
		val example = new OrgExample();
		example.createCriteria()
				.andNameEqualTo(name);
		val orgs = orgMapper.selectByExample(example);
		return orgs.size()>0?orgs.get(0):null;
	}
	
	public Org selectByPrimaryKey(Integer id){
		return orgMapper.selectByPrimaryKey(id);
	}
	
	public int insertSelective(Org org){
		return orgMapper.insertSelective(org);
	}
	
	public int updateByPrimaryKeySelective(Org org){
		return orgMapper.updateByPrimaryKeySelective(org);
	}
	
	public List<Org> selectByExample(OrgQueryRequest orgQueryRequest){
		return orgMapper.selectByExample(createExample(orgQueryRequest));
	}
	
	public int countOrgsByCondi(OrgQueryRequest orgQueryRequest){
		return orgMapper.countByExample(createExample(orgQueryRequest));
	}
	
	private OrgExample createExample(OrgQueryRequest orgQueryRequest){
		OrgExample orgExample = new OrgExample();
        if (!StringUtils.isEmpty(orgQueryRequest.getOrderField()) && !StringUtils.isEmpty(orgQueryRequest.getDire())) orgExample.setOrderByClause(orgQueryRequest.getOrderField() + " " + orgQueryRequest.getDire());
        if (!StringUtils.isEmpty(orgQueryRequest.getOffset()) && !StringUtils.isEmpty(orgQueryRequest.getLimit())){
        	orgExample.setOffset(orgQueryRequest.getOffset());
        	orgExample.setLimit(orgQueryRequest.getLimit());
        } 
        Criteria orgCriteria = orgExample.createCriteria();
        orgCriteria.andStatusEqualTo("1");
        if (!StringUtils.isEmpty(orgQueryRequest.getId())) orgCriteria.andIdEqualTo(Integer.parseInt(orgQueryRequest.getId()));
        if (!StringUtils.isEmpty(orgQueryRequest.getName())) orgCriteria.andNameLike("%" + orgQueryRequest.getName() + "%");    
        if (!StringUtils.isEmpty(orgQueryRequest.getCreateDate())) orgCriteria.andCreateDateLike(orgQueryRequest.getCreateDate() + "%");
        if (!StringUtils.isEmpty(orgQueryRequest.getType())) orgCriteria.andTypeEqualTo(orgQueryRequest.getType());
        return orgExample;
	}

}
