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

import com.uas.platform.b2b.dao.*;
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.erp.service.VendorService;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.Constant;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class QuotationServiceImpl implements QuotationService {

	@Autowired
	private ProductDao productDao;

	@Autowired
	private VendorDao vendorDao;

	@Autowired
	private SaleQuotationDao saleQuotationDao;

	@Autowired
	private EnterpriseDao enterpriseDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private VendorService vendorService;

	@Override
	public Map<String, List<SaleQuotationItem>> convertQuotation(List<Quotation> quotations) {
		Map<String, List<SaleQuotationItem>> mapSaleQuotationItem = new HashMap<String, List<SaleQuotationItem>>();
		List<SaleQuotationItem> saveItems = new ArrayList<SaleQuotationItem>();
		List<SaleQuotationItem> resItems = new ArrayList<SaleQuotationItem>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
        final String appId = "uas";// 应用来源
		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());
				Vendor vendor = null;
				if (vendors.size() > 0) {// 存在对应的供应商资料
					vendor = vendors.get(0);
					// 如果主动报价单中的客户联系人uu号为空 或 无效，则设为供应商资料中的客户联系人
					if (saleQuotation.getCustUserUU() == null) {
						saleQuotation.setCustUserUU(vendors.get(0).getMyUserUU());
					} else {
						List<User> custUsers = userDao.findByEnUUAndUserUU(saleQuotation.getCustUU(),
								saleQuotation.getCustUserUU());
						if (CollectionUtils.isEmpty(custUsers)) {
							saleQuotation.setCustUserUU(vendors.get(0).getMyUserUU());
						}
					}
					// 如果主动报价单中的供应商联系人uu号为空 或 无效，则设为供应商资料中的供应商联系人
					if (saleQuotation.getUserUU() == null) {
						saleQuotation.setUserUU(vendors.get(0).getVendUserUU());
					} else {
						List<User> vendUsers = userDao.findByEnUUAndUserUU(enUU, saleQuotation.getUserUU());
						if (CollectionUtils.isEmpty(vendUsers)) {
							saleQuotation.setUserUU(vendors.get(0).getVendUserUU());
						}
					}
				} else {// 不存在对应的供应商资料，增加供应商关系
					vendor = addVendor(saleQuotation);
					if (null != vendor) {
                        vendorService.addPartnerShipRecord(vendor, appId); // 添加供应商关系同时增加合作伙伴关系记录
					}
				}
				if (vendor != null && vendor.getMyEnUU() != null) {
					if (!CollectionUtils.isEmpty(saleQuotation.getQuotationItems())) {
						Iterator<SaleQuotationItem> it = saleQuotation.getQuotationItems().iterator();
						while (it.hasNext()) {
							SaleQuotationItem item = it.next();
							item.setQuotation(saleQuotation);
							// 取平台的产品ID
							Product product = item.getProduct();
							// 查找客户是否存在对应的物料号。
							List<Product> products = productDao.findByEnUUAndCode(vendor.getMyEnUU(),
									product.getCode());
							if (products.size() > 0) {
								item.setProduct(products.get(0));
								item.setProductId(products.get(0).getId());
								item.setErpDate(new Date());
								saveItems.add(item);
							} else {
								SaleQuotationItem resItem = new SaleQuotationItem();
								resItem.setQuotation(new SaleQuotation());
								resItem.setNumber(item.getNumber());
								resItem.getQuotation().setCode(saleQuotation.getCode());
								resItems.add(resItem);// 这里存储不能保存的明细，返回到erp,显示在备注中。
								it.remove();
							}
						}

					}
				}
			}
		}
		mapSaleQuotationItem.put("save", saveItems);
		mapSaleQuotationItem.put("res", resItems);
		return mapSaleQuotationItem;
	}

	@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;
	}

	@Override
	public List<Quotation> convertSaleQuotation(List<SaleQuotation> saleQuotations) {
		List<Quotation> quotations = new ArrayList<Quotation>();
		if (!CollectionUtils.isEmpty(saleQuotations)) {
			for (SaleQuotation saleQuotation : saleQuotations) {
				quotations.add(new Quotation(saleQuotation));
			}
		}
		return quotations;
	}

	/**
	 * 保存主动报价单时,增加供应商关系
	 * 
	 * @param saleQuotation
	 * @return
	 */
	private Vendor addVendor(SaleQuotation saleQuotation) {
		Vendor vendor = new Vendor();
		Long vendUU = SystemSession.getUser().getEnterprise().getUu();
		Long vendUserUU = saleQuotation.getUserUU();
		Long custUU = saleQuotation.getCustUU();
		Long custUserUU = saleQuotation.getCustUserUU();
		if (custUU != null) {// 客户UU号存在，增加供应商关系
			Enterprise cust = enterpriseDao.findOne(custUU);
			if (cust != null) {
				vendor.setVendEnUU(vendUU);
				vendor.setMyEnUU(custUU);
				vendor.setMyEnterprise(cust);
				if (custUserUU != null) {// 买方用户UU号存在且有效，既保留，否则设为买方企业的管理员UU号
					List<User> custUsers = userDao.findByEnUUAndUserUU(custUU, custUserUU);
					if (CollectionUtils.isEmpty(custUsers)) {
						vendor.setMyUserUU(cust.getEnAdminuu());
						saleQuotation.setCustUserUU(cust.getEnAdminuu());
					} else {
						vendor.setMyUserUU(custUserUU);
					}
				} else {
					vendor.setMyUserUU(cust.getEnAdminuu());
					saleQuotation.setCustUserUU(cust.getEnAdminuu());
				}

				if (vendUserUU != null) {// 卖方用户UU号存在且有效，既保留，否则设为卖方企业的管理员UU号
					List<User> vendUsers = userDao.findByEnUUAndUserUU(vendUU, vendUserUU);
					if (CollectionUtils.isEmpty(vendUsers)) {
						vendor.setVendUserUU(SystemSession.getUser().getEnterprise().getEnAdminuu());
						saleQuotation.setUserUU(SystemSession.getUser().getEnterprise().getEnAdminuu());
					} else {
						vendor.setVendUserUU(vendUserUU);
					}
				} else {
					vendor.setVendUserUU(SystemSession.getUser().getEnterprise().getEnAdminuu());
					saleQuotation.setUserUU(SystemSession.getUser().getEnterprise().getEnAdminuu());
				}
				vendor.setCustswitch(Constant.YES);
				vendor.setVendswitch(Constant.YES);
				vendor = vendorDao.save(vendor);// 保存
			} // 客户UU号存在但无效，不保存供应商关系
		} // 客户UU号不存咋，不保存供应商关系
		return vendor;
	}

}
