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.PurchaseMRBDao;
import com.uas.platform.b2b.model.PurchaseMRB;
import com.uas.platform.b2b.service.PurchaseMRBService;
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 PurchaseMRBServiceImpl implements PurchaseMRBService{
	
	@Autowired
	private PurchaseMRBDao purchaseMRBDao;
	
	@Override
	public void save(List<PurchaseMRB> purchaseMRBs) {
		purchaseMRBDao.save(purchaseMRBs);
		//发送推送消息
		Set<Long> productId = new HashSet<Long>();
		for(PurchaseMRB purchaseMRB : purchaseMRBs) {
			//不是每一个明细都发送，每个物料发一个
			if( ! productId.contains(purchaseMRB.getOrderItem().getProduct().getId())){
				XingePusher.pushSingleAccountAndroid(purchaseMRB.getOrderItem().getOrder().getVendUserUU().toString(), 
						"物料已被客户MRB入库", "物料：" + purchaseMRB.getOrderItem().getProduct().getTitle(),
						null);
				XingePusher.pushSingleAccountIOS(purchaseMRB.getOrderItem().getOrder().getVendUserUU().toString(),
						purchaseMRB.getOrderItem().getProduct().getTitle() + "已被客户MRB入库");
				productId.add(purchaseMRB.getOrderItem().getProduct().getId());
			}
		}
	}

	@Override
	public List<PurchaseMRB> findNotUpload() {
		return purchaseMRBDao.findPurchaseMRBByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

	@Override
	public void onUploadSuccess(String[] idArray) {
		for(String id : idArray) {
			PurchaseMRB mrb = purchaseMRBDao.findOne(Long.parseLong(id));
			if(mrb != null) {
				mrb.setSendStatus((short) Status.DOWNLOADED.value());
				purchaseMRBDao.save(mrb);
			}
		}
	}

	@Override
	public Page<PurchaseMRB> findAllByPageInfo(final PageInfo pageInfo) {
		return purchaseMRBDao.findAll(new Specification<PurchaseMRB>() {

			public Predicate toPredicate(Root<PurchaseMRB> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				query.where(pageInfo.getPredicates(root, query, builder));
				return null;
			}
		}, pageInfo);
	}

	@Override
	public PurchaseMRB findById(Long id) {
		return purchaseMRBDao.findOne(id);
	}

}
