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.ProductDao;
import com.uas.platform.b2b.dao.PurchaseApBillDao;
import com.uas.platform.b2b.dao.PurchaseApBillItemDao;
import com.uas.platform.b2b.erp.model.PurchaseAPBill;
import com.uas.platform.b2b.erp.service.PurchaseAPBillService;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.Product;
import com.uas.platform.b2b.model.PurchaseApBill;
import com.uas.platform.b2b.model.PurchaseApBillItem;
import com.uas.platform.b2b.support.SystemSession;

@Service
public class PurchaseAPBillServiceImpl implements PurchaseAPBillService{

	@Autowired
	private PurchaseApBillDao purchaseApBillDao;
	
	@Autowired
	private PurchaseApBillItemDao purchaseApBillItemDao;
	
	@Autowired
	private ProductDao productDao;
	
	@Autowired
	private EnterpriseDao enterpriseDao;

	@Override
	public List<PurchaseApBillItem> convertApBills(List<PurchaseAPBill> apBills) {
		List<PurchaseApBillItem> apBillItems = new ArrayList<PurchaseApBillItem>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for(PurchaseAPBill apBill : apBills) {
			PurchaseApBill purchaseApBill = apBill.convert();
			List<PurchaseApBill> apBills2 = purchaseApBillDao.findPurchaseApBillByEnUUAndCode(enUU, purchaseApBill.getCode());
			Enterprise vendor = enterpriseDao.findEnterpriseByUu(purchaseApBill.getVendUU());
			if(apBills2.size() == 0 && vendor != null) {
				for(PurchaseApBillItem apBillItem : purchaseApBill.getItems()){
					List<Product> products = productDao.findByEnUUAndCode(enUU, apBillItem.getProduct().getCode());
					if(products.size() > 0) {
						apBillItem.setProduct(products.get(0));
					}
					apBillItem.setaPBill(purchaseApBill);
					apBillItems.add(apBillItem);
				}
				
			}
		}
		return apBillItems;
	}

}
