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

import com.uas.platform.b2b.dao.PurchaseForecastAllItemDao;
import com.uas.platform.b2b.model.PurchaseForecastAllItem;
import com.uas.platform.b2b.model.SearchFilter;
import com.uas.platform.b2b.service.PurchaseForecastOrderService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.Status;
import com.uas.platform.core.persistence.criteria.PredicateUtils;
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 org.springframework.util.CollectionUtils;
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;

@Service
public class PurchaseForecastOrderServiceImpl implements PurchaseForecastOrderService {

	@Autowired
	private PurchaseForecastAllItemDao purchaseForecastAllItemDao;


	@Override
	public List<PurchaseForecastAllItem> save(List<PurchaseForecastAllItem> items) {
		return purchaseForecastAllItemDao.save(items);
	}

	@Override
	public List<PurchaseForecastAllItem> findNotUploadOrder() {
		return purchaseForecastAllItemDao.findByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onEndDownSuccess(String[] idArray) {
		for (String id : idArray) {
			PurchaseForecastAllItem forecastAllItem = purchaseForecastAllItemDao.findOne(Long.parseLong(id));
			if (forecastAllItem != null) {
				forecastAllItem.setSendStatus((short) Status.DOWNLOADED.value());
				purchaseForecastAllItemDao.save(forecastAllItem);
			}
		}
	}

	@Override
	public Page<PurchaseForecastAllItem> findAllByPageInfo(final PageInfo pageInfo, final String keyword,
			final SearchFilter filter) {
		return purchaseForecastAllItemDao.findAll(new Specification<PurchaseForecastAllItem>() {
			@Override
            public Predicate toPredicate(Root<PurchaseForecastAllItem> root, CriteriaQuery<?> query,
                                         CriteriaBuilder builder) {
				if (filter != null) {
					if (!CollectionUtils.isEmpty(filter.getDistribute())) {
                        pageInfo.expression(PredicateUtils.in("order.enUU", filter.getDistribute(), false));
                    }
				}
				if (StringUtils.hasText(keyword)) {
                    query.where(pageInfo.getPredicates(root, query, builder));
                }
				return null;
			}
		}, pageInfo);
	}

	@Override
	public PurchaseForecastAllItem findById(Long id) {
		return purchaseForecastAllItemDao.findOne(id);
	}

}
