package com.uas.platform.b2b.erp.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.uas.platform.b2b.dao.CommonDao;
import com.uas.platform.b2b.erp.dao.ErpLogDao;
import com.uas.platform.b2b.erp.model.ErpLog;
import com.uas.platform.b2b.erp.model.ErpLogMessageStat;
import com.uas.platform.b2b.erp.service.ErpLogService;
import com.uas.platform.b2b.model.SearchFilter;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.persistence.criteria.PredicateUtils;

@Service
public class ErpLogServiceImpl implements ErpLogService {
	
	@Autowired
	private ErpLogDao erpLogDao;

	@Autowired
	private CommonDao commonDao;

	@Override
	public void save(ErpLog log) {
		erpLogDao.save(log);
	}

	@Override
	public void save(Iterable<ErpLog> logs) {
		erpLogDao.save(logs);
	}
	
	/**
	 * @description 根据搜索参数查询
	 * @author Hao
	 * @date 2015年9月28日17:17:38
	 * 
	 */
	@Override
	public Page<ErpLog> findSearchByPageInfo(final PageInfo pageInfo, SearchFilter filter) {
		if(filter != null) {
			if(filter.getFromDate() != null){
				pageInfo.expression(PredicateUtils.gte("time", new Long(filter.getFromDate()), false));
			}
			if(filter.getEndDate() != null) {
                pageInfo.expression(PredicateUtils.lte("time", new Long(filter.getEndDate()), false));
            }
		}
		Page<ErpLog> erpLog = erpLogDao.findAll(new Specification<ErpLog>() {
			@Override
            public Predicate toPredicate(Root<ErpLog> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
			}
		},pageInfo);
		return erpLog;
	}

	@Override
	public List<ErpLogMessageStat> findMessageStat(Long enuu, SearchFilter filter) {
		String where = "";
		boolean whereAdded = false;
		if(enuu != null) {
			whereAdded = true;
			where += " where";
			where += " log_enuu = " + enuu;
		}
		if(filter != null) {
			if(filter.getFromDate() != null) {
				if(whereAdded) {
					where += " and";
				} else {
					where += " where";
				}
				whereAdded = true;
				where += " log_time >= " + filter.getFromDate();
			}
			if(filter.getEndDate() != null) {
				if(whereAdded) {
					where += " and";
				} else {
					where += " where";
				}
				whereAdded = true;
				where += " log_time <= " + filter.getEndDate();
			}
		}
		String sql = "select log_message, sum(log_total) log_sum from log$erp " + where + " group by log_message order by log_sum desc";
		List<ErpLogMessageStat> list = commonDao.query(sql, ErpLogMessageStat.class);
		return list;
	}

}
