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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.uas.platform.b2b.dao.MakeOrderChangeDao;
import com.uas.platform.b2b.dao.MakeOrderDao;
import com.uas.platform.b2b.erp.model.MakeChange;
import com.uas.platform.b2b.erp.model.MakeChangeReply;
import com.uas.platform.b2b.erp.service.MakeChangeService;
import com.uas.platform.b2b.model.MakeOrder;
import com.uas.platform.b2b.model.MakeOrderChange;
import com.uas.platform.b2b.model.MakeOrderChangeItem;
import com.uas.platform.b2b.support.SystemSession;

@Service
public class MakeChangeServiceImpl implements MakeChangeService {

	@Autowired
	private MakeOrderChangeDao makeOrderChangeDao;

	@Autowired
	private MakeOrderDao makeOrderDao;

	@Override
	public List<MakeOrderChangeItem> convertMakeChange(List<MakeChange> changes) {
		List<MakeOrderChangeItem> changeItems = new ArrayList<MakeOrderChangeItem>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		if (!CollectionUtils.isEmpty(changes)) {
			for (MakeChange change : changes) {
				MakeOrderChange orderChange = change.convert();
				List<MakeOrderChange> existOrderChanges = makeOrderChangeDao.findByEnUUAndCode(enUU,
						change.getMc_code());
				// 平台上已存在变更单时不保存
				if (CollectionUtils.isEmpty(existOrderChanges)
						&& !CollectionUtils.isEmpty(orderChange.getOrderChangeItems())) {
					for (MakeOrderChangeItem changeItem : orderChange.getOrderChangeItems()) {
						List<MakeOrder> makeOrders = makeOrderDao.findByEnUUAndCode(enUU, changeItem.getOrderCode());
						if (makeOrders.size() > 0) {
							MakeOrder makeOrder = makeOrders.get(0);
							changeItem.setOrderId(makeOrder.getId());
							changeItem.setProduct(makeOrder.getProduct());
							changeItem.setProductId(makeOrder.getProductId());
							changeItem.setVendUU(makeOrder.getVendUU());
							changeItem.setVendUserUU(makeOrder.getUserUU());
							changeItem.setOrderChange(orderChange);
							changeItem.setErpDate(new Date());
							changeItems.add(changeItem);
						}
					}
				}
			}
		}
		return changeItems;
	}

	@Override
	public List<MakeChangeReply> convertMakeOrderChangeReply(List<MakeOrderChangeItem> items) {
		List<MakeChangeReply> replies = new ArrayList<MakeChangeReply>();
		if (!CollectionUtils.isEmpty(items)) {
			for (MakeOrderChangeItem item : items) {
				replies.add(new MakeChangeReply(item));
			}
		}
		return replies;
	}

}
