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

import com.uas.platform.b2b.publicapi.dao.TradeCountDao;
import com.uas.platform.b2b.publicapi.model.TradeCount;
import com.uas.platform.b2b.publicapi.service.TradeCountService;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.persistence.criteria.PredicateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * 查询销售额接口
 *
 * Created by hejq on 2018-05-30.
 */
@Service
public class TradeCountServiceImpl implements TradeCountService {

    @Autowired
    private TradeCountDao tradeCountDao;

    /**
     * 查询销售额统计
     *
     * @param tradeType 类型
     * @param currency  币别
     * @param fromDate  开始时间
     * @param endDate   截止时间
     * @return
     */
    @Override
    public List<TradeCount> findByParameters(String tradeType, String currency, String fromDate, String endDate, final PageInfo pageInfo) {
        if (!StringUtils.isEmpty(fromDate)) {
            pageInfo.expression(PredicateUtils.eq("fromDate", fromDate, true));
        }
        if (!StringUtils.isEmpty(endDate)) {
            pageInfo.expression(PredicateUtils.eq("endDate", endDate, true));
        }
        if (!StringUtils.isEmpty(currency)) {
            pageInfo.expression(PredicateUtils.eq("currency", currency, true));
        }
        if (!StringUtils.isEmpty(tradeType)) {
            pageInfo.expression(PredicateUtils.eq("tradeType", tradeType, true));
        }
        return tradeCountDao.findAll(new Specification<TradeCount>() {
            @Override
            public Predicate toPredicate(Root<TradeCount> root, CriteriaQuery<?> query,
                                         CriteriaBuilder builder) {
                return query.where(pageInfo.getPredicates(root, query, builder)).getRestriction();
            }
        });
    }
}
