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

import java.util.HashSet;
import java.util.List;
import java.util.Set;

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.PurchaseForecastAllDao;
import com.uas.platform.b2b.dao.PurchaseForecastAllItemDao;
import com.uas.platform.b2b.model.PurchaseForecastAllItem;
import com.uas.platform.b2b.service.PurchaseForecastOrderService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.support.XingePusher;
import com.uas.platform.core.model.PageInfo;
import com.uas.platform.core.model.Status;
@Service
public class PurchaseForecastOrderServiceImpl implements PurchaseForecastOrderService {

	@Autowired
	private PurchaseForecastAllItemDao purchaseForecastAllItemDao;
	
	@Autowired
	private PurchaseForecastAllDao purchaseForecastAllDao;
	
	@Override
	public List<PurchaseForecastAllItem> save(List<PurchaseForecastAllItem> items) {
		List<PurchaseForecastAllItem> items2 = purchaseForecastAllItemDao.save(items);
		Set<Long> vendUsers = new HashSet<Long>();
		for(PurchaseForecastAllItem item : items2) {
			//每一个相关的供应商联系人每次只接收到一条推送通知
			if(! vendUsers.contains(item.getVendUserUU())) {
				if(item.getVendUserUU() != null) {
					XingePusher.pushSingleAccountAndroid(item.getVendUserUU().toString(), 
							"客户对您下达了新的采购预测", "", null);
					XingePusher.pushSingleAccountIOS(item.getVendUserUU().toString(), 
							"客户对您下达了新的采购预测");
				}
				vendUsers.add(item.getVendUserUU());
			}
		}
		return items2;
	}

	@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) {
		return purchaseForecastAllItemDao.findAll(new Specification<PurchaseForecastAllItem>() {
			public Predicate toPredicate(Root<PurchaseForecastAllItem> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				query.where(pageInfo.getPredicates(root, query, builder));
				return null;
			}
		}, pageInfo);
	}

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

}
