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.PurchaseBadInDao;
import com.uas.platform.b2b.dao.PurchaseBadInItemDao;
import com.uas.platform.b2b.model.PurchaseBadIn;
import com.uas.platform.b2b.model.PurchaseBadInItem;
import com.uas.platform.b2b.service.PurchaseBadInService;
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 PurchaseBadInServiceImpl implements PurchaseBadInService{
	
	@Autowired
	private PurchaseBadInItemDao purchaseBadInItemDao;
	
	@Autowired
	private PurchaseBadInDao purchaseBadInDao;

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

	@Override
	public List<PurchaseBadIn> findNotUpload() {
		return purchaseBadInDao.findPurchaseBadInByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

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

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

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

	@Override
	public PurchaseBadIn findById(Long id) {
		return purchaseBadInDao.findOne(id);
	}

}
