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.PurchaseReturnDao;
import com.uas.platform.b2b.dao.PurchaseReturnItemDao;
import com.uas.platform.b2b.model.PurchaseReturn;
import com.uas.platform.b2b.model.PurchaseReturnItem;
import com.uas.platform.b2b.service.PurchaseReturnService;
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 PurchaseReturnServiceImpl implements PurchaseReturnService{
	
	@Autowired
	private PurchaseReturnItemDao purchaseReturnItemDao;
	
	@Autowired
	private PurchaseReturnDao purchaseReturnDao;

	@Override
	public void save(List<PurchaseReturnItem> returnItems) {
		purchaseReturnItemDao.save(returnItems);
		//发送推送消息
		Set<Long> productId = new HashSet<Long>();
		for(PurchaseReturnItem returnItem : returnItems) {
			//不是每一个明细都发送，每个物料发一个
			if( ! productId.contains(returnItem.getOrderItem().getProduct().getId())){
				XingePusher.pushSingleAccountAndroid(returnItem.getOrderItem().getOrder().getVendUserUU().toString(), 
						"物料已被客户采购验退", "物料：" + returnItem.getOrderItem().getProduct().getTitle(),
						null);
				XingePusher.pushSingleAccountIOS(returnItem.getOrderItem().getOrder().getVendUserUU().toString(),
						returnItem.getOrderItem().getProduct().getTitle() + "已被客户采购验退");
				productId.add(returnItem.getOrderItem().getProduct().getId());
			}
		}
	}

	@Override
	public List<PurchaseReturn> findNotUpload() {
		return purchaseReturnDao.findPurchaseReturnByVendUUAndSendStatus(SystemSession.getUser().getEnterprise().getUu(),
				(short) Status.NOT_UPLOAD.value());
	}

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

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

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

	@Override
	public PurchaseReturn findById(Long id) {
		return purchaseReturnDao.findOne(id);
	}

}
