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.PurchaseBadOutDao;
import com.uas.platform.b2b.dao.PurchaseBadOutItemDao;
import com.uas.platform.b2b.model.PurchaseBadOut;
import com.uas.platform.b2b.model.PurchaseBadOutItem;
import com.uas.platform.b2b.service.PurchaseBadOutService;
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 PurchaseBadOutServiceImpl implements PurchaseBadOutService{
	
	@Autowired
	private PurchaseBadOutDao purchaseBadOutDao;
	
	@Autowired
	private PurchaseBadOutItemDao purchaseBadOutItemDao;

	@Override
	public void save(List<PurchaseBadOutItem> badOutItems) {
		purchaseBadOutItemDao.save(badOutItems);
		//发送推送消息
		Set<Long> productId = new HashSet<Long>();
		for(PurchaseBadOutItem badOutItem : badOutItems) {
			//不是每一个明细都发送，每个物料发一个
			if( ! productId.contains(badOutItem.getOrderItem().getProduct().getId())){
				XingePusher.pushSingleAccountAndroid(badOutItem.getOrderItem().getOrder().getVendUserUU().toString(), 
						"物料已被客户不良品出库", "物料：" + badOutItem.getOrderItem().getProduct().getTitle(),
						null);
				XingePusher.pushSingleAccountIOS(badOutItem.getOrderItem().getOrder().getVendUserUU().toString(),
						badOutItem.getOrderItem().getProduct().getTitle() + "已被客户不良品出库");
				productId.add(badOutItem.getOrderItem().getProduct().getId());
			}
		}
	}

	@Override
	public List<PurchaseBadOut> findNotUpload() {
		return purchaseBadOutDao.findPurchaseBadOutByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

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

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

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

	@Override
	public PurchaseBadOut findById(Long id) {
		return purchaseBadOutDao.findOne(id);
	}

}
