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

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

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

import com.uas.platform.b2b.dao.EnterpriseDao;
import com.uas.platform.b2b.dao.PurchaseBadInDao;
import com.uas.platform.b2b.dao.PurchaseMRBDao;
import com.uas.platform.b2b.dao.PurchaseOrderDao;
import com.uas.platform.b2b.dao.PurchaseOrderItemDao;
import com.uas.platform.b2b.erp.model.PurchaseQuaMRB;
import com.uas.platform.b2b.erp.service.PurchaseQuaMRBService;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.PurchaseBadIn;
import com.uas.platform.b2b.model.PurchaseMRB;
import com.uas.platform.b2b.model.PurchaseOrderItem;
import com.uas.platform.b2b.support.SystemSession;

@Service
public class PurchaseQuaMRBServiceImpl implements PurchaseQuaMRBService{

	@Autowired
	private PurchaseOrderDao purchaseOrderDao;
	
	@Autowired
	private PurchaseOrderItemDao purchaseOrderItemDao;
	
	@Autowired
	private PurchaseMRBDao purchaseMRBDao;
	
	@Autowired
	private PurchaseBadInDao purchaseBadInDao;
	
	@Autowired
	private EnterpriseDao enterpriseDao;
	
	@Override
	public List<PurchaseMRB> convertMRBs(
			List<PurchaseQuaMRB> quaMRBs) {
		List<PurchaseMRB> mrbs = new ArrayList<PurchaseMRB>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for(PurchaseQuaMRB quaMRB : quaMRBs) {
			PurchaseMRB mrb = quaMRB.convent();
			List<PurchaseMRB> purchaseMRBs = purchaseMRBDao.findPurchaseMRBByEnUUAndCode(enUU, mrb.getCode());
			Enterprise vendor = enterpriseDao.findEnterpriseByUu(mrb.getVendUU());
			//采购验收单不存在，供应商UU号存在对应供应商
			if(purchaseMRBs.size() == 0 && vendor != null) {
				List<PurchaseBadIn> badIns =  purchaseBadInDao.findPurchaseBadInByEnUUAndCode(enUU, mrb.getBadIn().getCode());
				if(badIns.size() > 0) {//存在对应的不良品入库单
					mrb.setBadIn(badIns.get(0));
					mrb.setBadInId(badIns.get(0).getId());
				}
				List<PurchaseOrderItem> orderItems = purchaseOrderItemDao.findByEnUUAndOrderCodeAndNumber(enUU, mrb.getOrderItem().getOrder().getCode(), mrb.getOrderItem().getNumber());
				if(orderItems.size() > 0){//存在对应的采购单明细
					mrb.setOrderItem(orderItems.get(0));
					mrb.setOrderItemId(orderItems.get(0).getId());
					mrbs.add(mrb);
				}
			}
		}
		return mrbs;
	}

	

}
