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

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.PurchaseOrderAllDao;
import com.uas.platform.b2b.dao.PurchaseOrderDao;
import com.uas.platform.b2b.dao.PurchaseOrderItemDao;
import com.uas.platform.b2b.dao.PurchaseReplyDao;
import com.uas.platform.b2b.model.PurchaseOrder;
import com.uas.platform.b2b.model.PurchaseOrderAll;
import com.uas.platform.b2b.model.PurchaseOrderItem;
import com.uas.platform.b2b.model.PurchaseReply;
import com.uas.platform.b2b.service.PurchaseOrderService;
import com.uas.platform.core.model.PageInfo;

@Service
public class PurchaseOrderServiceImpl implements PurchaseOrderService {

	@Autowired
	private PurchaseOrderDao purchaseOrderDao;

	@Autowired
	private PurchaseOrderAllDao purchaseOrderAllDao;

	@Autowired
	private PurchaseReplyDao purchaseReplyDao;
	
	@Autowired
	private PurchaseOrderItemDao purchaseOrderItemDao;

	public Page<PurchaseOrder> findAllByPageInfo(final PageInfo pageInfo) {
		return purchaseOrderDao.findAll(new Specification<PurchaseOrder>() {

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

	@Override
	public Page<PurchaseOrderAll> findAllDetailByPageInfo(final PageInfo pageInfo) {
		return purchaseOrderAllDao.findAll(new Specification<PurchaseOrderAll>() {

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

	@Override
	public void reply(PurchaseReply reply) {
		purchaseReplyDao.save(reply);
		PurchaseOrderItem item = purchaseOrderItemDao.findOne(reply.getOrderItem().getId());
		Double replyQty = item.getReplyQty();
		replyQty = replyQty == null ? 0 : replyQty;
		item.setReplyQty(replyQty + reply.getQty());
		purchaseOrderItemDao.save(item);
	}

}
