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

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uas.platform.b2b.dao.PurchaseNoticeDao;
import com.uas.platform.b2b.dao.PurchaseOrderItemDao;
import com.uas.platform.b2b.erp.model.AcceptNotify;
import com.uas.platform.b2b.erp.model.PurchaseNotify;
import com.uas.platform.b2b.erp.service.PurchaseNotifyService;
import com.uas.platform.b2b.model.PurchaseNotice;
import com.uas.platform.b2b.model.PurchaseOrderItem;
import com.uas.platform.b2b.model.SaleSend;
import com.uas.platform.b2b.model.SaleSendItem;

@Service
public class PurchaseNotifyServiceImpl implements PurchaseNotifyService {

	@Autowired
	private PurchaseOrderItemDao purchaseOrderItemDao;
	@Autowired
	private PurchaseNoticeDao purchaseNoticeDao;

	@Override
	public List<PurchaseNotice> convertPurchaseNotify(List<PurchaseNotify> notifies) {
		List<PurchaseNotice> notices = new ArrayList<PurchaseNotice>();
		for (PurchaseNotify notify : notifies) {
			PurchaseNotice notice = notify.convert();
			List<PurchaseOrderItem> orderItems = purchaseOrderItemDao.findByEnUUAndOrderCodeAndNumber(notice.getEnUU(), notice
					.getOrderItem().getOrder().getCode(), notice.getOrderItem().getNumber());
			if (!CollectionUtils.isEmpty(orderItems)) {
				notice.setOrderItem(orderItems.get(0));
				notice.setOrderItemId(notice.getOrderItem().getId());
				notices.add(notice);
			}
		}
		return notices;
	}

	@Override
	public List<AcceptNotify> convertSaleSend(List<SaleSend> sends) {
		List<AcceptNotify> accepts = new ArrayList<AcceptNotify>();
		for (SaleSend send : sends)
			accepts.add(new AcceptNotify(send));
		return accepts;
	}

	@Override
	public List<SaleSendItem> convertAcceptNotify(List<AcceptNotify> accepts) {
		List<SaleSendItem> sendItems = new ArrayList<SaleSendItem>();
		for (AcceptNotify accept : accepts) {
			SaleSend send = accept.convert();
			Set<SaleSendItem> items = send.getSendItems();
			if (!CollectionUtils.isEmpty(items)) {
				for (SaleSendItem item : items) {
					item.setSend(send);
					PurchaseNotice notice = item.getNotice();
					List<PurchaseNotice> notices = purchaseNoticeDao.findByEnUUAndSourceId(notice.getEnUU(), notice.getSourceId());
					if (!CollectionUtils.isEmpty(notices)) {
						item.setNotice(notices.get(0));
						item.setNoticeId(item.getNotice().getId());
						sendItems.add(item);
					}
				}
			}
		}
		return sendItems;
	}

}
