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

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

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

import com.uas.platform.b2b.dao.EnterpriseDao;
import com.uas.platform.b2b.dao.ProductDao;
import com.uas.platform.b2b.dao.PurchaseOrderDao;
import com.uas.platform.b2b.dao.PurchaseOrderItemDao;
import com.uas.platform.b2b.dao.UserDao;
import com.uas.platform.b2b.dao.VendorDao;
import com.uas.platform.b2b.erp.model.Purchase;
import com.uas.platform.b2b.erp.model.PurchaseDetailEnd;
import com.uas.platform.b2b.erp.model.PurchaseReply;
import com.uas.platform.b2b.erp.service.PurchaseService;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.Product;
import com.uas.platform.b2b.model.PurchaseOrder;
import com.uas.platform.b2b.model.PurchaseOrderAll;
import com.uas.platform.b2b.model.PurchaseOrderAllItem;
import com.uas.platform.b2b.model.PurchaseOrderItem;
import com.uas.platform.b2b.model.PurchaseOrderReply;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.model.Vendor;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.Status;

@Service
public class PurchaseServiceImpl implements PurchaseService {

	@Autowired
	private ProductDao productDao;
	@Autowired
	private VendorDao vendorDao;
	@Autowired
	private EnterpriseDao enterpriseDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private PurchaseOrderDao purchaseOrderDao;
	@Autowired
	private PurchaseOrderItemDao purchaseOrderItemDao;

	@Override
	public List<PurchaseOrderAllItem> convertPurchase(List<Purchase> purchases) {
		List<PurchaseOrderAllItem> orderItems = new ArrayList<PurchaseOrderAllItem>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (Purchase purchase : purchases) {
			// 先查看是否已存在
			List<PurchaseOrder> orders = purchaseOrderDao.findByEnUUAndCode(enUU, purchase.getPu_code());
			if (orders.size() == 0) {
				PurchaseOrderAll order = purchase.convert();//将order的UserUU set 为em_uu
				List<Vendor> vendors = vendorDao.findByMyEnUUAndVendUU(order.getEnUU(), order.getVendUU());
				Vendor vendor = null;
				if (vendors.size() == 0) {//供应商资料在平台上不存在
					vendor = addVendor(order);//添加企业的供应商资料
				} else {//供应商资料在平台上存在
					vendor = vendors.get(0);
				}
				if (vendor != null && !CollectionUtils.isEmpty(order.getOrderItems())) {//平台中存在供应商的UU&&单据有明细行
					if (order.getVendUserUU() == null && vendors.get(0).getVendorUser() != null)//单据不包含供应商联系人UU号&&供应商列表中有供应商联系人
						order.setVendUserUU(vendor.getVendorUser().getUserUU());//将供应商列表中的联系人设为单据的供应商联系人
					User user = order.getUser();//单据采购员
					if (order.getUserUU() != null) {//单据采购员uu不为空
						List<User> users = userDao.findUserByUserUU(order.getUserUU());//根据单据采购员uu获取users
						if (users.size() == 0)//平台中不存在单据采购员UU的用户
							user = addUser(user);//新增当前企业的一个user
						else//平台中存在单据采购员UU的用户
							user = users.get(0);
					} else {//单据采购员uu为空
						user = addUser(user);//新增当前企业的一个user
					}
					order.setUser(user);
					order.setUserUU(user.getUserUU());//如果单据包含平台存在的UU号，即为这个UU号，否则新增一个当前企业的user（UU序列生成）
					for (PurchaseOrderAllItem item : order.getOrderItems()) {
						item.setOrder(order);
						// 取平台的产品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());
						}
					}
					orderItems.addAll(order.getOrderItems());
				}
			}
		}
		return orderItems;
	}

	@Override
	public List<PurchaseReply> convertPurchaseOrderReply(List<PurchaseOrderReply> orderReplies) {
		List<PurchaseReply> replies = new ArrayList<PurchaseReply>();
		for (PurchaseOrderReply orderReply : orderReplies)
			replies.add(new PurchaseReply(orderReply));
		return replies;
	}

	/**
	 * 添加供应商资料
	 * 
	 * @param order
	 */
	private Vendor addVendor(PurchaseOrderAll order) {
		Vendor vendor = new Vendor();
		vendor.setMyEnUU(order.getEnUU());
		vendor.setMyUserUU(SystemSession.getUser().getUserUU());
		Enterprise enterprise = enterpriseDao.findOne(order.getVendUU());
		if (enterprise != null) {
			vendor.setVendorEnterprise(enterprise);
			vendor.setVendEnUU(order.getVendUU());
			if (order.getVendUserUU() != null) {
				List<User> users = userDao.findByEnUUAndUserUU(enterprise.getUu(), order.getVendUserUU());
				if (users.size() > 0) {
					vendor.setVendorUser(users.get(0));
					vendor.setVendUserUU(order.getVendUserUU());
				}
			}
			return vendorDao.save(vendor);
		}
		return null;
	}

	/**
	 * 添加用户
	 * 
	 * @param user
	 * @return
	 */
	private User addUser(User user) {
		user.setUserUU(null);
		user.setEnable(Constant.NO);
		Set<Enterprise> enterprises = new HashSet<Enterprise>();
		enterprises.add(SystemSession.getUser().getEnterprise());
		user.setEnterprises(enterprises);
		return userDao.save(user);
	}

	@Override
	public List<PurchaseOrderReply> convertPurchaseReply(List<PurchaseReply> replies) {
		List<PurchaseOrderReply> orderReplies = new ArrayList<PurchaseOrderReply>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (PurchaseReply reply : replies) {
			List<PurchaseOrderItem> items = purchaseOrderItemDao.findByEnUUAndOrderCodeAndNumber(enUU, reply.getPr_pucode(),
					reply.getPr_pddetno());
			if (!CollectionUtils.isEmpty(items)) {
				PurchaseOrderReply orderReply = reply.convert();
				orderReply.setOrderItem(items.get(0));
				orderReplies.add(orderReply);
			}
		}
		return orderReplies;
	}

	@Override
	public List<PurchaseOrderItem> convertPurchaseEnd(List<PurchaseDetailEnd> ends) {
		List<PurchaseOrderItem> orderItems = new ArrayList<PurchaseOrderItem>();
		long enUU = SystemSession.getUser().getEnterprise().getUu();
		for (PurchaseDetailEnd end : ends) {
			List<PurchaseOrderItem> items = purchaseOrderItemDao.findByEnUUAndOrderCodeAndNumber(enUU, end.getPd_code(), end.getPd_detno());
			if (!CollectionUtils.isEmpty(items)) {
				PurchaseOrderItem orderItem = items.get(0);
				orderItem.setEnd(end.getPd_ended());
				orderItem.setEndStatus((short) Status.NOT_UPLOAD.value());
				orderItems.add(orderItem);
			}
		}
		return orderItems;
	}
}
