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

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

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

import com.uas.platform.b2b.dao.ProductDao;
import com.uas.platform.b2b.dao.SaleQuotationDao;
import com.uas.platform.b2b.dao.VendorDao;
import com.uas.platform.b2b.erp.model.Quotation;
import com.uas.platform.b2b.erp.model.QuotationDecide;
import com.uas.platform.b2b.erp.service.QuotationService;
import com.uas.platform.b2b.model.Product;
import com.uas.platform.b2b.model.SaleQuotation;
import com.uas.platform.b2b.model.SaleQuotationItem;
import com.uas.platform.b2b.model.Vendor;
import com.uas.platform.b2b.support.SystemSession;

@Service
public class QuotationServiceImpl implements QuotationService {

	@Autowired
	private ProductDao productDao;
	
	@Autowired
	private VendorDao vendorDao;

	@Autowired
	private SaleQuotationDao saleQuotationDao;

	@Override
	public List<SaleQuotationItem> convertQuotation(List<Quotation> quotations) {
		List<SaleQuotationItem> items = new ArrayList<SaleQuotationItem>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (Quotation quotation : quotations) {
			// 先查看是否已存在
			List<SaleQuotation> quotations2 = saleQuotationDao.findByEnUUAndCode(enUU, quotation.getQu_code());
			if (quotations2.size() == 0) {
				SaleQuotation saleQuotation = quotation.convert();
				List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(saleQuotation.getCustUU(), saleQuotation.getEnUU());
				if(vendors.size() > 0) {//存在对应的供应商资料
					//如果主动报价单中的客户联系人uu号为空，则设为供应商资料中的客户联系人
					if(saleQuotation.getCustUserUU() == null) saleQuotation.setCustUserUU(vendors.get(0).getMyUserUU());
					//如果主动报价单中的供应商联系人uu号为空，则设为供应商资料中的供应商联系人
					if(saleQuotation.getUserUU() == null) saleQuotation.setUserUU(vendors.get(0).getVendUserUU());
				}
				if (!CollectionUtils.isEmpty(saleQuotation.getQuotationItems())) {
					for (SaleQuotationItem item : saleQuotation.getQuotationItems()) {
						item.setQuotation(saleQuotation);
						// 取平台的产品ID
						Product product = item.getProduct();
						List<Product> products = productDao.findByEnUUAndCode(product.getEnUU(), product.getCode());
						if (products.size() > 0) {
							item.setProduct(products.get(0));
							item.setProductId(products.get(0).getId());
						}
					}
					items.addAll(saleQuotation.getQuotationItems());
				}
			}
		}
		return items;
	}

	@Override
	public List<QuotationDecide> convertQuotationDecide(List<SaleQuotationItem> quotationItems) {
		List<QuotationDecide> decides = new ArrayList<QuotationDecide>();
		if (!CollectionUtils.isEmpty(quotationItems)) {
			for (SaleQuotationItem item : quotationItems)
				decides.add(new QuotationDecide(item));
		}
		return decides;
	}

}
